面试题答案
一键面试1. 代码压缩
在 Webpack 中可以使用 terser-webpack-plugin
来压缩代码,减少文件体积。
在 webpack.config.js
中配置如下:
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
parallel: true, // 使用多进程并行运行以提高构建速度
terserOptions: {
compress: {
drop_console: true // 移除 console.log 等日志,进一步减小体积
}
}
})
]
}
};
2. 按需加载与代码分割
使用 splitChunks
进行代码分割,将公共代码提取出来,避免重复打包。
在 webpack.config.js
中配置如下:
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 30000, // 模块的最小大小,小于这个值的模块不会被拆分
minChunks: 1, // 被多少个chunk共享,在分割之前模块必须被至少这么多模块引用
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name:'vendors',
priority: -10
},
commons: {
name: 'commons',
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
};
3. 图片优化
可以使用 image-webpack-loader
来优化图片。
先安装 image-webpack-loader
:npm install image-webpack-loader -D
在 webpack.config.js
中配置如下:
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
}
}
}
]
}
]
}
};
4. 移除未使用的 CSS
可以使用 purgecss-webpack-plugin
来移除未使用的 CSS。
先安装 purgecss-webpack-plugin
:npm install purgecss-webpack-plugin -D
在 webpack.config.js
中配置如下:
const PurgeCSSPlugin = require('purgecss-webpack-plugin');
const glob = require('glob-all');
module.exports = {
plugins: [
new PurgeCSSPlugin({
paths: glob.sync(`${path.join(__dirname, 'src')}/**/*`, {nodir: true}),
safelist: function () {
return {
standard: ['body-dark']
};
}
})
]
};