webpack3 官方guides中的热更新失败!

按照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...')
}
阅读 3.1k
2 个回答

试下这个

...
module.hot.accept('./print', function() {
...

要检查 package.json 里面的依赖装了 webpack-dev-server没

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题