1.
npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-2
2.
npm install --save-dev react-hot-loader@3.0.0-beta.6或者npm install --save-dev react-hot-loader@next
3.
.babelrc配置{ "presets": [ ["es2015", {"modules": false}], // webpack現在已經支援原生的import語句了, 並且將其運用在tree-shaking特性上 "stage-2", // 規定JS運用的語言規範層級 // Stage 2 是 "草案", 4 是 "已完成", 0 is "稻草人(strawman)"。 // 詳情查看 https://tc39.github.io/process-document/ "react" // 轉譯React組件為JS代碼 ], "plugins": [ "react-hot-loader/babel" // 開啟react代碼的模組熱替換(HMR) ]}
4.
config配置:const { resolve } = require('path');const webpack = require('webpack');module.exports = { context: __dirname, entry: [ 'react-hot-loader/patch', 'webpack/hot/only-dev-server', './app/main.js' ], output: { path: resolve(__dirname, 'build'),//打包後的檔案存放的地方 filename: "bundle.js",//打包後輸出檔案的檔案名稱 publicPath: "/" }, devServer: { contentBase: resolve(__dirname, 'build'), hot: true, publicPath:'/' }, module: { rules: [ { test: /\.jsx?$/, use: [ 'babel-loader', ], exclude: /node_modules/ }, ], }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), ], devtool: "cheap-eval-source-map",};
5.
入口檔案中配置:import {AppContainer} from 'react-hot-loader'import Redbox from 'redbox-react'const render = (Component) => { ReactDOM.render( <AppContainer errorReporter={Redbox}> <Component /> </AppContainer>, document.querySelector('#odiv') )};render(App);if(module.hot) { module.hot.accept('./app', () => { render(App) });}或者const oEle = document.querySelector('#odiv');render( <AppContainer errorReporter={Redbox}> <App /> </AppContainer>, oEle)if (module.hot) { module.hot.accept('./app', () => { const NextApp = require('./app').default; render( <AppContainer errorReporter={Redbox}> <NextApp /> </AppContainer>, oEle ) });}