webpack4性能优化
splitChunks 配置
webpack 总共提供了三种办法来实现 Code Splitting,如下:
- 入口配置:entry 入口使用多个入口文件;
- 抽取公有代码:使用 SplitChunks 抽取公有代码;
- 动态加载 :动态加载一些代码。
这里我们姑且只讨论使用 SplitChunks 抽取公有代码。
optimization: {
splitChunks: {
cacheGroups: {
commons: {
chunks: 'initial',
minChunks: 2,
maxInitialRequests: 5,
minSize: 0,
name: 'commons',
},
},
},
}
额外生成commons.js、commons.css
externals配置来提取常用库
webapck遇到此类变量名时就可以不用解析和编译至模块的内部文件中,而改用从外部变量中读取,这样能极大的提升编译速度,同时也能更好的利用CDN来实现缓存。
生产配置
contenthash
output: {
filename: 'scripts/[name].[contenthash:5].bundle.js',
},
压缩html
const minify = require('html-minifier').minify;
plugins: [
new CopyPlugin(
[
{
from: join(__dirname, '../', 'src/web/components'),
to: '../components',
transform(content) {
const resutlt = minify(content.toString('utf-8'), {
collapseWhitespace: true, // 压缩空格
});
return resutlt;
},
},
],
{
ignore: ['*.js', '*.css', '.DS_Store'],
}
),
]
压缩CSS
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
},
canPrint: true,
}),
压缩JS, terser-webpack-plugin(代替uglifyjs-webpack-plugin)
const TerserPlugin = require('terser-webpack-plugin');
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
test: /\.js(\?.*)?$/i,
}),
],
},
打包测量
打包速度测量speed-measure-webpack-plugin
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();
module.exports = smp.wrap(merge(webpackConfig, _mergeConfig));
结果:
Build completed in 1.204s
SMP ⏱
General output time took 1.21 secs
SMP ⏱ Plugins
OptimizeCssAssetsWebpackPlugin took 0.28 secs
TerserPlugin took 0.177 secs
HardSourceWebpackPlugin took 0.067 secs
HtmlWebpackPlugin took 0.034 secs
CopyPlugin took 0.016 secs
MiniCssExtractPlugin took 0.002 secs
ProgressPlugin took 0.002 secs
HtmlAfterPlugin took 0 secs
SMP ⏱ Loaders
mini-css-extract-plugin, and
css-loader, and
postcss-loader took 0.425 secs
module count = 1
css-loader, and
postcss-loader took 0.405 secs
module count = 1
thread-loader, and
cache-loader, and
babel-loader took 0.155 secs
module count = 6
html-webpack-plugin took 0.016 secs
module count = 3
modules with no loaders took 0.004 secs
module count = 2
可视化打包性能分析webpack-bundle-analyzer
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
}
加速loader, cache-loader
注意, 需要的地方使用cache-loader。 核心: 多核。
yarn add --dev cache-loader
{
test: /\.?js$/,
exclude: /(node_modules|bower_components)/,
use: ['thread-loader', 'cache-loader', 'babel-loader'],
},