一、上手 webpack
npm init -y
npm install webpack webpack-cli --save-dev
二、启动本地 server
- 安装插件
npm install --save-dev webpack-dev-server
- 配置
- 在
package.json
中配置 script 指令
"scripts": {
"dev": "webpack-dev-server --config ./webpack/webpack-dev-config.js --mode development --open",
},
相应的webpack-dev-config.js
文件代码
const path = require('path')
const { merge } = require('webpack-merge') //把基本webpack配置和开发(生产)环境的配置合并
const webpackConfigBase = require('./webpack-base-config')
function resolve(relatedPath) {
return path.join(__dirname, relatedPath)
}
const webpackConfigDev = {
mode: "development",
optimization: {
splitChunks: {
chunks: "all", //all(全部模块)
},
},
devServer: {
static: {
directory: resolve('../src'),
},
historyApiFallback: false,
open: true,
compress: true,
host: '127.0.0.1',
port: 9096,
hot: true, //启动热更新
},
devtool: 'inline-source-map'
}
module.exports = merge(webpackConfigBase, webpackConfigDev)
三、使用 babel 编译 react
- 下载相关插件
npm i babel-loader --save-dev //^8.2.5
npm install @babel/core --save-dev //^7.18.0
npm i @babel/preset-react --save-dev //^7.17.12
npm i @babel/preset-env --save-dev //^7.18.0
npm i @babel/plugin-transform-runtime
- 配置
.babelrc
文件
{
"presets": [
[
"@babel/preset-react",
{
"runtime": "automatic"
}
],
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"targets": {
"chrome": "49",
"ie": "11"
},
"corejs": 2
}
]
],
"plugins": ["@babel/plugin-transform-runtime"]
}
- 修改 webpack 配置文件
module: {
rules: [
...
{
test: /\.js[x]?$/,
include: [paths.src],
exclude: /node_modules/,
use: [
'babel-loader?cacheDirectory', // 开启缓存
],
},
...
]
}
四、下载 react 相关包
npm install --save react react-dom