首先安裝 npm i react-hot-loader -D
css
安裝好以後在webpack.config.dev.js中entry第一行增長`'react-hot-loader/patch',客戶端熱更新代碼須要用到的內容node
若是有.babelrc文件就增長 "plugins": ["react-hot-loader/babel"]
react
{ "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行號webpack
// 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 根節點包含熱更新web
# 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();