Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize the construction speed of Webpack

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to optimize the construction speed of Webpack, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

How to output Webpack Construction Analysis

.json file that outputs Webpack build information: webpack-- profile-- json > starts.json

-- profile: record the time-consuming information in the build

-- json: output the build results in json format, with only one json file (containing all the build information)

Web visual view build analysis: get the webpack build information file starts.json, how to do a good visual view?

1. Plan 1: through the visual analysis tool Webpack Analyse, it is an online Web application, and you can upload starts.json files.

two。 Option 2: install the webpack-bundle-analyzer tool npm I-g webpack-bundle-analyzer, generate starts.json and directly execute webpack-bundle-analyzer in its folder directory, the browser will open the corresponding web page and display the construction analysis document address webpack-bundle-analyzer

3. Webpack-dashboard is a tool for statistics and optimization of webpack logs, which can display log information in tabular situations. This includes the build process and status, logs, and a list of modules involved

4. Jarvis is a webpack performance analysis plug-in based on webapck-dashboard. The results of performance analysis are displayed in the browser, and the GitHub document address is more beautiful and clear than webpack-bundler-anazlyer.

Npm I-D webpack-jarvis

Webpack.config.js configuration:

Const Jarvis = require ("webpack-jarvis"); plugins: [new Jarvis ({watchOnly: false, port: 3001 / / optional: set a port})]

Port: listening port. Default is 1337. The listening panel will listen on this port, usually like http://localhost:port/.

Host: domain name. Default is localhost. Domain name is not restricted.

WatchOnly: only listens to the compile phase. The default is true. If false,jarvis is high, it not only runs during the compilation phase, but also remains running after the compilation is complete.

Interface: you can see that the build time is: Time: 11593ms (as an optimization time comparison)

Webpack configuration optimization

Webpack starts from the configured Entry, parses the import statements in the file, and then parses them recursively.

For the import statement Webpack, the following actions are done:

1. Find the corresponding file to be imported according to the import statement

two。 Use the Loader in the configuration to process the file according to the suffix of the file to be imported (for example, babel-loader processing is required to use ES6)

In view of these two points, the search path can be optimized.

1. Optimize Loader configuration

It is time-consuming for Loader to process the conversion of files, so it is necessary to have as few files as possible processed by Loader.

{

Test: /\ .js $/

Use: [

'babel-loader?cacheDirectory',// enables the conversion result cache

]

Include: path.resolve (_ _ dirname, 'src'), / / only use babel-loader for files in the src directory

Exclude: path.resolve (_ _ dirname,'. / node_modules'), / / exclude files in the node_modules directory

}

two。 Optimize resolve.modules configuration

Resolve.modules is used to configure webpack to find third-party modules in which directories. The default is ['node_modules']. However, it will first go to the. / node_modules of the current directory, and then go to.. / node_modules if not. Finally, go to the root directory.

Therefore, when the installed third-party modules are placed in the root directory of the project, there is no need for a default layer-by-layer search to directly indicate the absolute location of storage.

Resolve: {modules: [path.resolve (_ _ dirname, 'node_modules')],}

3. Optimize resolve.extensions configuration

When importing a path without a file suffix, webpack automatically takes a suffix to try to ask if the file exists, while resolve.extensions is used to configure the list of attempted suffixes; the default is extensions: ['js','json']

And when you encounter require ('. / data'), webpack will try to find data.js first, but not data.json;. The longer the list is, or the later the correct suffix is, the more times you will try.

Therefore, in order to improve the build optimization during configuration, you should follow:

1. File suffixes with high frequency are given priority.

two。 The list is as small as possible

3. When writing import statements, try to write the suffix.

Because more jsx is used in the project, configure extensions: [".jsx", ".js"]

Check the construction speed after basic configuration: Time: 10654ms; before configuration: Time: 11593ms

Optimize with DllPlugin

When using webpack for packaging, for dependencies on third-party libraries, such as react,react-dom, which will not be modified, you can package it separately from the business code.

As long as the dependent library version is not upgraded, webpack only needs to package the project business code and directly go to the dynamic link library to obtain the module that needs to be imported; instead of compiling the third-party library, the third-party library only needs to be packaged once.

What needs to be done to access:

1. Extract dependent third-party modules and package them into separate dynamic link libraries

two。 When the module to be imported exists in the dynamic link library, let it get it directly from the link library

3. All dynamic link libraries that the project depends on need to be loaded

Access tool (webpack is built-in)

1. DllPlugin plug-in: used to package individual dynamic link library files

2. DllReferencePlugin: used to introduce the dynamic link library files packaged by the DllPlugin plug-in into the main configuration files

Configure webpack_dll.config.js to build dynamic link library

Const path = require ('path'); const DllPlugin = require (' webpack/lib/DllPlugin') Module.exports = {mode: 'production', entry: {/ / put React related modules into a dynamic link library react: [' react','react-dom','react-router-dom','react-loadable'], librarys: ['wangeditor'], utils: [' axios','js-cookie']} Output: {filename:'[name]-dll.js', path: path.resolve (_ _ dirname, 'dll'), / / the global variable name where the dynamic link library is stored Add _ dll_ to prevent global variables from colliding with library:'_ dll_ [name]'}, / / global variable names of dynamic link libraries, which need to be consistent in output.library It is also the field value of name in the output manifest.json file / / for example, there is "name": "_ dll_react" plugins in the react.manifest.json field: [new DllPlugin ({name:'_ dll_ [name]', path: path.join (_ _ dirname, 'dll',' [name] .room.json'})]}

Used in webpack.pro.config.js

Const DllReferencePlugin = require ('webpack/lib/DllReferencePlugin');... Plugins: [/ / tell webpack which dynamic link libraries are used new DllReferencePlugin ({manifest: require ('. / dll/react.manifest.json')}), new DllReferencePlugin ({manifest: require ('. / dll/librarys.manifest.json')}) New DllReferencePlugin ({manifest: require ('. / dll/utils.manifest.json')}),]

Note: in the webpack_dll.config.js file, the name parameter in DllPlugin must be the same as in output.library; because the name parameter of DllPlugin affects the name; of the output manifest.json and the DllReferencePlugin in webpack.pro.config.js reads the name of manifest.json, using the value as the global variable name when getting dynamic link library content from global variables

Perform a build

1. Webpack-progress-colors-config. / webpack.dll.config.js

2. Webpack-progress-colors-config. / webpack.prod.js

Introducing dll.js file into html

Build time comparison: ["11593ms", "10654ms", "8334ms"]

Optimization of HappyPack parallel Construction

Core principle: decompose the most time-consuming loader file conversion task in webpack into multiple processes for parallel processing, thus reducing the construction time.

HappyPack

Access to HappyPack

1. Installation: npm I-D happypack

two。 Reconfigure the rules section and hand over the loader to happypack for allocation:

Const HappyPack = require ('happypack'); const happyThreadPool = HappyPack.ThreadPool ({size: 5}); / / build a shared process pool containing 5 processes. Plugins: [/ / happypack parallel processing new HappyPack ({/ / using ID to represent the current HappyPack is used to process a specific class of files Corresponding to use in rules: id: 'babel', loaders: [' babel-loader?cacheDirectory'], / / default setting loader processing threadPool: happyThreadPool,// uses shared pool processing}), new HappyPack ({/ / using a unique ID to represent the current HappyPack is used to process a specific class of files Corresponding to use in rules id: 'css', loaders: [' css-loader', 'postcss-loader',' sass-loader'], threadPool: happyThreadPool})], module: {rules: [{test: /\. (js | jsx) $/ Use: ['happypack/loader?id=babel'], exclude: path.resolve (_ _ dirname,'. / node_modules'),}, {test: /\. (scss | css) $/, / / the mini-css-extract-plugin used to extract css here Use: [MiniCssExtractPlugin.loader,'happypack/loader?id=css'], include: [path.resolve (_ _ dirname,'src'), path.join (_ _ dirname,'. / node_modules/antd')]},}

Parameters:

1. Threads: indicates that several sub-processes are opened to process this type of files. The default is 3.

2. Verbose: whether to run HappyPack output log. Default is true.

3. ThreadPool: represents a shared process pool, that is, multiple HappyPack examples use child processes in a shared process pool to process tasks in case too many resources are occupied

Code compression uses ParallelUglifyPlugin instead of its own UglifyJsPlugin plug-in

The built-in JS compression plug-in is executed in a single thread, while webpack-parallel-uglify-plugin can execute in parallel

Configuration parameters:

1. UglifyJS: {}: configuration for compressing ES5 code, Object type

2. Test: / .js $/ g: use rules to match which files need to be compressed by ParallelUglifyPlugin. The default is / .js$/.

3. Include: []: use regular to include compressed files. Default is [].

4. Exclude: []: use rules to include files that are not compressed. Default is []

5. CacheDir:'': cache the compressed result. The next time the same input is encountered, the compressed result is directly obtained from the cache and returned. There is no cache by default, and the cache is enabled to set a directory path.

6. WorkerCount:'': start several sub-processes to perform compression concurrently. The default is the number of CPU cores of the current running computer minus 1.

7. SourceMap: false: whether to generate the corresponding Source Map for the compressed code. Default is not generated.

... Minimizer: [/ / webpack:production mode is equipped with js compression by default, but if css compression is set here Js compression also needs to be reset, because using minimizer automatically cancels the default configuration of webpack new optimizeCssPlugin ({assetNameRegExp: /\ .css $/ g, cssProcessor: require ('cssnano'), cssProcessorOptions: {discardComments: {removeAll: true}}, canPrint: true}), new ParallelUglifyPlugin ({cacheDir:' .cache /' UglifyJS: {output: {/ / whether to output readable code Spaces and tabs will be preserved. Default is output. In order to achieve a better compression effect, you can set it to false beautify: false, / / whether to retain comments in the code, default to retain, in order to achieve a better compression effect. Can be set to false comments: false}, compress: {/ / whether to output a warning message when UglifyJS deletes unused code. Default is to output warnings: false, / / whether to delete all console statements in the code. Default is not deleted. Will delete all console statements drop_console: true, / / variables that are defined but used only once, such as var x = 1 Y = x, converted to y = 1. Default is No collapse_vars: true,}),]

Comparison of construction results: ["11593ms", "10654ms", "8334ms", "7734ms"]

The overall build speed has slowed down from 12000ms to 8000ms.

"accumulate long steps and travel thousands of miles"-keep updating, leave a like and follow if you like!

The classic articles of the past:

CORS cross-domain resource sharing that you don't know

Koa logging Middleware package Development (log4js)

Git operations necessary for teamwork

Deploy a node production environment using pm2

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report