React + Webpack HMR is refreshing the page (not hot loading)

落花浮王杯 提交于 2019-12-06 18:49:15

问题


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] Waiting for update signal from WDS...
[WDS] Hot Module Replacement enabled.

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()
    ]
}

command: webpack-dev-server --hot --inline

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).


回答1:


I just ran into this problem. A couple things:

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.

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()

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

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



来源:https://stackoverflow.com/questions/37271499/react-webpack-hmr-is-refreshing-the-page-not-hot-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!