当项目中同时存在大量源代码和需要压缩的静态资源时,如何配置`webpack`及其相关插件,确保在提升构建速度的同时实现高效的资源压缩?
在项目中同时存在大量源代码和需要压缩的静态资源时,正确的配置 Webpack 及其相关插件不仅可以有效提升构建速度,还能实现高效的资源压缩。以下是一些关键配置和优化策略,可以帮助达到这一目标。
1. 使用 mode 模式
Webpack 4 之后版本中引入了 mode 配置项,允许开发者通过简单的方式设置构建模式:development、production 和 none。设置为 production 时,会自动启用多个优化功能,如代码压缩、Scope Hoisting 等。
module.exports = {
mode: 'production',
// 其他配置
};
2. 利用 SplitChunksPlugin
针对大型项目,使用 optimization.splitChunks 配置项可以将代码分割成多个小块,以减少初始加载时间和后续加载时间。通过将公共代码和第三方库提取到单独的文件中,可以显著提高缓存效率。
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 10000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 10,
maxInitialRequests: 5,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
},
// 其他配置
};
3. 启用 Tree Shaking
Tree Shaking 用于移除未使用的代码,帮助减少最终输出文件的体积。确保使用 ES6 模块语法,并在 .babelrc 中正确配置以支持 Tree Shaking。
{
"presets": [
[
"@babel/preset-env", {
"modules": false
}
]
]
}
4. 使用 TerserPlugin 进行代码压缩
虽然在 production 模式下 Webpack 会自动使用 TerserPlugin 压缩 JavaScript 代码,但可以根据项目需求对插件进行自定义配置,例如设置压缩级别或添加版权注释。
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true // 移除所有 console 语句
},
output: {
comments: false // 移除所有注释
}
}
})
]
},
// 其他配置
};
5. 压缩 CSS 和 图片资源
- CSS 压缩:可以使用
mini-css-extract-plugin和optimize-css-assets-webpack-plugin来提取和压缩 CSS。 - 图片优化:使用
image-webpack-loader对图片进行压缩。
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /[\/]\.css$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
require('autoprefixer'),
],
},
},
},
],
},
{
test: /[\/]legacy\.css$/i,
use: [
'style-loader',
'css-loader',
],
},
{
test: [\/]\.(jpe?g|png|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65,
},
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.90],
speed: 4,
},
gifsicle: {
interlaced: false,
},
webp: {
quality: 75,
},
},
},
]
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
new OptimizeCSSAssetsPlugin({
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', {discardComments: {removeAll: true}}],
},
canPrint: true,
}),
],
optimization: {
minimizer: [
new ImageMinimizerPlugin({
minimizer: {
implementation: ImageMinimizerPlugin.svgoMinify,
options: {
plugins: [
{
name: 'removeViewBox',
active: false,
},
],
},
},
}),
],
},
// 其他配置
};
6. 使用缓存机制
Webpack 的缓存机制可以显著提高构建速度。通过缓存节省的时间对于大型项目尤其重要。开启 DLL Plugins、持久化缓存和 HardSourceWebpackPlugin 插件来加速缓存。
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
cache: {
type: 'memory', // 或 'filesystem'
},
plugins: [
new HardSourceWebpackPlugin(),
],
// 其他配置
};
7. 并行处理
利用多核 CPU 通过 thread-loader 或 happypack 等加载器来加速构建过程。
const HappyPack = require('happypack');
module.exports = {
module: {
rules: [
{
test: /[\/]\.js$/,
use: 'happypack/loader?id=js',
exclude: /node_modules/, // 排除 node_modules 目录
},
],
},
plugins: [
new HappyPack({
id: 'js',
loaders: ['babel-loader?cacheDirectory=true'],
}),
],
// 其他配置
};
以上是针对同时处理大量源代码和需要压缩的静态资源时,如何配置 Webpack 及其相关插件的一些建议。通过这些配置,可以在保证资源压缩效果的同时,有效提升构建速度。