react配置HMR(热替换 保留页面数据状态)

webpack.config.js(基础配置不介绍了,直接走HMR配置)

  1. devServer开启hot
  2. plugins部分启用webpack.HotModuleReplacementPlugin() 配合
  3. npm install react-hot-loader --save
const webpack = require('webpack');
const { resolve } =require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: resolve(__dirname, "index.js"),//入口文件
    output: {
        path: resolve(__dirname, "dist"),//打包后的文件存放的地方
        filename: "build.js"//打包后输出文件的文件名
    },
    mode: 'development', // production 生产环境会自动压缩js代码,无需我们关系
    devServer: { //开发服务器的配置
        port: 3000,//自定义访问的端口号
        open: true, // 
        hot: true,
        compress: true, //启动gzip压缩,启动速度快
        progress: true,
        contentBase: resolve(__dirname, 'dist') //运行的文件目录
    },
    module: {
        // 根据文件后缀匹配规则
        rules: [
            // 配置js/jsx语法解析
            { test: /\.js|jsx$/, use: 'babel-loader', exclude: /node_modules/ }
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),   //启用HMR,配合server的hot
        new HtmlWebpackPlugin({
            template: resolve(__dirname, 'index.html'),
            // 压缩html
            minify: {
                collapseWhitespace: true, //移除空格
                removeComments: true // 移除注释
            }
        }),
       
    ],
   
}

react代码部分(修改任意子组件的内容,保存,另一组件的input输入值依然存在)

根组件

import React from 'React';
import { render } from 'react-dom';
import Test from './test'
import Three from './three'
class Index extends React.Component{
  render() {
    return (
      
) } } render(, document.querySelector("#app"))

子组件Test

import React from 'React';
import { hot } from 'react-hot-loader/root';
class Test extends React.Component{
  render() {
    return (
      
) } } export default hot(Test)

子组件 Three

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

class Three extends React.Component{  
  render() {
    return (
      
) } } export default hot(Three)

 

你可能感兴趣的:(前端)