Hot Module Replacement
Hot module replacement
Live reload, but much better
FEM/01.6-hmr branch
The idea is that you don't have to manually refresh the page after having changed the code in one of your sub-modules. Especially frustrating, if you have to reset the UI state each time.
webpackHotUpdate
Webpack wraps webpackHotUpdate around your file. Anywhere your file is required, Webpack passes the webpackHotUpdate wrapper and not directly your file. webpackHotUpdate will send the updates.
Not very complicated to set up in fact
// **** bootstrap.js ****
/* eslint no-console:0 */
var app = require('./app')
var helpers = require('./helpers')
// this is only relevant when using `hot` mode with webpack
// special thanks to Eric Clemmons: https://github.com/ericclemmons/webpack-hot-server-example
// detects if hot reload is active
const reloading = document.readyState === 'complete'
// this (module.hot β) is the same object that has
// module.exports
// but supercharged by Webpack (monkey-patched)
// if the --hot flag is not present,
// this becomes dead code and is removed
if (module.hot) {
// you can accept one file
// or accept all files as here β
module.hot.accept(function(err) {
console.log('β HMR Error:', err)
})
// if accepted, then the file is reloaded
// in React this is great
// and while Reduc fits well with this
// state and view separate
if (reloading) {
console.log('π HMR Reloading.')
app.onLoad()
} else {
console.info('β
HMR Enabled.')
bootstrap()
}
} else {
console.info('β HMR Not Supported.')
bootstrap()
}
function bootstrap() {
helpers.$on(window, 'load', app.onLoad)
helpers.$on(window, 'hashchange', app.onLoad)
}
// **** package.json ****
..
"scripts": {
"prebuild": "rimraf dist",
"build": "webpack --env.prod -p",
"prebuild:dev": "rimraf dist",
"build:dev": "webpack --env.dev",
"start": "http-server",
// 1. ++++ add the --hot flag
"dev": "webpack-dev-server --env.dev --hot",
"debug": "node-nightly --inspect --debug-brk node_modules/.bin/webpack --env.debug",
..
Now you can see in the browser console that HMR is enabled. ( β$ npm run dev
β )Now, you can change any file and it will be hot reloaded in the browser.
If your doing React, then there's a loader that makes this even easier. It works great with NodeJS and Express (see comment above).
This only works with the Webpack Dev Server (and the
β--hot
β command line flag, or set it in the config)