按照webpack官网的文档尝试HMR,遇到了文档中Gotchas所提到的dom事件没有更新的问题,但用他给出的方法并没有解决。即修改print.js的输出内容并不会改变btn的click事件
事实上,我并没有理解module.hot.accept的意思,我尝试在它里面输出print.js的printMe方法,发现即使修改printMe,输出的也没有变化
配置和代码完全按照官方写的,如下:
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ClearnWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
app: './src/index.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
hot: true,
publicPath: '/'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new ClearnWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Output Management'
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
index.js
import _ from 'lodash';
import printMe from './print';
import './style.css';
function component() {
var element = document.createElement('div');
var btn = document.createElement('button');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
btn.innerHTML = 'Click me and check the console!';
btn.onclick = printMe;
element.appendChild(btn);
return element;
}
let element = component();
if (module.hot) {
module.hot.accept('./print.js', function() {
console.log('Accepting the updated printMe module!');
document.body.removeChild(element);
element = component();
document.body.appendChild(element);
});
}
print.js
export default function printMe() {
console.log('Updating print.js...')
}
试下这个