需要的包
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'));