The full text is 1500 words, and the reading time is about 15 minutes. If you feel the article useful, welcome to praise attention, but writing is not easy, without the consent of the author, prohibit any form of reprint!!

Imagine a scenario where you need to speed up a WebPack build, or optimize the size of your build product. Where do you start? Don’t worry, take the time to understand the current build execution and identify performance bottlenecks before you go into action. Today I’m going to share some diagnostics and tools for the WebPack build process. Based on these tools, you can:

  • Understand which module resources the build artifact consists of
  • Understand the dependencies between modules
  • Understand the build speed of different modules
  • Understand the resource ratio of modules in the end product
  • , etc.

Collecting Statistics

The Webpack runtime collects various statistics, which can be obtained by attaching the — JSON parameter at startup:

npx webpack --json > stats.json
Copy the code

Stats. json file will be output in the folder. The file contains the following contents:

{
  "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": [
    // ...]."modules": [
    // ...]."entrypoints": {
    // ...
  },
  "namedChunkGroups": {
    // ...
  },
  "errors": [
    // ...]."errorsCount": 0."warnings": [
    // ...]."warningsCount": 0."children": [
    // ...]}Copy the code

Typically, when analyzing build performance, you focus on the following attributes:

  • Assets: A list of artifacts compiled for final output
  • Chunks: a list of chunks generated during the build process, containing an array containing the chunk name, size, and dependency graph
  • Modules: All modules touched by this run. The array contains the size, chunk of the module, analysis time, and construction reason of the module
  • Entrypoints: Entry lists, including dynamically imported entries, are also included in this list
  • NamedChunkGroups: named versions of chunks, which are more concise than chunks
  • Errors: All error messages that occur during the build process
  • Warnings: All warnings that occur during the build process

Based on these attributes, we can analyze module dependencies, module percentages, compile times, and so on, but just get a sense of how this works, and the community has provided us with a number of tools that can be used with less effort.

Visual analysis tool

Webpack Analysis

Webpack Analysis is an official visual Analysis tool provided by Webpack. Compared with other tools, it provides a more complete view and more powerful. To get a set of analysis views, simply drag the stats.json file generated by the webpack –json > stats.json command from the previous section into the page:

Click on modules/chunks/ Assets and the page will render the corresponding dependency diagram. For example, click modules:

In addition to modules/chunks/assets, Hints in the upper right menu bar can also check the processing time of each stage and module in the construction process, which can be used to analyze the performance bottlenecks of the construction:

Hints does not support webPack 5 output yet. Wait for the official update.

Webpack Analysis provides a very complete Analysis perspective with almost no distortion of information, but this also means that it is more difficult to get started and the information is more noisy. Therefore, the community also provides a simplified version of WebPack-Deps-Tree, which has similar usage but simpler usage and clearer information. Readers can compare and cross use according to the actual scene.

Webpack Visualizer

Webpack Visualizer is an online analysis tool. Once again, just drag the stats.json file to the page to see the bundle’s composition, level by level, from folder to module:

In addition to the online version, Webpack Visualizer also provides a plugin version of the Webpack-Visualizer-Plugin tool, but this plugin is in disrepair and only compatible with Webpack 1.x, so it’s almost useless now.

In addition, the online tool Webpack Chart also provides similar functionality, which is highly compatible and won’t be covered here.

Webpack Bundle Analyzer

Webpack-bundle-analyzer is a webpack plug-in. With a simple configuration, you can obtain the statistics of module distribution in the form of Treemap after the webpack runs. Users can carefully compare treemap content to infer whether it contains duplicate modules, unnecessary modules, and other scenarios, such as:

const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
  .BundleAnalyzerPlugin;

module.exports = {
  ...
  plugins: [new BundleAnalyzerPlugin()],
};
Copy the code

The local view page is automatically opened by default after compiling:

In addition, webpack-bundle-size- Analyzer provides similar, but command-line view-based analysis functions. You can use webpack-bundle-size- Analyzer to perform automatic analysis and automatic warning functions.

Webpack Dashboard

Webpack-dashboard is a command line visualization tool that displays compilation progress, module distribution, and production information in real time during compilation. Similar to Webpack-bundle-size analyzer, webpack-Dashboard also requires a few simple modifications to run, starting with the registration of plug-ins:

const DashboardPlugin = require("webpack-dashboard/plugin");

module.exports = {
  // ...
  plugins: [new DashboardPlugin()],
};
Copy the code

Second, change the way webPack is started. For example, the original start command might be:

"scripts": {
    "dev": "node index.js", # OR
    "dev": "webpack-dev-server", # OR
    "dev": "webpack",}Copy the code

Change the value to:

"scripts": {
    "dev": "webpack-dashboard -- node index.js", # OR
    "dev": "webpack-dashboard -- webpack-dev-server", # OR
    "dev": "webpack-dashboard -- webpack",}Copy the code

After that, you can see a nice visual interface on the command line:

UnusedWebpackPlugin

Finally, UnusedWebpackPlugin can be shared. It can reverse find out which files are not used in the project according to webpack statistics. I will use them in the daily reconstruction work of various projects, which is very practical. Usage is also relatively simple:

const UnusedWebpackPlugin = require("unused-webpack-plugin");

module.exports = {
  // ...
  plugins: [
    new UnusedWebpackPlugin({
      directories: [path.join(__dirname, "src")].root: path.join(__dirname, ".. /"),})]};Copy the code

In the example, directories are used to specify a file directory that needs to be analyzed; Root specifies the root path, which is related to output. After configuring the plug-in, webPack prints out what files are not being used in the directories after each run:

conclusion

To do a good job, you must sharpen your tools. The tools shared above all solve similar problems — building analysis, with slightly different emphasis, usage, and interaction patterns. Readers can choose the best of the best based on the actual situation.