将文件移动到 /app 文件夹后 HMR 不工作

HMR isn't working after moving files to /app folder

你好,我目前正在尝试学习如何将 express 与 webpacks HMR 一起使用,每次我更新和保存文件时都会出现错误:

"The following modules couldn't be hot updated: (Full reload needed)" "./app/components/App.js"

我当前的配置文件有问题吗?

所以我的目录结构是这样的:

todos
    |
    app
      |
    package.son
    server.js
    webpack.config.js

我有一个 webpack.config.js 文件和一个 server.js 文件,如下所示:

var path = require('path');
var webpack = require('webpack');


module.exports = {
  context: path.join(__dirname + "/app"),

  entry: ['./index'],
  output: {
    path: "/bundle",
    publicPath: '/static/',
    filename: "bundle.js"
  },
  module: {
    loaders: [
     {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          presets: ['react', 'es2015']
        }
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  }

};

server.js

var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.config')

var app = new (require('express'))()
var port = 3000

var compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
app.use(webpackHotMiddleware(compiler))

app.get("/", function(req, res) {
  res.sendFile(__dirname + '/app/index.html')
})

app.listen(port, function(error) {
  if (error) {
    console.error(error)
  } else {
    console.info("==>   Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
  }
})

你试过接受模块吗?在 Webpack HMR documentation 中,它表示如下:

A module can only be updated if you “accept” it. So you need to module.hot.accept the module in the parents or the parents of the parents. For example, a router or a subview would be a good place.

在您的 index.js 文件或您希望 HMR 重新加载的任何模块中尝试此操作:

if (module.hot) {  
 module.hot.accept();
}