Skip to content

Instantly share code, notes, and snippets.

@kisenka
Last active February 16, 2017 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kisenka/836a47f9053647683cb3fb0f2a5ba82e to your computer and use it in GitHub Desktop.
Save kisenka/836a47f9053647683cb3fb0f2a5ba82e to your computer and use it in GitHub Desktop.
HotModuleReplacementPlugin doesn't generate hot update assets if it applies in child compilation
require('./styles.css');
const MultiEntryPlugin = require('webpack/lib/MultiEntryPlugin');
const JsonpTemplatePlugin = require("webpack/lib/JsonpTemplatePlugin");
const ChildCompiler = require('webpack-toolkit').ChildCompiler;
class Plugin {
apply(compiler) {
const host = compiler.options.devServer.host;
const port = compiler.options.devServer.port;
compiler.plugin('make', (compilation, done) => {
// This is just handy wrapper over the compilation.createChildCompiler(compilerName, outputOptions)
const childCompiler = new ChildCompiler(compilation);
// Original webpack child compiler instance
const originCompiler = childCompiler._compiler;
// Add Jsonp runtime to the bundle for proper updates receiving (see webpack/lib/JsonpMainTemplate.runtime.js)
originCompiler.apply(new JsonpTemplatePlugin());
// Add separate multi-entry with webpack-dev-server and HMR runtime
originCompiler.apply(
new MultiEntryPlugin(originCompiler.options.context, [
`webpack-dev-server/client/index?http://${host}:${port}`,
'webpack/hot/only-dev-server',
'./app'
], 'child-entry')
);
childCompiler.run()
.then(compilation => done())
.catch(done);
});
}
}
module.exports = Plugin;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Page with Hot module replacement</h1>
<script src="/main-entry.js"></script>
<script src="/child-entry.js"></script>
</body>
</html>
{
"name": "webpack-hot-module-replacement-with-child-compiler",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"css-loader": "^0.26.1",
"style-loader": "^0.13.1",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.3.0",
"webpack-toolkit": "^0.7.9"
}
}
body {
background-color: green;
}
const path = require('path');
const ChildCompilationPlugin = require('./child-compilation-plugin');
module.exports = {
entry: {
'main-entry': './app'
},
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].js',
pathinfo: true
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
},
devServer: {},
plugins: [
new ChildCompilationPlugin()
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment