本文是如何收集、分析 Webpack 打包过程的性能数据的学习笔记。介绍几种分析webpack构建性能的工具。
Webpack 内置 stats 接口
 webpack内置的stats 产出一个json文件,专门用于统计模块构建耗时、模块依赖关系等信息。
使用方法:
方法一:添加配置
module.exports = {profile: true}
方法二:通过命令
# 命令启动# 产出stats.jsonnpx webpack --json=stats.json
产出的stats.json大致结构是:
{"hash": "2c0b66247db00e494ab8","version": "5.36.1","time": 81,"builtAt": 1620401092814,"publicPath": "","outputPath": "/Users/tecvan/learn-webpack/hello-world/dist","assetsByChunkName": { "main": ["index.js"] },// 编译后最终输出的产物列表、文件路径、文件大小等"assets": [// ...],// 构建过程生成的 chunks 列表// 数组内容包含 chunk 名称、大小、包含了哪些模块等"chunks": [// ...],// modules// 本次打包处理的所有模块列表// 内容包含模块的大小、所属 chunk、构建原因、依赖模块等// 特别是 modules.profile 属性// 包含了构建该模块时,解析路径、编译、打包、子模块打包等各个环节所花费的时间"modules": [// ...],// entry 列表,包括动态引入所生产的 entry 项也会包含在这里面"entrypoints": {// ...},"namedChunkGroups": {// ...},"errors": [// ...],"errorsCount": 0,"warnings": [// ...],"warningsCount": 0,// 子 Compiler 对象的性能数据// 例如 extract-css-chunk-plugin 插件内部就会调用 compilation.createChildCompiler// 函数创建出子 Compiler 来做 CSS 抽取的工作"children": [// ...]}
更多信息可参考官网对status的介绍:
生成的stats.json怎么分析呢,可以使用官方的 Analysis 工具,将json文件上传就能得到分析结果,比如依赖关系图,查看构建过程各阶段、各模块的处理耗时等信息。
webpack-bundle-analyzer
yarn add -D webpack-bundle-analyzer
使用方式:
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;module.exports = {plugins: [new BundleAnalyzerPlugin()]}
配置好之后运行build命令,会自动打开浏览器载入分析结果视图:
分析结果如图所示,基于此可以:
- Bundle 包所包含的模块内容 —— 从而推断出产物中是否包含预期之外的模块;
 - 确定模块体积大小与占比 —— 从而确定是否存在优化空间;
 - 了解 Bundle 产物体积,以及经过压缩后的体积。
speed-measure-webpack-plugin
 

这个插件,能够统计出各个 Loader、插件的处理耗时,输出的结果如左图所示。
yarn add -D speed-measure-webpack-plugin
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");const smp = new SpeedMeasurePlugin();const config = {entry: "./src/index.ts",// ...};// 包裹原先的 Webpack 配置module.exports = smp.wrap(config);
unused-webpack-plugin

这个插件能够根据 webpack 统计信息,反向查找出工程项目里哪些文件没有被用到。
结果在build命令后在控制台输出。
用法
const UnusedWebpackPlugin = require('unused-webpack-plugin');module.exports = {// webpack configurationplugins: [...otherPlugins,new UnusedWebpackPlugin({// Source directoriesdirectories: [path.join(__dirname, 'src')],// Exclude patternsexclude: ['*.test.js'],// Root directory (optional)root: __dirname,}),],};
webpack dashboard

能够在编译过程中实时展示编译进度、模块分布、产物信息等。
用途没那么大,用法参考上面贴出的官网。
