webpack5大致使用和webpack4相同
介绍下新的特性
webpack serve 就能启动 webpack-dev-server
"scripts": {
"build": "webpack",
"start": "webpack serve"
},
packjson结构
{
"name": "zhufeng-webpack5-202012",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"start": "webpack serve"
},
"sideEffects":["*.css","@babel/polyfill"],
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.12.10",
"@babel/preset-env": "^7.12.11",
"@babel/preset-react": "^7.12.10",
"babel-loader": "^8.2.2",
"buffer": "^6.0.3",
"crypto-browserify": "^3.12.0",
"crypto-js": "^4.0.0",
"css-loader": "^5.0.1",
"html-webpack-plugin": "^4.5.0",
"stream-browserify": "^3.0.0",
"style-loader": "^2.0.0",
"webpack": "^5.11.0",
"webpack-cli": "^4.3.0",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"lodash-es": "^4.17.20",
"react": "^17.0.1",
"react-dom": "^17.0.1"
}
}
通过cache配置缓存存储位置和开启
{
...
//watch:true,
cache: {
//不要再使用cnpm来安装模块
type: 'filesystem', //memory filesystem
cacheDirectory: path.resolve(__dirname, 'node_modules/.cache/webpack')
},
}
...
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/, //不打包 不编译node_modules下面的文件
use: [
{
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react'
]
}
}
]
},
{
test: /\.png$/,
type: 'asset/resource' //对标file-loader
},
{
test: /\.ico$/,
type: 'asset/inline' //对标url-loader 模块的大小
},
{
test: /\.txt$/,
type: 'asset/source' //对标raw-loader
},
{
test: /\.jpg$/,
type: 'asset', //对标raw-loader
parser: {
dataUrlCondition: {
maxSize: 4 * 1024
}
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
以前webpack4.0 chunkId是用数字0 1 2顺序定义, 模块少量变动引入会打乱了各个文件命名, 对缓存资源文件不友好,于是可以通过配置chunkId moduleIds的规则。
{
...
optimization: {
usedExports: true, //标使用到的导出
moduleIds: 'deterministic', //模块名称的生成规则
chunkIds: 'deterministic' //代码块名称的生成规则
},
}
// 使用:
fallback:{
'crypto':require.resolve('crypto-browserify'),
'stream':require.resolve('stream-browserify'),
'buffer':require.resolve('buffer')
},
{
...
mode: 'production',
optimization: {
usedExports: true, // true: 使用到的导出才使用
...
},
}
package.json
{
...
"sideEffects":["*.css","@babel/polyfill"],
}