React的webpack脚手架搭建
1.安装webpack
npm init -y
npm i react -S
npm i react-dom -S
npm i webpack -D
npm i webpack-cli -D
npm i babel-loader @babel/core @babel/preset-env @babel/preset-react -D (react打包器)
npm i css-loader style-loader -D (css打包器)
npm i sass-loader node-sass -D (scss打包器)
npm i mini-css-extract-plugin -D (css提取器)
npm i html-webpack-plugin -D (复制index.html到dist文件夹的插件)
npm i webpack-dev-server -D (webpack-dev-server)
2.创建src/index.jsx,src/dev.jsx文件,内容如下
index.jsx
import React from 'react' import ReactDOM from 'react-dom' ReactDOM.render( <div>hello webpack !!!</div> , document.getElementById("root"))
dev.jsx(用于触发HMR)
if (module.hot) { module.hot.accept(err => { if (err) { console.error('Cannot apply HMR update.', err); } }); }
3.创建public/index.html,内容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>webpack练习</title> </head> <body> <div id="root"></div> </body> </html>
4.创建并配置webpack.config.js,内容如下
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack'); //增加导入webpack
module.exports = {
mode: 'development',
devtool: 'cheap-module-source-map',
devServer: {
hot: true, //在devServer中增加hot字段
contentBase: path.join(__dirname, './src/'),
publicPath: '/',
host: '127.0.0.1',
port: 3000,
stats: {
colors: true
}
},
entry:['./src/index.js', './src/dev.jsx'], //在entry字段中添加触发文件配置
resolve: {
extensions: ['.wasm', '.mjs', '.js', '.json', '.jsx']
},
module: {
rules: [
{
test: /\.jsx?$/, // jsx/js文件的正则
exclude: /node_modules/, // 排除 node_modules 文件夹
use: {
// loader 是 babel
loader: 'babel-loader',
options: {
// babel 转义的配置选项
babelrc: false,
presets: [
// 添加 preset-react
require.resolve('@babel/preset-react'),
[require.resolve('@babel/preset-env'), {modules: false}]
],
cacheDirectory: true
}
}
},{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
'css-loader',
'sass-loader',
],
}
]
},
plugins: [
// plugins中增加下面内容,实例化热加载插件
new webpack.HotModuleReplacementPlugin(),
new HtmlWebPackPlugin({
template: 'public/index.html',
filename: 'index.html',
inject: true
}),
new MiniCssExtractPlugin()
]
};
5.在package.json配置scripts如下
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --mode production", "start": "webpack-dev-server --mode development --open" },
6.执行打包
npx webpack --mode development
如果出现下图显示内容,则打包成功

也可以用配置在scripts内的命令打包
npm run build
7.启动服务器
npm start

浙公网安备 33010602011771号