即使在配置后 React 热加载也不起作用

React hot loading does not work even after configuration

安装了最新的 react-hot-loader

yarn add react-hot-loader@next

更新入口点:

entry: [
        'react-hot-loader/patch',
        'webpack-dev-server/client?http://localhost:8080',
        'webpack/hot/only-dev-server',
        './src/app.jsx'
    ],

添加 react-hot-loader/babel 到 babel 插件:

{
    test: /.jsx?$/,
    loader: 'babel-loader',
    include: path.resolve(__dirname, 'src'),
    exclude: /node_modules/,
    options: {
        presets: [['es2015', { modules: false }], 'react'],
        plugins: ['react-hot-loader/babel']
    }
},

添加了 HMR 插件

plugins: [
    new CopyWebpackPlugin([
        { from: 'src/index.html' }
    ]),
    new WriteFilePlugin(),
    new webpack.HotModuleReplacementPlugin()
],

使用过的 AppContainer

import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import Home from './components/home';

const render = Component => {
    ReactDOM.render(
        <AppContainer>
            <Home />
        </AppContainer>,
        document.getElementById('react')
    )
};

render(Home);

if (module.hot) {
    module.hot.accept('./components/home', () => render(Home));
}

而且还是不行。该页面会完全重新加载。

好的,经过一个小时的谷歌搜索和阅读,我想出了这个。使用 Webpack 2 及更高版本,应将以下配置添加到 devServer:

devServer: {
    contentBase: path.join(__dirname, 'dist'),
    hot: true
}

在我提到的 earlier Webpack documentation 中,它建议:

Make sure to use either the --hot flag, or the HotModuleReplacementPlugin in your webpack.config.js, but never both at the same time as in that case, the HMR plugin will actually be added twice, breaking the setup.