2

我遇到了一个问题,我在其他地方看到过报告(但不是真正有效的解决方案),当尝试使用反应热模块重新加载时,当渲染方法中的内容发生变化时,整个页面都会刷新。

客户端.js

import React from 'react'
import { render } from 'react-dom'
import { AppContainer } from 'react-hot-loader'

import Root from './Root'

ReactDOM.render(
  <Root />
  , document.getElementById('root'))

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept()
}

根.js

//imports: react, {provider} from react-redux, {AppContainer} from react-hot-loader, other components

const Root = React.createClass({
  render () {
    return (
      <AppContainer>
        <Provider store={this.props.store}>
          <MainComponent>
            {/* bunch of other components */}
          </MainComponent>
        </Provider>
      </AppContainer>
    )
  }
})

package.json脚本:yarn run dev

"dev": "webpack-dev-server --env.development"

webpack.config.js

let isProd
module.exports = env => {
  isProd = env.production === true
  isDev = !isProd
  return {
    context: __dirname,
    entry: {
      app: [
        'react-hot-loader/patch',
        './js/client.js'
      ]
    },
    devtool: env.production ? 'source-map' : 'eval',
    // devtool: 'source-map',
    output: {
      path: path.join(__dirname, 'dist', 'js'),
      filename: 'bundle.js',
      // publicPath: '/dist/js',
      pathinfo: isDev
    },
    devServer: {
      publicPath: '/public/',
      historyApiFallback: true,
      hot: true,
      inline: true,
      port: 5888,
      proxy: {
        '/api': {
         target: 'http://localhost:6500'
        }
      }
    },
    resolve: {
      extensions: ['.js', '.json']
      // alias: {
      //   'google': path.resolve(__dirname, 'vendor', 'google.js')
      // }
    },
    stats: {
      colors: true,
      reasons: true,
      chunks: true
    },
    module: {
      rules: [
        {
          enforce: 'pre',
          test: /\.js$/,
          loader: 'eslint-loader',
          exclude: /node_modules/
        }
      ]
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoEmitOnErrorsPlugin()
    ]
  }
}

版本

"webpack": "^2.6.1",
"webpack-dev-server": "^2.4.5"

在控制台的初始加载中,我看到[HMR] Waiting for update signal from WDS...

然后在保存更改时,页面刷新,然后在控制台中我得到

[HMR] 找不到更新。需要完全重新加载![HMR](可能是因为重启了 webpack-dev-server)

如何让 HMR 注入 JS 而不重新加载页面?

4

0 回答 0