React + Webpack HMR刷新页面(不热装) [英] React + Webpack HMR is refreshing the page (not hot loading)

查看:435
本文介绍了React + Webpack HMR刷新页面(不热装)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使反应热的webpack加载程序正常工作时遇到了一些麻烦。

I'm having a bit of trouble getting the react-hot webpack loader to work correctly.

当我加载页面时,我得到以下内容,正如我所料:

When I load the page I get the following as I would expect:


[HMR]等待来自WDS的更新信号...

[WDS]启用热模块更换。

[HMR] Waiting for update signal from WDS...
[WDS] Hot Module Replacement enabled.

但是当我保存更改时,页面会自动刷新浏览器(而不是更换HMR)。

But when I save a change the page automatically hard refreshes the browser (rather than a HMR replacement).

//webpack.config.js

 {
  entry: {
    client: 'webpack-dev-server/client?http://localhost:8786', // WebpackDevServer host and port
    app: "./HelloWorld.tsx"
  },
  devtool: process.env.WEBPACK_DEVTOOL || 'cheap-module-source-map',
  output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].entry.js'
  },
  module: {
    loaders: [
      {
        test: /\.ts(x?)$/,
        loaders: ['react-hot', 'babel-loader?cacheDirectory=true,presets[]=es2015,presets[]=react', 'ts-loader']
      }
    ]
  },
    devServer: {
        contentBase: "./dist",
    port:8786
    },
    plugins: [
        new webpack.NoErrorsPlugin()
    ]
}

命令: webpack-dev-server --hot --inline

如果我使用 babel-preset-react-hmre,那么有趣的旁注一切都按预期工作。 (但我真的不想使用它,因为它似乎比正确的react-hot loader更少支持)。

on an interesting sidenote if I use babel-preset-react-hmre everything works as expected. (However I don't really want to use this as it seems less supported than the proper react-hot loader).

推荐答案

我刚遇到这个问题。一些事情:

I just ran into this problem. A couple things:

要帮助调试您的特定问题,请尝试启用保留日志(在Chrome开发工具中)。这将在页面刷新后持久保存控制台日志,因此您至少可以在触发刷新之前看到webpack-dev-server正在记录的任何消息。

To help debug your particular issue, try enabling "Preserve log" (in Chrome dev tools). This will persist console logs across page refreshes, so you'll at least be able to see any messages that webpack-dev-server is logging before it triggers a refresh.

在我的情况下,webpack-dev-server很新鲜,因为我没有在我的条目js文件中选择HMR。将以下行添加到文件中解决了问题:

In my case webpack-dev-server was refreshing because I had not opted into HMR in my entry js file. Adding the following line to the file solved the issue:

// Opt-in to Webpack hot module replacement
if (module.hot) module.hot.accept()

有关 module.hot API webpack HMR docs 非常有用。

For details on the module.hot API the webpack HMR docs are very helpful.

更新:一个时代的结束,webpack 1文档不再起作用。对于仍在寻找的人, HMR文档现在在这里

UPDATE: End of an era, webpack 1 docs are no longer up. For anyone still looking, HMR docs are here now.

这篇关于React + Webpack HMR刷新页面(不热装)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆