React热替换配置
首先,我这里说两种方式,其他的暂时还不知道,时间比加紧,还看不了这么多。
开启方式
-
命令行方式
-
直接在webpack-dev-server的启动命令中加入
--hot
配置文件方式
- 在配置文件中(如webpack.config.js)导入webpack
- devServer配置hot为true
-
plugins的配置加上
new webpack.HotModuleReplacementPlugin()
加载webpack,并添加webpack的模块热替换插件
使热替换生效
入口文件index.js中加入
if (module.hot) {
module.hot.accept();
}
以下是我的配置文件和入口文件
配置文件和入口文件
//webpack.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: [
'react-hot-loader/patch',
path.join(__dirname, 'app/index.js')
],
output: {
path: path.join(__dirname, 'app/dist/js'),
filename: 'bundle.js',
publicPath: 'dist/js'
},
module: {
rules: [
{
test: /\.js[x]?$/,
use: ['babel-loader?cacheDirectory=true'],
include: path.join(__dirname, 'app')
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
historyApiFallback: true,
hot: true,
port: 8909,
host: '0.0.0.0',
contentBase: './app',
}
}
//index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {AppContainer} from 'react-hot-loader';
import getRouter from './src/router';
const boot = (elements)=> {
ReactDOM.render(
<AppContainer>
{elements}
</AppContainer>
, document.getElementById('app'));
}
let rs = getRouter();
boot(rs);
if (module.hot) {
module.hot.accept();
}
我学习这个技术的来源
从零搭建React全家桶框架教程(https://github.com/brickspert/blog/issues/1)