With my current configuration of node and webpack, I am able to run the dev-server and develop my application.
I am however unable to create the static bundle.js that i could use for a deployment on my website.
How can I configure my webpack.js files and package.json command to make it build the required bundle file ?
When I run npm build, nothing happens
When I run npm deploy, i get the following error message :
Usage: npm <command>
where <command> is one of:
access, add-user, adduser, apihelp, author, bin, bugs, c,
cache, completion, config, ddp, dedupe, deprecate, dist-tag,
dist-tags, docs, edit, explore, faq, find, find-dupes, get,
help, help-search, home, i, info, init, install, issues, la,
link, list, ll, ln, login, logout, ls, outdated, owner,
pack, ping, prefix, prune, publish, r, rb, rebuild, remove,
repo, restart, rm, root, run-script, s, se, search, set,
show, shrinkwrap, star, stars, start, stop, t, tag, team,
test, tst, un, uninstall, unlink, unpublish, unstar, up,
update, upgrade, v, verison, version, view, whoami
npm <cmd> -h quick help on <cmd>
npm -l display full usage info
npm faq commonly asked questions
npm help <term> search for help on <term>
npm help npm involved overview
Specify configs in the ini-formatted file:
C:\Users\Sébastien\.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config
Following is my configuration :
package.json
{
"license": "UNLICENSED",
"private": true,
"version": "1.0.0",
"webPath": "web/",
"nodePath": "node_modules/",
"devDependencies": {
"autoprefixer": "^6.3.1",
"exports-loader": "^0.6.2",
"grunt": "^0.4.5",
"grunt-autoprefixer": "^3.0.3",
"grunt-contrib-concat": "^0.5.1",
"grunt-contrib-cssmin": "^0.14.0",
"grunt-contrib-less": "^1.1.0",
"grunt-contrib-uglify": "^0.11.0",
"grunt-contrib-watch": "^0.6.1",
"grunt-css-url-rewrite": "^0.3.5",
"grunt-cssjoin": "^0.3.0",
"grunt-postcss": "^0.7.1",
"imports-loader": "^0.6.5",
"matchdep": "^1.0.0",
"redux-devtools": "^3.0.2",
"redux-devtools-dock-monitor": "^1.0.1",
"redux-devtools-log-monitor": "^1.0.4",
"webpack-shell-plugin": "^0.4.2"
},
"repository": {
"type": "git",
"url": ""
},
"dependencies": {
"babel-core": "^6.4.0",
"babel-loader": "^6.2.1",
"babel-plugin-transform-runtime": "^6.4.3",
"babel-polyfill": "^6.3.14",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"babel-runtime": "^6.3.19",
"grunt-postcss": "^0.7.1",
"history": "^1.17.0",
"i18next": "^2.5.1",
"isomorphic-fetch": "^2.2.1",
"lodash": "^4.11.1",
"radium": "^0.16.2",
"rc-switch": "^1.4.2",
"react": "^0.14.6",
"react-dom": "^0.14.6",
"react-hot-loader": "^1.3.0",
"react-redux": "^4.1.2",
"react-router": "^1.0.3",
"react-router-redux": "^3.0.0",
"redux": "^3.1.6",
"redux-thunk": "^2.1.0",
"selfupdate": "^1.1.0",
"webpack": "^1.12.11",
"webpack-dev-server": "^1.14.1",
"whatwg-fetch": "^0.11.0"
},
"scripts": {
"start": "node webpack.dev-server.js",
"build": "webpack",
"deploy": "NODE_ENV=production webpack -p --config webpack.production.config.js"
}
}
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.join(__dirname, 'node_modules');
var devFlagPlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});
console.log(__dirname);
var config = {
entry: [
'babel-polyfill',
'webpack-dev-server/client?http://127.0.0.1:3000',
'webpack/hot/only-dev-server',
'./app/Resources/react/app.js'
],
output: {
path: path.join(__dirname, 'web/js'),
filename: 'bundle.js',
publicPath: 'http://127.0.0.1:3000/static/'
},
debug: true,
devtool: 'eval',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
devFlagPlugin
],
module: {
loaders: [
{
loaders: ["react-hot","babel-loader?plugins=transform-runtime&presets[]=es2015&presets[]=stage-0&presets[]=react"],
test: /\.js$/,
include: path.join(__dirname, 'app/Resources/react')
}
]
}
};
module.exports = config;
/*
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
})
*/
webpack.dev-server.js
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
quiet: false,
noInfo: false,
contentBase: "./assets"
}).listen(3000, 'localhost', function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3000');
});
webpack.production.config.js
var path = require('path');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var config = {
entry: [
'babel-polyfill',
'./app/Resources/react/app.js'
],
output: {
path: path.join(__dirname, 'web/js'),
filename: 'bundle.js'
},
module: {
loaders: [
{
loaders: ["babel-loader?plugins=transform-runtime&presets[]=es2015&presets[]=stage-0&presets[]=react"],
test: /\.js$/,
include: path.join(__dirname, 'src/react')
}
]
}
};
module.exports = config;
you missed run
npm run deploy
run is required for all scripts. To help with common tasks npm knows how to use several preconfigured scripts such as start and test which is why npm start is an equivalent of npm run start.
Related
I have been struggling with an issue with hot reloading where making edits in certain files would reload the app without those changes.
My initial solution was to update webpack and related modules. The first module I updated was webpack-dev-server. I went from v3 to v4 which immediately broke the app. All images and json files were getting 404'd when running the dev server.
Here is the original package.json:
{
...
"scripts": {
"dev": "set NODE_ENV=development && webpack serve --config config/webpack.dev.js --open",
"build": "set NODE_ENV=production && webpack --config config/webpack.prod.js",
"beatmarkers": "babel-node fetchAndFormatData/fetchAndFormatBeatMarkers.js"
},
"devDependencies": {
"#babel/cli": "^7.14.3",
"#babel/core": "^7.14.3",
"#babel/node": "^7.14.2",
"#babel/preset-env": "^7.14.4",
"clean-webpack-plugin": "^4.0.0-alpha.0",
"css-loader": "^5.2.6",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.1",
"lodash.clonedeep": "^4.5.0",
"node-fetch": "^2.6.1",
"node-sass": "^6.0.0",
"sass-loader": "^11.1.1",
"style-loader": "^2.0.0",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.7.3"
},
"dependencies": {
"bezier-easing": "^2.1.0",
"howler": "^2.2.3",
"pixi.js": "^6.2.0"
}
}
Here are the original webpack config files:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app.js',
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '../src/template.html')
})
],
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg|ico|pvr|mp3|fnt)$/,
type: 'asset/resource'
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
}
]
}
};
const { merge } = require('webpack-merge');
const common = require('./webpack.common');
module.exports = merge(common, {
mode: 'development',
devServer: {
historyApiFallback: true,
},
output: {
publicPath: '/'
},
devtool: "source-map"
});
This configuration produces a sources structure in chrome that looks like this:
localhost:8080
main.js
(index)
assets/images
animations
fonts
interface
When I updated webpack-dev-server to the latest version, 4.11.1, the assets/images folder no longer exists. I haven't be able to figure out how to get it back. Any help would be deeply appreciated.
I am learning to use webpack to develop a react project, but I cannot start local services locally. It reports the following error.
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import App from './App';
|
> ReactDOM.render(<App />, document.getElementById('root'));
|
I suspect this is a babel compilation problem, but I have configured babel-loader, but it does not work. I Googled this issue for a long time, but I still didn't find the problem. Can you help me? Thanks!
And this is my configuration files.
// webpack.common.js
const path = require('path');
const commonConfig = {
entry: [
'babel-polyfill',
'../src/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'dist/index.html')
})
],
module: {
rules: [{
test: /\.(jsx?|tsx?)$/,
loader: 'babel-loader',
exclude: /node_modules/,
}]
}
};
module.exports = commonConfig;
// webpack.dev.js
const merge = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
const path = require('path');
const devConfig = merge(commonConfig, {
mode: 'development',
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000
}
})
module.exports = devConfig;
// package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server",
},
"devDependencies": {
"#babel/core": "^7.11.4",
"#babel/preset-env": "^7.11.0",
"#babel/preset-react": "^7.10.4",
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^4.3.0",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1"
// .babelrc
{
"presets": ["env", "react"]
}
I found out where the problem was. I didn’t specify the webpack.dev.js file for the npm run start command in the scripts of package.json, and it worked after making the following changes.
"scripts": {
"start": "webpack-dev-server --config webpack/webpack.dev.js",
},
When I run npm run build in my directory, to get all my files bundled into bundle.js, I find this error: ERROR in ./bundle.js from UglifyJs \n Unexpected token name «key», expected punc «;» [./bundle.js:8141,13].
So I went to bundle.js line 8141 and found this: for (let key in val) {
And therein lies the problem: let. Uglify cannot deal with let and const
So I've looked through the entire bundle.js file and the ONLY time let appears is literally right there, and a couple lines down, and I know specifically what package that code comes from: npm install clone-deep
None of the other packages I'm using are having this issue, they are all correctly converted from es6 before uglify runs, and I use let and const in my own code all the time. This one package only is causing me the issue.
Here's my package.json
{
"name": "jsx2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "",
"license": "ISC",
"dependencies": {
"autobind-decorator": "^2.1.0",
"axios": "^0.18.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"classnames": "^2.2.5",
"clone-deep": "^4.0.1",
"prop-types": "^15.6.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-toastify": "^4.5.2",
"webpack": "^3.11.0"
},
"scripts": {
"dev": "webpack -d --watch",
"build": "webpack -p --config webpack.build.config.js"
}
}
And here's my webpack.build.config.js
// https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'out/');
var APP_DIR = path.resolve(__dirname, 'src/');
var config = {
entry: ['babel-polyfill', APP_DIR + '/App.jsx'],
output: {
path: BUILD_DIR,
filename: './bundle.js'
//https://cloud.githubusercontent.com/assets/593571/20785959/290f7fbc-b7b4-11e6-9ad2-7dafd7803552.png
//https://github.com/babel/babel-loader/issues/93
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel-loader',
options: {
"presets" : ["env", "react"],
"plugins": ["transform-decorators-legacy"]
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
}
};
module.exports = config;
-- edit
Just to confirm, I did actually go into clone-deep index.js and change the lets to vars, and it all worked and I got no errors. I don't really consider that as a solution, because... there's no reason why this one package should have this error and nothing else. But it is definitely this one package that is the source of the issue.
Some npm packages have no es5 version. We have to accept this or use other packages.
If you want to continue to use clone-deep, you have to add this package to include property of your babel-loader config:
...
{
test : /\.jsx?/,
include : [APP_DIR, path.resolve(__dirname, 'node_modules', 'clone-deep')],
loader : 'babel-loader',
options: {
"presets" : ["env", "react"],
"plugins": ["transform-decorators-legacy"]
}
};
...
You can read more in this issue
I'm developping an application using React, and webpack as the module bundler for the client part. For the server, I'm using Express.js.
For the client, I'm using webpack.config.dev.js for the configuration, and I use npm start to start a web server at localhost:3000.
For the server, I have the app.js file, and I use node bin/www to start the express server, but I have to give a different port to start the server, in this case, localhost:3100.
I have only a package.json for both, client, and server.
Is there a way to deploy both client and server in the same domain? If so, how can I do it? I would like from my client code to reference the endpoint as: /data/users, instead of doing localhost:3100/data/users.
See webpack config, express config, and package.json below (in case it helps):
webpack.config.dev.js:
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import autoprefixer from 'autoprefixer';
let node_dir = __dirname + '/node_modules';
let app_dir = __dirname + '/app';
export default {
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
'jquery': node_dir + '/jquery/dist/jquery.js',
'jquery-validation': node_dir + '/jquery-validation/dist/jquery.validate.js',
'jquery-placeholder': node_dir + '/jquery-placeholder/jquery.placeholder.js',
'jquery-oauth': node_dir + '/jquery-oauth/dist/jquery.oauth.js',
'bootstrap': node_dir + '/bootstrap/dist/js/bootstrap.min.js',
'owlcarousel':node_dir+'/owlcarousel/owl-carousel/owl.carousel.min.js',
'modernizr':node_dir + '/npm-modernizr/modernizr.js',
'jquery-shuffle':node_dir + '/shufflejs/dist/shuffle.js' ,
'jquery-stellar':node_dir + '/jquery.stellar/jquery.stellar.js',
'jquery-touchswipe':node_dir + '/jquery-touchswipe/jquery.touchSwipe.min.js'
},
modulesDirectories: ['js', 'node_modules']
},
debug: true,
devtool: 'cheap-module-eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
noInfo: true, // set to false to see a list of every file being bundled.
context: app_dir + "/app",
entry: {
// must be first entry to properly set public path
app: [app_dir+'/webpack-public-path',
'webpack-hot-middleware/client?reload=true',
app_dir+'/index']
},
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
// path: `${__dirname}/src`, // Note: Physical files are only output by the production build task `npm run build`.
path: `${__dirname}/app`,
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("package.json", ["main"])
),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'), // Tells React to build in either dev or prod modes. https://facebook.github.io/react/downloads.html (See bottom)
__DEV__: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({ // Create HTML file that includes references to bundled CSS and JS.
//template: 'src/index.ejs',
template: app_dir+'/index.html',
minify: {
removeComments: true,
collapseWhitespace: true
},
inject: true
}),
new webpack.ProvidePlugin({
$: "jquery",
jquery: "jquery",
"windows.jQuery": "jquery",
jQuery:"jquery",
}),
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js', Infinity)
],
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel']},
{test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
{test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, 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: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
{test: /\.ico$/, loader: 'file?name=[name].[ext]'},
{test: /(\.css|\.scss)$/, loaders: ['style', 'css?sourceMap', 'postcss', 'sass?sourceMap']},
]
},
postcss: ()=> [autoprefixer]
};
app.js for the server side:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And package.json:
{
"name": "dario-webapplication",
"version": "1.0.0",
"description": "Webapplication for Dario project",
"engines": {
"npm": ">=3"
},
"scripts": {
"server": "nodemon ./server/bin/www",
"preinstall": "node tools/nodeVersionCheck.js",
"setup": "node tools/setup/setupMessage.js && npm install && node tools/setup/setup.js",
"remove-demo": "babel-node tools/removeDemo.js",
"start-message": "babel-node tools/startMessage.js",
"prestart": "npm-run-all --parallel start-message remove-dist",
"start": "npm-run-all --parallel open:app lint:watch server",
"open:app": "babel-node tools/srcServer.js",
"open:dist": "babel-node tools/distServer.js",
"lint": "esw webpack.config.* app tools --color",
"lint:watch": "npm run lint -- --watch",
"clean-dist": "npm run remove-dist && mkdir dist",
"remove-dist": "rimraf ./dist",
"prebuild": "npm run clean-dist && npm run lint && npm run test",
"build": "babel-node tools/build.js && npm run open:dist",
"test": "mocha tools/testSetup.js \"app/**/*.spec.js\" --reporter progress",
"test:cover": "babel-node node_modules/isparta/bin/isparta cover --root app --report html node_modules/mocha/bin/_mocha -- --require ./tools/testSetup.js \"app/**/*.spec.js\" --reporter progress",
"test:cover:travis": "babel-node node_modules/isparta/bin/isparta cover --root app --report lcovonly _mocha -- --require ./tools/testSetup.js \"app/**/*.spec.js\" && cat ./coverage/lcov.info | node_modules/coveralls/bin/coveralls.js",
"test:watch": "npm run test -- --watch",
"open:cover": "npm run test:cover && open coverage/index.html"
},
"author": "Francisco Jose Parra Gonzalez",
"license": "MIT",
"dependencies": {
"bootstrap": "3.3.7",
"imports-loader": "0.6.5",
"jquery": "^1.11.1",
"jquery-oauth": "2.1.3",
"jquery-placeholder": "2.3.1",
"jquery-touchswipe": "1.6.15",
"jquery-ui": "^1.10.4",
"jquery-validation": "1.15.1",
"jquery.easing": "^1.3.2",
"jquery.stellar": "0.6.2",
"lightgallery": "1.2.21",
"npm-modernizr": "2.8.3",
"object-assign": "4.1.0",
"owlcarousel": "1.3.3",
"react": "15.3.0",
"react-bootstrap": "0.30.3",
"react-dom": "15.3.0",
"react-redux": "4.4.5",
"react-router": "2.6.1",
"react-router-redux": "4.0.5",
"redux": "3.5.2",
"redux-thunk": "2.1.0",
"shufflejs": "4.0.1",
"throttle-debounce": "1.0.1",
"body-parser": "~1.15.1",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"express": "~4.13.4",
"express-validator": "^2.20.8",
"jade": "~1.11.0",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0"
},
"devDependencies": {
"autoprefixer": "6.4.0",
"babel-cli": "6.11.4",
"babel-core": "6.11.4",
"babel-loader": "6.2.4",
"babel-plugin-react-display-name": "2.0.0",
"babel-plugin-transform-react-remove-prop-types": "0.2.9",
"babel-preset-es2015": "6.9.0",
"babel-preset-react": "6.11.1",
"babel-preset-react-hmre": "1.1.1",
"babel-preset-stage-1": "6.5.0",
"babel-register": "6.11.6",
"browser-sync": "2.14.0",
"chai": "3.5.0",
"chalk": "1.1.3",
"connect-history-api-fallback": "1.2.0",
"coveralls": "2.11.12",
"cross-env": "2.0.0",
"css-loader": "0.23.1",
"enzyme": "2.4.1",
"eslint": "3.2.2",
"eslint-plugin-import": "1.12.0",
"eslint-plugin-jsx-a11y": "2.0.1",
"eslint-plugin-react": "6.0.0",
"eslint-watch": "2.1.14",
"extract-text-webpack-plugin": "1.0.1",
"file-loader": "0.9.0",
"html-webpack-plugin": "2.22.0",
"isparta": "4.0.0",
"mocha": "3.0.1",
"mockdate": "1.0.4",
"node-sass": "3.8.0",
"npm-run-all": "2.3.0",
"open": "0.0.5",
"postcss-loader": "0.9.1",
"prompt": "1.0.0",
"react-addons-test-utils": "15.3.0",
"redux-immutable-state-invariant": "1.2.3",
"replace": "0.3.0",
"rimraf": "2.5.4",
"sass-loader": "4.0.0",
"sinon": "1.17.5",
"sinon-chai": "2.8.0",
"style-loader": "0.13.1",
"url-loader": "0.5.7",
"webpack": "1.13.1",
"webpack-dev-middleware": "1.6.1",
"webpack-hot-middleware": "2.12.2",
"webpack-md5-hash": "0.0.5"
},
"keywords": [],
"repository": {
"type": "git",
"url": ""
}
}
Maybe these boilerplate can help you.
And here in line 37 is what you looking for.
What initially gets run is bin/server.js, which does little more than enable ES6 and ES7 awesomeness in the server-side node code. It then initiates server.js. In server.js we proxy any requests to /api/* to the API server, running at localhost:3030. All the data fetching calls from the client go to /api/*. Aside from serving the favicon and static content from /static, the only thing server.js does is initiate delegate rendering to react-router. At the bottom of server.js, we listen to port 3000 and initiate the API server.
I'm using webpack for my build which works without any problems using the webpack-dev-server (npm run watch), however when I try to create a production build (npm run build) I seem to get the error in the console when I try to load the website and nothing shows up at all on-screen.
Uncaught Error: [HMR] Hot Module Replacement is disabled.
I have a few questions about this:
My understanding of using Hot Module Replacement is that its designed for making life easier during development, it should not be used in production deployments. Is that correct?
Given the below, why is Hot Module Replacement is being used? I don't see what's driving it.
What's the best practice when it comes to production builds, should I have a separate webpack config for prod and dev? Ideally I'd like to make use of a single config purely to ease maintenance.
package.json
{
// ...
"scripts": {
"build": "webpack --progress --colors --production",
"watch": "webpack-dev-server --inline --hot --progress --colors"
},
"dependencies": {
"bootstrap": "^3.3.6",
"bootstrap-sass": "^3.3.6",
"bootstrap-webpack": "0.0.5",
"extract-text-webpack-plugin": "^1.0.1",
"html-webpack-plugin": "^2.15.0",
"jquery": "^2.2.3",
"node-sass": "^3.4.2",
"react": "^15.0.1",
"react-bootstrap": "^0.28.5",
"react-dom": "^15.0.1",
"react-redux": "^4.4.1",
"react-router": "^2.0.1",
"react-router-redux": "^4.0.1",
"redux": "^3.3.1",
"redux-thunk": "^2.0.1",
"webpack": "^1.12.14"
},
"devDependencies": {
"babel-core": "^6.7.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.23.1",
"exports-loader": "^0.6.3",
"file-loader": "^0.8.5",
"imports-loader": "^0.6.5",
"less": "^2.6.1",
"less-loader": "^2.2.3",
"redux-devtools": "^3.2.0",
"redux-logger": "^2.6.1",
"sass-loader": "^3.2.0",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack-dev-server": "^1.14.1"
}
}
webpack.config.js
var webpack = require('webpack');
var htmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
module.exports = {
entry: [
'webpack/hot/only-dev-server',
path.resolve(__dirname, 'app/index.js')
],
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015', 'react' ] } },
{ test: /\.scss$/, loader: 'style!css!sass?includePaths[]=' + path.resolve(__dirname, './node_modules/bootstrap-sass/assets/stylesheets/') },
{ test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader: 'file' }
]
},
resolve: {
modulesDirectories: ['node_modules']
},
plugins: [
new webpack.NoErrorsPlugin(),
new htmlWebpackPlugin({
filename: 'index.html',
template: './index.html',
inject: false
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.optimize.OccurenceOrderPlugin()
]
};
You need to enable the HMR plugin. Add the HotModuleReplacementPlugin to your plugins array in you webpack.config. You can have a separate webpack.config for dev and production.
Something like
plugins: [
new webpack.NoErrorsPlugin(),
new htmlWebpackPlugin({
filename: 'index.html',
template: './index.html',
inject: false
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin()
]
It's not a particularly good idea to include the hot loading bits in a production build. They are practically useless there and just bloat your file size.
There are multiple strategies on how to deal with this. Some people separate their webpack configuration per file and then point to it through --config. I prefer to maintain a single file and branch through npm. I use webpack-merge to share configuration between branches (disclaimer: I'm the author).
I got this error due to the fact that I had code like this in webpack.config.js.
devServer: {
...
hot: true,
inline: true
}
Used the command webpack-dev-server --hot --inline instead and then I did not have to bloat my config with new webpack.HotModuleReplacementPlugin().
https://github.com/webpack/webpack/issues/1151#issuecomment-111972680
You will need to enable Hot Module Replacement feature to have it working e.g:
webpack.config.js
module.exports = {
//...
devServer: {
hot: true
},
plugins: [
//...
new webpack.HotModuleReplacementPlugin()
]
};
From webpack:
Note that webpack.HotModuleReplacementPlugin is required to fully enable HMR. If webpack or webpack-dev-server are launched with the --hot option, this plugin will be added automatically, so you may not need to add this to your webpack.config.js. See the HMR concepts page for more information.
As said, otherwise you can enable it through package.json add --hot to your script e.g.
"start": "webpack-dev-server --hot",