postinstall webpack not working on Heroku - node.js

I'm using Heroku to host my app and webpack to build it.
Basically, I'm trying to deploy my app, but it doesn't work at all.
The postinstall doesn't seem to occur since when I load the page it's missing the file bundle.js (which is built via webpack).
Here is my package.json scripts:
"main": "server.js",
"scripts": {
"dev": "webpack-dev-server --devtool eval --content-base build/ --colors --hot",
"start": "node server.js",
"postinstall": "webpack -p --config webpack.prod.config.js --progress"
}
When I push my project to heroku, there is no error displayed during the process. I can see in the console that it's running my postinstall:
remote: > pistou#1.0.0 postinstall /tmp/build_80dea0f9774d7a9a5f8f33ee9c913bca
remote: > webpack -p --config webpack.prod.config.js --progress
Here is my whole webpack.prod.config.js file:
var path = require('path');
var webpack = require('webpack');
var node_dir = path.resolve(__dirname, 'node_modules');
module.exports = {
entry: [
'unveil',
path.resolve(__dirname, 'app/main.js')
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'app'),
loader: 'babel'
},
{
test: /\.scss$/,
include: path.join(__dirname, 'app/styles'),
loader: 'style!css!sass'
},
{
test: /\.(png|jpg)$/,
loader: "file"
},
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" }
]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
}),
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /(fr|en)$/),
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": JSON.stringify("production")
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: false
}
}),
],
resolve: {
alias: {
"unveil": "./app/statics/jquery.unveil.js",
}
},
};

The --progress flag leads to a high number of print statements and log messages which heroku doesn't like and makes the process crash. Try to run without the --progress flag

Related

Webpack builds on production environment

In React JS starter kits like the one at https://github.com/wallacyyy/reactly-starter-kit, I see package.json files that have content like this:
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config ./webpack.prod.config.js --progress --colors",
...
},
"dependencies": {
"express": "^4.15.2",
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"webpack": "^2.2.1",
"webpack-dev-server": "^2.4.2"
}
The build script uses webpack to process the production build. How is it able to run on production when webpack is only a devDependency?
Webpack doesn't run on your production environment. Your build script just sets the NODE_ENV variable to equals production and thus letting Webpack and his plugins know they should prepare the bundle for production use. What exactly happens when you run this command depends on your webpack configuration, but among most common things would be code minification. You can also specify different kind of source maps and many other things. See https://webpack.js.org/guides/production/ for more information.
You keep both prod and dev webpack config. And in prod webpack config use definePlugin to set process.env.NODE_ENV as production ( you can also use other env variables ).
Now during transpiling and minification, NODE_ENV will be used in your vendor lib or in you app js.
'use strict';
var webpack = require('webpack');
var uglifyPlugin = new webpack.optimize.UglifyJsPlugin({
minimize: true,
comments: false
});
var definePlugin = new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
});
var commonChunkPlugin = new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
chunks: ['vendor', 'source'],
filename: 'vendor.bundle.js'
});
module.exports = {
context: __dirname + '/jsFolder',
entry: {
source: ['./app.jsx'],
vendor: [
'react',
'react-dom',
'redux',
'axios'
]
},
output: {
filename: "[name].bundle.js"
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
{
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['react', 'es2015', 'stage-0']
}
},
{ test: /\.css$/, loader: "css-loader" },
]
},
plugins: [commonChunkPlugin, definePlugin, uglifyPlugin],
node: {
console: true,
fs: 'empty',
net: 'empty',
tls: 'empty'
},
target: 'web'
};

How to set up react and nodeJS on your local machine(npm error)?

I'm new in React and nodeJS and I have some problems with webpack and npm. I've tried to configure my localhost based on this tutorial : https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm
When I write into the cmd: "npm start" it throws me the following message(on the picture). I've installed webpack but it says it doesn't recognise it. And what is a "weird error" by the way?
Can you give me some links, where I can properly config my machine?
My webpack.config.js file:
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2016', 'react']
}
}
]
}
}
module.exports = config;
package.json file:
{
"name": "reactApp",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "",
"license": "BSD"
}
The error message is in Hungarian I think, but from what I see I guess the system isn't able to find webpack-dev-server.
Try to install it locally using npm install --save-dev webpack-dev-server. Make sure it is there inside node_modules/.bin/webpack-dev-server. If your console says it can't find the command, try running node_modules/.bin/webpack-dev-server
Refer to this for more info regarding webpack-dev-server installation: https://webpack.js.org/guides/development/#webpack-dev-server
==================
edit: regarding the new error, as it says in the console, you need to add the suffix -loader to babelin your webpack.config.js
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2016', 'react']
}
}
]
}
}
module.exports = config;

npm start webpack issue?

I got mini app in react and trying to start it with npm start - package.json - "scripts": {
"start": "node server.js"
All works fine in windows but when trying to start this on Ubuntu console throws an error
/var/www/react_pwa/node_modules/webpack/lib/RuleSet.js:143
throw new Error("options/query cannot be used with loaders");
I've updated node.js and npm so I thik this might be webpack configuration issue. The file looks like this now
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'eval',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: 'index.html'
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src'),
query: {
"presets": [
"es2015",
"stage-0",
"react"
],
"plugins": [
"react-hot-loader/babel"
]
}
},
{
test: /\.css/,
loaders: ["style", "css"]
}]
}
};
Any ideas? Thanks.
Change loaders: ['babel'] to loader: 'babel' and it should work.
I don't think you can use query with multiple "loaders" because it doesn't know what query to attach to which loader.
You are probably missing a dependency in your package.json.
Have you installed react-hot-loader, css-loader, style-loader, babel-loader,babel-core, babel-preset-es2015,babel-preset-react,babel-preset-stage-0 ?
Try running this command to make sure:
npm install --save-dev react-hot-loader css-loader style-loader babel-loader babel-core babel-preset-es2015 babel-preset-react babel-preset-stage-0
Another thing you can do is ls node_modules in your windows setup and make sure all dependencies are in your package.json so you install them on npm install.

How to make Webpack and Node work together?

I was planning to use ES6 Modules on front-end so I did experiment on Webpack. However, I am having a hard time making the ff: work
Hot reload when there are changes in client-side
Hot reload when there are changes in server-side (before webpack, I'm using nodemon . and not have issues with it)
Losing debug/console.log info in terminal since it's printing the webpack status and nothing on the server e.g my custom 'Server running....' log.
The setup below I was trying to run via npm start. And everytime I make any change, I have to run npm start again
package.json
{
"name": "socket-io-chat",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "npm run build",
"build": "webpack -d && webpack-dev-server --hot --inline --watch && node --watch",
"build:prod": "webpack -p && webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.7.1",
"express": "*",
"socket.io": "*"
},
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-stage-2": "^6.13.0",
"nodemon": "^1.10.2",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.15.1"
}
}
webpack.config.js
var path = require("path");
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var SRC_DIR = path.join(__dirname, "public");
var DIST_DIR = path.join(__dirname, "public/js/dist");
var config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: {
guest : path.join(SRC_DIR, "entry-guest.js"),
authenticated : path.join(SRC_DIR, "entry-authenticated.js")
},
output: {
path: DIST_DIR,
filename: "[name].js"
},
modules: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["es2015", "stage-2"]
}
}
]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
devServer: {
https: false,
contentBase: SRC_DIR,
stats: 'errors-only',
port: 3000
}
};
module.exports = config;
server.js
//create server
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
console.log('here');
var server = require('http').createServer(app);
//prepare socket io, make it listen to server
var io = require('socket.io').listen(server);
users = [];
connections = [];
var port = process.env.PORT || 3000;
server.listen(port);
console.log(`Server running *:${port}`);
//routing
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
//open a connection
io.sockets.on('connection', function(socket) {
connections.push(socket);
console.log('Connected: %s sockets connected:', connections.length);
//...more codes here
});
In your webpack config file you can try using the plugin "Hot Module Replacement"
Along side with your already implemented Nodemon you should have both the client and server reloading on changes.
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
})
],
Here is an example webpack config utilizing HotModuleReplacement.
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3001',
'webpack/hot/only-dev-server',
path.resolve(__dirname, 'client', 'index.jsx')
],
output: {
path: path.resolve(__dirname, 'public'),
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
})
],
resolve: {
modules: [path.resolve(__dirname, 'node_modules')],
extensions: ['*', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
]
},
devServer: {
port: 3001,
contentBase: path.resolve(__dirname, 'public'),
hot: true,
historyApiFallback: true
},
devtool: 'source-map'
};

Deploying an app developed with babel-node

I have been using webpack for the first time, starting for a tutorial, but I'm stuck trying to deploy this to digital ocean.
I have been running the server during development by typing
npm start
Which calls:
babel-node devServer.js
This works fine for me locally, but when I try to run it on digital ocean it first works for a few minutes, then dies. I read somewhere that running babel-node on a live server isn't recommended, so I guess this is something to do with that.
I can see from this line in package.json :
"build:webpack": "NODE_ENV=production node_modules/webpack/bin/webpack.js --config webpack.config.prod.js",
that I should be doing some sort of deploy step, which I do, but I can still only get it to run using npm start, which uses babel-node devServer.js
How do I actually run this after doing the build? What am I doing wrong?
From package.json:
"scripts": {
"build:webpack": "NODE_ENV=production node_modules/webpack/bin/webpack.js --config webpack.config.prod.js",
"build": "npm run clean && npm run build:webpack",
"test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js \"test/**/*#(.js|.jsx)\"",
"clean": "rimraf dist",
"start": "babel-node devServer.js",
"tunnel": "browser-sync start --proxy localhost:7770 --tunnel wesbos",
"test:watch": "npm run test -- --watch"
},
My dev config:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
'./client/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
root: [
path.resolve('./client')
],
alias: {
},
},
module: {
loaders: [
// js
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'client')
},
// CSS
{
test: /\.styl$/,
include: path.join(__dirname, 'client'),
loader: 'style-loader!css-loader!stylus-loader'
}
]
}
};
Prod config:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'./client/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': "'production'"
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
],
resolve: {
root: [
path.resolve('./client')
],
alias: {
},
},
module: {
loaders: [
// js
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'client')
},
// CSS
{
test: /\.styl$/,
include: path.join(__dirname, 'client'),
loader: 'style-loader!css-loader!stylus-loader'
}
]
}
};
You could try using babel-loader and running the build script in npm start
In your package.json:
"start": "npm run build && babel-node --presets es2015 devServer.js"
Also include the following dependencies in your package.json:
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
In your webpack.config:
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]

Resources