以下的所有尝试是基于webpack5.9.0版本
分析打包数据
有几个插件可以帮助你分析数据:
- friendly-errors-webpack-plugin及node-notifier
更友好的错误提示插件
webpack.config.js
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const notifier = require('node-notifier');
module.export = {
plugins: [
new FriendlyErrorsWebpackPlugin({
onErrors:(severity,errors) => {
const error = errors[0];
notifier.notify({
title: 'webpack编译报错',
message: severity + ':' + error.name,
subtitle: error.file || '',
icon: xxxx // 可以随便放个图标
})
}
})
]
}
配置后,报错会在右下角出现类似提示:
2.speed-measure-webpack5-plugin
可以分析打包速度
webpack.config.js
const SpeedMeasureWebpack5Plugin = require('speed-measure-webpack5-plugin');
const smw = new SpeedMeasureWebpack5Plugin();
module.export = smw.wrap({...}) //将整个配置用wrap包起来
运行编译后,可以更直观地帮你展示打包时间
- webpack-bundle-analyzer
可以分析打包后的体积
webpack.config.js
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
}
需要通过命令去启动
比如package.json里配置一下:
"scripts": {
...
"dev": "webpack --progress"
},
启动后会跳转8888端口号的服务器展示代码关系及体积的分布图(有点类似微信小程序开发者里的代码依赖分析)
但有时候你不想展示8888服务器,这些分析数据不想立即查看,而是先存起来,你也可以这么配置:
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: "disabled", //不启动展示打包报告的http服务器
generateStatsFile: true //生成stats.json文件
})
]
}
重新启动一遍,会发现dist里多了stats.json
当然,json文件看起来肯定还是没刚刚的http服务器来得爽,那后期如果你又想看http服务器了怎么办?你可以再加个启动指令
"scripts": {
...
"analyzer": "webpack-bundle-analyzer --port 8888 ./dist/stats.json"
},