先安装所有的依赖: 没有cnpm 的 可以找 淘宝镜像
cnpm init -y
cnpm install [email protected] -S
cnpm install [email protected] -S
cnpm install webpack -D
cnpm install webpack-cli -D
cnpm i babel-loader @babel/core @babel/preset-env @babel/preset-react -D
cnpm i html-webpack-plugin -D
cnpm i webpack-dev-server -D
第二部:
创建app/index.js
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(react , document.getElementById("root"))
创建public/index.html
手动搭建react
创建webpack.config.js
const HtmlWebPackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './app/index.js',
mode: 'development',
devtool: 'cheap-module-source-map',
resolve: {
extensions: ['*', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
babelrc: true,
presets: ['@babel/preset-react', '@babel/preset-env'],
cacheDirectory: true
}
}
},
]
},
devServer: {
host: '127.0.0.1',
port: 8080
},
plugins: [
new HtmlWebPackPlugin({
template: 'public/index.html',
filename: 'index.html'
})
]
}
对比一下package.json ,缺失的直接复制
{
"name": "myblue",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"serve": "webpack-dev-server --mode development --open",
"build": "webpack --mode production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@babel/core": "^7.18.2",
"@babel/preset-env": "^7.18.2",
"@babel/preset-react": "^7.17.12",
"babel-loader": "^8.2.5",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.9.0"
}
}
可以运行了。
运行:
npm run serve
打包:
npm run build
上面可以跑起来了。
下面继续 css 处理依赖
cnpm install mini-css-extract-plugin -D
cnpm install css-loader -D
MiniCssExtractPlugin 可以单独打包, 但是没有压缩。
webpack.config.js 加入 loader中加入
{
test: /\.css$/,
use:[MiniCssExtractPlugin.loader,'css-loader']
}
plugins: [
new HtmlWebPackPlugin({
template: 'public/index.html',
filename: 'index.html'
}),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
new CssMinimizerPlugin()
]