webpack配置react热更新

需要的包

cnpm i react react-dom webpack webpack-cli webpack-dev-server html-webpack-plugin clean-webpack-plugin style-loader css-loader @babel/core @babel/preset-react babel-loader -D
npm i react react-dom webpack webpack-cli webpack-dev-server html-webpack-plugin clean-webpack-plugin style-loader css-loader @babel/core @babel/preset-react babel-loader -D

配置

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

module.exports = {
  entry: {
    app: './src/index.jsx'
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist',
    hot: true,
    port: 8686,
    historyApiFallback: true
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './src/index.template.html'
    }),
    new webpack.HotModuleReplacementPlugin()
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.jsx$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        loader: ['style-loader', 'css-loader']
      }
    ]
  }
};

在package.json中配置babel及start命令

  "babel": {
    "presets": [
      "@babel/react"
    ]
  }
"start": "webpack-dev-server --hot --open"

完整的package.json文件

{
  "name": "name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --hot --open"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "babel": {
    "presets": [
      "@babel/react"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.7.2",
    "@babel/preset-react": "^7.7.0",
    "babel-loader": "^8.0.6",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.2.0",
    "html-webpack-plugin": "^3.2.0",
    "react": "^16.11.0",
    "react-dom": "^16.11.0",
    "style-loader": "^1.0.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0"
  }
}

热更新

使用module.hot实现热更新而不是刷新

import React from 'react';
import ReactDOM from 'react-dom';

if (module.hot) {
  module.hot.accept(()=>{
    ReactDOM.render(<App/>, document.getElementById('root'));
  });
}
ReactDOM.render(<App/>, document.getElementById('root'));

github地址:https://github.com/zwmain/react-webpack-template

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值