1. 优化 babel-loader
- 缓存:使用
cacheDirectory
选项开启缓存,将 Babel 编译后的结果缓存起来,下次编译相同代码时直接从缓存读取,提升编译速度。
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
}
]
}
};
- 指定
include
或 exclude
:明确指定需要处理的文件目录,避免对不必要的文件进行编译。比如排除 node_modules
目录,因为其中的代码通常已经是编译好的,不需要再次通过 babel-loader
处理。
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
2. 优化 image - loader
- 压缩图片:使用
image-webpack-loader
对图片进行压缩,减少图片体积从而加快打包后资源的加载速度。通过设置 mozjpeg
等插件的参数来优化压缩效果。
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
}
}
}
]
}
]
}
};
- 限制处理图片大小:通过
limit
参数,当图片小于指定大小(单位为字节)时,将图片转为 base64 编码嵌入到代码中,减少 HTTP 请求,但过大的图片转为 base64 会使文件体积增大,适得其反,所以要合理设置。
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: 'images/[name].[ext]'
}
}
]
}
]
}
};
3. 优化 css - loader
与 style - loader
- 使用
mini - css - extract - plugin
替代 style - loader
用于生产环境:style - loader
将 CSS 插入到 JavaScript 中,在生产环境会增加 JavaScript 体积,影响加载性能。mini - css - extract - plugin
会将 CSS 提取到单独的文件中,实现 CSS 与 JavaScript 的分离,浏览器可以并行加载 CSS 和 JavaScript,提升加载速度。
const MiniCssExtractPlugin = require('mini - css - extract - plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles.css'
})
]
};
- 启用
css - loader
的 importLoaders
:当有多个 CSS 相关 Loader 链式调用时,importLoaders
可以指定 css - loader
之前的 Loader 数量,确保 @import
引入的 CSS 也能经过正确的 Loader 处理,避免重复处理或遗漏处理导致的性能问题。
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1
}
},
'postcss-loader'
]
}
]
}
};