2

首先安装 npm i react-hot-loader -D

安装好之后在webpack.config.dev.js中entry第一行增加`'react-hot-loader/patch',客户端热更新代码需要用到的内容

如果有.babelrc文件就增加 "plugins": ["react-hot-loader/babel"]

{
  "presets": [
    ["es2015", {"loose": true}],
    "react"
  ],
  "plugins": ["react-hot-loader/babel"]
}

如果是create-react-app项目就在webpack.config.dev.js文件module-rules-oneOf下新增代码"plugins": ["react-hot-loader/babel"] 大约在143行号

          // Process JS with Babel.
          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              
              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              cacheDirectory: true,
              plugins: [
                'react-hot-loader/babel'
              ]
            },
          },

然后在代码的入口entry 根节点包含热更新

# File: index.js

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

import { AppContainer } from 'react-hot-loader'; // 包裹根节点,想要渲染的内容

const root = document.getElementById('root')
const render = Component => {
    ReactDOM.hydrate(
        <AppContainer>
            <Component />
        </AppContainer>,
        root
    )
}
render(App)

if (module.hot) {
    module.hot.accept('./App', () => { // 当我们热更新的代码出现的时候,把App重新加载
        const NextApp = require('./App').default //因为在App里使用的是export default语法,这里使用的是require,默认不会加载default的,所以需要手动加上
        render(NextApp) // 重新渲染到 document 里面
    })
}
// ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

custer
81 声望3 粉丝

引用和评论

0 条评论