react-hot-loader v3 + webpack v2之坑

.babelrc 文件的配置必须指定 module: false

1
2
3
4
5
6
7
8
9
{
"presets": [
["env", { "modules": false }],
"react"
],
"plugins": [
"react-hot-loader/babel"
]
}

相关解释:

Note that because webpack 2 has built-in support for ES2015 modules, you won’t need to re-require your root component in module.hot.accept.

https://webpack.js.org/guides/hmr-react/

几种实现方式

  1. 使用 npm scripts 执行 webpack-dev-server
1
2
3
"scripts": {
"dev": "webpack-dev-server --hot --history-api-fallback --open"
}

这种方式的完整代码:
https://github.com/xwillmadeit/webpack2-hmr/tree/master

  1. 在 webpack.config.js 中配置 devServer 参数
1
2
3
4
5
6
7
8
9
10
11
12
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
template: './index.html'
})
],
devServer: {
port: 8081,
contentBase: path.resolve(__dirname, 'dist'),
hot: true
}

注意:这种方式必须配置 hot: true,同时在插件中加入 new webpack.HotModuleReplacementPlugin()

这种方式的完整代码:
https://github.com/xwillmadeit/webpack2-hmr/tree/option2

  1. 使用 webpack-dev-middleware 和 webpack-hot-middleware
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// webpack.config.js
entry: {
app: [
'webpack-hot-middleware/client?reload=true',
'react-hot-loader/patch',
'./index.js'
]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]

// server.js
app.use(webpackMiddleware(compiler))
app.use(hotMiddleware(compiler))

完整代码:
https://github.com/xwillmadeit/webpack2-hmr/tree/middleware