webpack + react-hot-loader 修改state页面不能热更新

按照文档配置 https://github.com/gaearon/re... 当修改文件中的state的name字段时,页面不会更新,但是修改render函数中的button text,页面就会更新?

"dev": "webpack-dev-server --inline --hot --progress --config build/webpack.dev.conf.js"

base config

const path = require('path');
const APP_PATH = path.resolve(__dirname, '../app');
const DIST_PATH = path.resolve(__dirname, '../dist');

module.exports = {
  entry: {
    app: './app/index.js',
    vendors: ['react', 'react-dom']
  },
  output: {
    filename: 'js/bundle.js',
    path: DIST_PATH
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        use: 'babel-loader',
        include: APP_PATH
      }
    ]
  }
};

dev config


module.exports = merge(baseWebpackConfig, {
  mode: 'development',
  output: {
    filename: 'js/[name].[hash:16].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'public/index.html',
      inject: 'body',
      minify: {
        html5: true
      },
      hash: false
    }),
    new webpack.HotModuleReplacementPlugin()
  ],
  devServer: {
    port: '3015',
    contentBase: path.join(__dirname, '../public'),
    compress: true, // gzip
    historyApiFallback: true,
    hot: true, // 启用 webpack 的模块热替换特性
    https: false,
    noInfo: false,
    open: true, // open the browser
    proxy: {}
  }
});

index.js



import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

App.js

import React from 'react';
import { hot } from 'react-hot-loader';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'world',
      show: true
    };
  }

  render() {
    return <div>
      {this.state.show && <button>button</button>}
      <h1>Hello, {this.state.name}</h1>
    </div>;
  }
}

export default hot(module)(App);


console在代码更新后可以打印log,但是页面不更新,什么原因?

[WDS] 91% - additional asset processing.
client:127 [WDS] 92% - chunk asset optimization.
client:127 [WDS] 92% - after chunk asset optimization.
client:127 [WDS] 93% - asset optimization.
client:127 [WDS] 93% - after asset optimization.
client:127 [WDS] 94% - after seal.
client:127 [WDS] 95% - emitting.
client:127 [WDS] 95% - emitting (HtmlWebpackPlugin).
2VM5824 client:127 [WDS] 98% - after emitting.
2VM5824 client:127 [WDS] 100% - Compilation completed.
VM5824 client:218 [WDS] App hot update...
VM5849 log.js:24 [HMR] Checking for updates on the server...
client:218 [WDS] App hot update...
log.js:24 [HMR] Checking for updates on the server...
log.js:24 [HMR] Nothing hot updated.
log.js:24 [HMR] App is up to date.
VM5849 log.js:24 [HMR] Updated modules:
VM5849 log.js:24 [HMR]  - ./app/App.js
VM5849 log.js:24 [HMR] App is up to date.
阅读 4.6k
4 个回答

App.js 去掉 react-hot-loader

import React from 'react';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'world',
      show: true
    };
  }

  render() {
    return <div>
      {this.state.show && <button>button</button>}
      <h1>Hello, {this.state.name}</h1>
    </div>;
  }
}

index.js改一下

const renderApp = () => ReactDOM.render(
  <App />,
  document.getElementById('root')
);

function run() {
  renderApp();
  if (module.hot) {
    module.hot.accept(renderApp);
  }
}

run();

同样遇到这个问题,请问你解决了吗

这个问题解决了吗

有几个要设置:

webpack.config.js

module.exports = {
    // Make sure react-hot-loader is required before react and react-dom:
    entry: ['`react-hot-loader/patch`', 'your.js'],
    
    devServer: {
        hot: true
    },
    
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ],
    
    resolve: {
        alias: {
            // 解决警告:React-Hot-Loader: react-?-dom patch is not detected. React 16.6+ features may not work.
            // 这个根据自己需求决定要不要添加
            'react-dom': '@hot-loader/react-dom'
        }
    }
}

.babelrc

{
    plugins: [ 'react-hot-loader/babel' ]
}

在你要热更新的地方加上

if (module.hot) {
    module.hot.accept('./pages/Root', () => {
        const NextRoot = require('./pages/Root').default
        render(<NextRoot />, rootElem)
    })
}

// PS: <Root /> 是我集成了 Provider、Store、Router 的东西,自行按需修改
// const Root = () => {
//     return (
//         <Provider store={MyStore}>
//             <Router history={hashHistory} routes={routes} />
//         </Provider>
//     )
// }

还有记得安装对应的包

react-hot-loader、@hot-loader/react-dom 等

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