【发布时间】:2018-03-12 03:43:09
【问题描述】:
我的 webpack 热模块替换工作正常了。有人告诉我,一旦它开始工作,我将不再需要对我的代码进行完全刷新。不是这种情况!当我更改我的代码时,我仍然需要刷新! (App.js)。
如何正确启用 webpack HMR?
链接到github上的项目
这是我的切入点
import './styles/index.css';
import App from './components/App';
import React from 'react';
import { render } from 'react-dom';
const rootDOMNode = document.getElementById('app');
function renderRoot() {
render(<App/>, rootDOMNode);
}
renderRoot();
if (module.hot) {
module.hot.accept('./components/App', () => {
console.log('Accepting the updated module');
renderRoot();
});
}
webpack.config.js:
const webpack = require("webpack");
const path = require("path");
const CleanWebpackPlugin = require( "clean-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: [
"./app/index"
],
devtool: "inline-source-map",
output: {
path: path.resolve(__dirname, "dist"), // Note: Physical files are only output by the production build task `npm run build`.
publicPath: "/",
filename: "bundle.js"
},
devServer: {
contentBase: path.resolve(__dirname, "dist"),
hot: true,
port: 3000,
open: true,
compress: true
},
plugins: [
new ExtractTextPlugin({
disable: false,
filename: "css/style.css",
allChunks: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
module: {
rules: [
{ test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
} },
// { test: /(\.css)$/, use: ["style-loader", "css-loader"] },
{ test: /(\.css)$/, use: ExtractTextPlugin.extract(["css-loader"]) },
{ test: /\.(png|svg|jpg|gif)$/, use: ["file-loader"] },
// for fonts
{ test: /\.(woff|woff2|eot|ttf|otf)$/, use: ["file-loader"] }
]
}
};
【问题讨论】:
-
我不使用 React,但我使用 HMR。您需要记住的一件事是呼叫方也需要很热。我发现最好的办法是确保所有单元都有 hot.accept。您可以使用一个 webpack 插件来执行此操作 -> github.com/loggur/webpack-module-hot-accept
-
以 React 知道需要重新渲染的方式添加 react-hot-loader
标签: javascript reactjs webpack ecmascript-6