在阅读了 Dan Abramov 的这篇Medium 帖子后,我使用 webpack 尝试了非常基本的 HMR(没有 react-hot-loader) 。
入口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'));
webpack 配置
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
}
}
我的问题是,为什么 React 应用程序的 HMR 只适用于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'))
呢?
包版本
"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7"