preface

In the last two chapters we have covered the JavaScript packaging mechanism and all of WebPack’s built-in configurations, but when the business functionality of a project reaches a certain scale and the default configurations are no longer sufficient to meet development and user expectations, we need to optimize the WebPack configuration.

There are a few basic rules for optimization:

  • First know what to optimize;
  • Optimize the points to be optimized;
  • Measure the impact on the project before and after optimization;

The most intuitive way to know exactly how to optimize an app is to analyze its output file, but webPack files can be very large and unreadable. Here are some visual analysis tools that can help you quickly locate problems.

Measure build time

The first step in optimizing the speed of WebPack builds is knowing where to focus your efforts. We can use the speed-measurement-webpack-plugin to measure the time spent in each phase of your WebPack build:

Step 1: Install the speed-measurement-webpack-plugin

npm install speed-measure-webpack-plugin --save-dev
Copy the code

Step 2: Configure

// Analyze the packing time
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
// ...
module.exports = smp.wrap(prodWebpackConfig)
Copy the code

It is able to:

  • Analyze the total packaging time;
  • Time for each plug-in and loader;

It is convenient for developers to locate packaging time bottlenecks.

Analyze the contents of the package

Webpack-bundle-analyzer scans bundles and builds a visualization of their internal contents. Use this visualization to find large or unnecessary dependencies.

Step 1: Install Webpack-Bundle-Analyzer

npm install webpack-bundle-analyzer --save-dev
Copy the code

Step 2: Configure

// Analyze the package contents
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
  plugins: [
    / / open BundleAnalyzerPlugin
    new BundleAnalyzerPlugin(),
  ],
};
Copy the code

Typically running in a production version, the plug-in will open a statistical results page in your browser.

Note: WebPack4 inproductionEnvironment is started by defaultModuleConcatenationPlugin(Precompiling all modules into a closure to speed up code execution in the browser), it may incorporate a portion of the module in the Webpack-bundle-Analyzer output, making the report less detailed. If you use this plugin, disable it during the analysis. The Settings are as follows:

module.exports = {
  // ...
  optimization: {
    // 
    concatenateModules: false,}};Copy the code

Specifically, using webpack-Bundle-Analyzer, you can visually reflect:

  • What’s in the package;
  • What is the size of each file in the total, which files are large, think about why they are large, whether there is an alternative, whether all the code it contains is used;
  • The inclusion relationship between modules;
  • Are there duplicate dependencies? Is there a library that is duplicated in multiple files? Or are there multiple versions of the same library in the bundle?
  • If there are similar dependencies, try to use one to implement similar functionality.
  • The compressed size of each file.

3. Online analysis tools

If you don’t like the idea of having your measurement and analysis package installed locally, there are several online measurement tools recommended, but they all require webPack statistics files.

1. Generate statistics filesstats.json

When compiling the source code with WebPack, the user can generate a JSON file that contains statistics about the module. These statistics can be used to analyze an application’s dependency graph and to optimize compilation speed. The file is usually generated as follows:

–profile –json > stats. Json, for example:

webpack --config webpack.config.prod.js --profile --json > stats.json
Copy the code
  • --profile: Records the time spent during the build process
  • --json: Output the build results in JSON format, and output only one at the end.jsonThe file, the file (stats.json) includes all build-related information
  • > stats.json: is a pipe command in UNIX/Linuxwebpack --profile --jsonThe output is piped tostats.jsonIn the file

After executing this command, an additional stats.json file will be added to the project. Next, upload the stats.json file to the following online tool to visualize the composition of the package.

Common online tools are:

  • Webapck Analyse, the official visualization analysis tool, generates a diagram that lets you visualize your project’s dependencies, module size, time spent, etc.
  • Webpack Visualizer: Generates a pie chart to visualize the bundle content;
  • Webpack Bundle Optimize Helper: This tool will analyze your bundle and suggest operational improvements to reduce the bundle size.

2. Official visualization analysis tool Webapck

Webapck Analyse is an online Web application that gives you a more comprehensive analysis of packages, and it draws a graph of all the dependencies in your project, which is useful for projects with few dependencies.

Open Webapck Analyse and upload stats. Json:

Webpack Analyse doesn’t develop your stats. Json file of choice to the server, but instead parses it locally in the browser, so you don’t have to worry about leaking your code. After selecting the file, you immediately have the following renderings:

Modules: Displays all Modules, each with a file. It also contains the dependency graph, module path, module ID, module Chunk and module size of all modules.

Chunks: Displays all Chunks of code. A block of code contains multiple modules. It also contains the ID, name, size of the code block, the number of modules contained in each code block, and the dependency diagram between the code blocks.

Assets: Display all output file resources, including.js,.css, images, etc. It also includes the file name, size, and which code block the file comes from;

Warnings: Displays all Warnings that appear during the build.

Errors: Displays all Errors that occur during the build process.

Hints: Shows time consuming in handling each module.

3. Webpack Visualizer analysis tool

Visualize and analyze your Webpack bundle to see which modules are taking up space and which might be duplicate.

Available as a plug-in or online, it is a relatively new tool.

Method 1: Use as a plug-in

npm install webpack-visualizer-plugin --dev-save
Copy the code

Configuration:

// Analyze the package contents
const Visualizer = require('webpack-visualizer-plugin');
module.exports = {
  plugins: [
    / / open the Visualizer
    // The default output is stats.html, in this case statistics.html
    new Visualizer({
      filename: './statistics.html'})]};Copy the code

Then open statistics.html directly in your browser to see the analysis results:

Method 2: Online use

Open the chrisbateman. Making. IO/webpack – vis… To see the analysis results, upload stats. Json.

4. Webpack Bundle optimize Helper

Open the webpack. Jakoblind. No/optimize /, upload stats. Json can see the results of the analysis and optimization Suggestions:

Four,

In total, we covered the following five measurement tools, each of which provides a different perspective on package analysis, such as:

  • During development, I personally often use the Webpack Visualizer when introducing new packages to a project, and the pie chart gives immediate feedback on the size ratio;
  • When analyzing the time spent per build, compared to other builds4,speed-measure-webpack-pluginThe ability to get time for each plugin and loader helps you focus on the plugin that needs to be optimized.
  • webpack-bundle-analyzerThe ability to display bundle content as a convenient, interactive, and scalable tree form;
  • Webapck Analyse relative to others4Species, able to carry out all-round analysis of the package;
  • Relative to others4The WebPack bundle optimize Helper can provide suggestions for operational improvements.

Past webPack series

Best configuration for Webpack refers to north

How it works: Hand write a JavaScript wrapper

If you think it’s good, just like it! 👍 👍 👍

For more on this series,Go to the Github blog home page

Walk last

  1. ❤️ Have fun, keep learning, and always keep coding. 👨 💻

  2. If you have any questions or more unique opinions, please comment or directly contact Mr. Bottle (scan the code to follow the public account and reply 123)! 👀 👇

  3. 👇 welcome to pay attention to: front bottle gentleman, updated daily! 👇