19
votes

I've set up WebPack successfully - it's compiling my babel and SCSS files just fine, and I got the watch functionality to work fine. But I'd also like to work with the Hot Module Replacement - and I'm having difficulties getting it going. When I load the dev server in my browser it shows Cannot resolve module 'webpack/hot/dev-server'. My config looks like this:

import webpack from 'webpack';
import wpServer from 'webpack-dev-server';

var compiler = webpack({
    entry: [
        './src/core.js',
        'webpack/hot/dev-server'
    ],
    output: {
        path: outPath,
        filename: '[name].js'
    },
    resolveLoader: { root: path.join(MODULE_PATH, "node_modules") },
    module: {
        loaders: [
          { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
          { test: /\.scss$/, loader: "style!css!sass" }
        ]
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    watch: true
});

var server = new wpServer(compiler, {
    contentBase: outPath,
    hot: true,
    quiet: false,
    noInfo: false,
    lazy: true,
    filename: "main.js",
    watchDelay: 300,
    headers: { "X-Custom-Header": "yes" },
    stats: { colors: true },
});
server.listen(8080, "localhost", function() {});

and my index.html contains:

<script src="http://localhost:8080/webpack-dev-server.js"></script>
<script src='main.js'></script>

Does anyone have any ideas?

3
You cannot combine webpack-dev-server lazy mode with HMR. The lazy mode only recompiles when on HTTP request. HMR relies on watchers that recompile on change. Use lazy: false instead or just omit it. - Tobias K.
I've posted a small explanation about how HMR works and what's required to make it work: stackoverflow.com/questions/37016683/… - Johannes Ewald

3 Answers

14
votes

If you installed webpack-dev-server globally, which is npm install webpack-dev-server -g, try install it locally (just remove the option -g).

I solved this problem by doing so.

6
votes

IMPORTANT


If you are using [email protected] make sure you install

[email protected] 

Just running npm install webpack-dev-server won't play nice with webpack 2.

This will probably only be true while version 2 is still in beta.


I also struggled getting this working since the documentation on this topic is very fragmented.

Found this simple working example:

https://github.com/ahfarmer/webpack-hmr-starter-dev-server-api

Code is pretty self explanatory.

4
votes

I ran into a similar issue. I fixed it by installing webpack itself locally. To install webpack as a local dev dependency: npm i -D webpack