代码拆分
- 配置思路:使用Webpack的
splitChunks
插件,将代码按不同的规则拆分成多个文件,例如按路由拆分、按第三方库拆分等。
- 具体配置:
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name:'vendors',
chunks: 'all'
}
}
}
}
};
- 可能用到的插件:无,Webpack内置
splitChunks
功能。
Tree - shaking
- 配置思路:利用ES6模块的静态结构,Webpack在打包时去除未使用的代码。确保项目使用ES6模块,并且在
package.json
中设置"sideEffects": false
(如果项目所有代码都无副作用),或者指定有副作用的文件。
- 具体配置:在
webpack.config.js
中,确保mode
设置为'production'
,因为生产模式下Webpack默认开启Tree - shaking。
module.exports = {
mode: 'production'
};
- 可能用到的插件:无,Webpack生产模式默认支持。
Loader优化
- 配置思路:
- 减少Loader处理范围:通过
include
和exclude
属性指定Loader只处理特定目录下的文件。
- 缓存Loader结果:对于一些耗时的Loader,如Babel,可以启用缓存。
- 具体配置:
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
}
]
}
};
- 可能用到的插件:无,Loader自身可配置相关优化。
优化图片加载
- 配置思路:使用
image - webpack - loader
对图片进行压缩,减少图片体积。
- 具体配置:
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[name].[ext]'
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: false
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false
},
// the webp option will enable WEBP
webp: {
quality: 75
}
}
}
]
}
]
}
};
- 可能用到的插件:
image - webpack - loader
启用多进程打包
- 配置思路:使用
thread - loader
,它会开启多个子进程,将任务分配给这些子进程并行处理,从而加速打包。
- 具体配置:
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'thread-loader',
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset - env']
}
}
]
}
]
}
};
- 可能用到的插件:
thread - loader
压缩CSS和JS
- 配置思路:
- CSS:使用
OptimizeCSSAssetsPlugin
压缩CSS文件。
- JS:Webpack生产模式默认使用
TerserPlugin
压缩JS文件,可以进一步配置。
- 具体配置:
const OptimizeCSSAssetsPlugin = require('OptimizeCSSAssetsPlugin');
const TerserPlugin = require('terser - webpack - plugin');
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
compress: {
drop_console: true // 移除console.log
}
}
}),
new OptimizeCSSAssetsPlugin({})
]
}
};
- 可能用到的插件:
OptimizeCSSAssetsPlugin
、TerserPlugin