在阅读Dan Abramov的Medium post之后,我尝试了使用webpack的非常基本的HMR(没有react-hot-loader) .

Entry index.js

import React from 'react';
import { render } from 'react-dom';

import App from './App';

if(module.hot) {
  // Basic HMR for React without using react-loader

  // module.hot.accept('./App', () => {
  //   const UpdatedApp = require('./App').default;
  //
  //   render(<UpdatedApp />, document.getElementById('app'));
  // });

  // Why does this work as well?
  module.hot.accept();
}

render(<App />, document.getElementById('app'));

The webpack config

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  entry: [
    'webpack-dev-server/client?http://localhost:8081',
    'webpack/hot/only-dev-server',
    './src/js/index.js'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [{ loader: 'babel-loader' }]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({ template: 'src/index.html' }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin()
  ],
  devServer: {
    hot: true
  }
}

我的问题是,为什么HMR for React应用程序仅适用于 module.hot.accept()

据我所知,webpack的HMR只提供了一个简单的API来检测文件的变化 . 如何处理这些更改取决于加载器 . 样式加载器处理 .css 文件 . 并且,在React应用程序的上下文中,对 .js 模块的更改可能由react-hot-loader管理 .

或者,根据Medium post,可以像这样管理它们:

render(<UpdatedApp />, document.getElementById('app'))

那么为什么只做 module.hot.accept() 给出与做 render(<UpdatedApp />, document.getElementById('app')) 相同的结果?

Package verisons

"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7"