代码分割
- 使用
splitChunksPlugin
- 定制与使用:在 Webpack 的
optimization
配置中使用 splitChunksPlugin
。例如:
module.exports = {
//...其他配置
optimization: {
splitChunks: {
chunks: 'all',
minSize: 30000,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
};
- 优先级:在构建开始阶段就应用,有助于提高初始加载性能,因为它将代码拆分成更小的块,使得浏览器可以并行加载。
- 副作用:可能会增加请求数量,如果请求数量过多,会增加网络开销。同时,如果拆分不合理,可能导致一些模块重复加载。
- 动态导入(
import()
)
- 定制与使用:在代码中使用动态导入语法,Webpack 会自动将这些导入的模块拆分成单独的 chunk。例如:
// 懒加载组件
const loadComponent = async () => {
const { default: component } = await import('./MyComponent.js');
return component;
};
- 优先级:通常在需要实现按需加载的场景下使用,优先级根据业务需求确定,比如在路由懒加载场景下优先级较高。
- 副作用:如果处理不当,可能会导致初次加载时某些功能不可用,直到相关模块加载完成。
资源压缩
terser - webpack - plugin
- 定制与使用:用于压缩 JavaScript 代码。在
optimization.minimizer
中配置:
const TerserPlugin = require('terser - webpack - plugin');
module.exports = {
//...其他配置
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
compress: {
drop_console: true // 移除 console.log
}
}
})
]
}
};
- 优先级:在构建的最后阶段,打包完成后对输出的 JavaScript 文件进行压缩,因为它处理的是最终的代码产物。
- 副作用:可能会增加构建时间,尤其是在处理大型项目时。并且如果配置不当,如移除一些不该移除的代码,可能导致运行时错误。
image - webpack - loader
- 定制与使用:用于压缩图片资源。在
module.rules
中配置:
module.exports = {
//...其他配置
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
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
}
}
}
]
}
]
}
};
- 优先级:在处理图片资源加载时应用,通常在构建过程中较早阶段,因为它直接影响图片资源的大小和加载速度。
- 副作用:可能会降低图片质量,如果配置的压缩参数不合理,可能导致图片失真,影响用户体验。
缓存策略
webpack - cache
- 定制与使用:Webpack 4+ 内置了缓存机制,通过设置
cache
配置项启用。例如:
module.exports = {
//...其他配置
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
};
- 优先级:在整个构建过程的开始阶段起作用,它会缓存上一次构建的结果,减少重复计算。
- 副作用:如果缓存策略设置不当,比如没有正确配置
buildDependencies
,可能导致缓存失效或使用过期的缓存,从而影响构建结果的准确性。
html - webpack - include - assets - plugin
与缓存控制
- 定制与使用:配合 HTML Webpack 插件,设置 HTML 文件中引入资源的缓存头。例如:
const HtmlWebpackIncludeAssetsPlugin = require('html - webpack - include - assets - plugin');
module.exports = {
//...其他配置
plugins: [
new HtmlWebpackIncludeAssetsPlugin({
assets: [
{
path: '/js/vendor.js',
attributes: {
'cache - control':'max - age = 31536000, public'
}
}
]
})
]
};
- 优先级:在生成 HTML 文件阶段应用,设置资源的缓存策略,影响浏览器对资源的缓存。
- 副作用:如果缓存时间设置过长,在资源更新时,用户可能无法及时获取到最新版本,需要手动清除浏览器缓存。