Performance optimization of webpack engineering practice summary

1. Code size optimization

  1. JavaScript compression :
    In the mode=productioncase, Webpackare automatically compressed code, we can customize your own compression tool, it recommended here terser-webpack-plugin, it is the Webpackofficial maintenance of a plugin, terserto compress JavaScriptthe code. UglifyJSIn the compression ES5done very good, but with the ES6popularity of syntax UglifyJSin ES6the code compression is not good enough, so with uglify-esthe project, but after uglify-esthe project is not maintained, terserfrom uglify-esa branch to pull the project to continue to maintain. terser-webpack-pluginIt has with Uglifyjs-webpack-pluginthe same parameters.
  2. to sum up:
  • Reasonably divide code responsibilities, and appropriately use on-demand loading schemes;
  • Make good use of webpack-bundle-analyzerplug-ins, to help analyze the Webpackmodule after the package dependencies;
  • Set a reasonable SplitChunkspacket;
  • For some UIcomponent library, e.g. AntDesign, ElementUImaterials may be used bable-plugin-importsuch tools are optimized;
  • Use lodash、momentjsof these libraries, do not fall into the introduction, to demand the introduction, momentjsyou can use date-fnsthe library instead;
  • Rational use of hashplaceholders, to prevent hashrecurring, thereby leading to changes in the file name HTTPcache expires;
  • Use polyfillit reasonably to prevent redundant code;
  • The use of ES6grammar, try not to use the code with side effects, in order to enhance Tree-Shakingthe effect;
  • Use Webpackof the Scope Hoisting(scope lift) function, and Scope Hoistingis webpackthrough ES6static analysis grammar to analyze the dependencies between the modules, the modules as far as possible into the same function
  1. CSS compression :
    cssnanois based on postcssa powerful plug-in package, which integrates 30multiple plug-ins, just execute a command, it is possible for us CSSto do many different types of optimizations, such as:
  • Remove spaces and the last semicolon;
  • Delete comments;
  • Optimize font weight;
  • Discard duplicate style rules;
  • Compression selector
  • Reduce handwriting attributes;
  • Merger rules
  1. Image resource optimization:
    Usually our code size is much smaller than the image size, and sometimes the code of the entire page is not as big as a header image. Fortunately, image resources will not block browser rendering, but unreasonable image size will also consume a certain amount of code. You can use: url-loader、svg-url-loader 和 image-webpack-loaderto optimize pictures, you can also use Sprite to optimize picture resources, as shown below:
  • url-loaderAccording to the configuration, static files smaller than a certain volume can be inlined into our application. When we specify limitthis optionsoption, it will be encoded into the file smaller than no configuration Base64data urland the urlreturn, which can be linked into the picture within JavaScriptthe code, and save a HTTPrequest.
  • svg-url-loaderThe working principle is similar url-loader, except that it uses URL encodingrather than Base64for file encoding for the SVGpicture, it svg-url-loader's in this way that is effective, because the SVGplain text file on the file essence, this URL encodingcoding of scale become more pronounced.
  • If we project a particularly large number of small pictures, for example, there are a lot of iconclass icon, this time it is recommended to use Sprite map (CSS Sprite)to merge these small diagram to a large map, and then use background-positionto set the location of the picture, we can save many times in such a way Small picture request.
  • For the big picture, it can be used image-webpack-loaderto compress images, image-webpack-loaderit supports the JPG、PNG、GIF 和 SVGpicture format, so we met all of these types of pictures will use it.

2. Enhance the cache hit rate

  1. Browser cache policy and Webpackcache configuration, use your browser's persistent caching scheme in two steps, the first step is we generally static resources will (JavaScript 、CSS、图片字体文件等)these changes do not often find a more suitable file server storage, such as put CDNon the server and configure a separate domain name, such as Baidu common CDNdomain is: x.bdimg.comand x.bdstatic.comthe domain name, the benefits of doing so are:
  • Ensure the separation of dynamics and statics. Separate deployment of dynamic pages and static resources is conducive to better maintenance of services;
  • CDNMay be closer to the user's terminal, expedited services, you can view the detailed CDNprinciples;
  • Resources are not static dynamic logic, a separate header page request can be reduced Cookieand so the field necessary to reduce the HTTPbandwidth.
  • After the static resources stored in a separate server, you need to do is a reasonable allocation of HTTPcache-related agreements, such as we used Cache-Controlto tell the browser, the current file max-age: Cache-Control: max-age=31536000
    set above the file cache time of year (31536000=360024365).
  1. After the completion of the first step, the second step is to rename the static resources for the change happened, so although the use of static files CDNand cache strong, but as long as the content changes, then the path to the file (URL) changes, the browser The browser will still request the download again:

  2. Therefore, cache related Webpackpackaging optimization, the rational use of HTTPcache-related request header field, and mating Webpackof chunkhashand contenthashcan be done according to changes in file contents and enhanced dependence browser cache, additional code changes in accordance with reasonable frequency resolution codes can be Play the biggest role of the cache, Webpackthe split code used in the dynamic loading method and optimization.splitChunks.

Three, function split code

  1. Code Webpack split mode:
    In Webpackin a total of three ways to split the implementation code (Code Splitting):
  • entryConfiguration: a plurality entryimplemented files;
  • Dynamic load (demand loading): write by actively using the code import()or require.ensuredynamically loaded;
  • Extracting common code: Use splitChunksconfigured to extract the common code.
  1. Setting higher weights cacheGroup; using testfunction for a type jsand cssare provided each cacheGroup. In addition, we can also use the testfunction to achieve a more refined matching, for example: Ignore the part of the file and so on.

Fourth, speed optimization

  1. When Webpack, after more than a project file, the build process will become slower, this time we need to do some optimization of the means to build speed. Affect Webpackthe speed of constructing the two "big": one loaderand pluginbuild process aspects, is a compression, optimizing these two things together, you can reduce a lot of the time posted.

  2. Compression speed optimization:
    relative to the build process, we compress relatively speaking only production package will do, and we addition to adding compression cacheand multithreading support outside a small space can be optimized. We use terser-webpack-plugincan open multiple threads and cache configuration time by the following:

const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    
    
    optimization: {
    
    
        minimizer: [
            new TerserPlugin({
    
    
                cache: true, // 开启缓存
                parallel: true // 多线程
            })
        ]
    }
};
  1. From the perspective of construction speed, how to improve the packaging speed, introduce the methods to improve the speed from the two dimensions of the construction process and compression. Among them, there are few points that can be optimized from the compression perspective, and the search process can be reduced from the search process, multithreading, and multithreading. compiled ahead and caching to optimize multiple angles, which focuses on reducing the use of several search process configuration, use thread-loaderand HappyPackto open multi-threaded, use DLLPluginto compile and use of pre- babel-loadercaching methods. In the actual project, it is not necessary to optimize the construction speed. If the project is simple, it is not necessary at all, and specific problems should be analyzed in detail. In any case, keep the Webpacklatest version is a simple yet effect a good way!

、 、 Tree-Shaking

  1. Tree-ShakingTerm is a front-end, intended to shake the tree means, in terms generally used to describe the front end to remove JavaScriptthe code useless context, which can effectively reduce the packing volume. Regarding Tree-Shaking, the Webpackofficial document has a very vivid description: you can imagine the application as a tree. The green color represents the source code sum actually used library, which is the living leaves on the tree. Gray represents useless code, which is the withered leaves on autumn trees. In order to remove the dead leaves, you must shake the tree to make them fall.

  2. Tree-Shaking realization of the principle:
    Tree-Shaking the essence is the elimination of useless JavaScriptcode. Useless code elimination (Dead Code Elimination)widely exists in traditional programming language compilers. The compiler can determine that certain codes do not affect the output at all, and then eliminate these codes. This is called DCE(Dead Code Elimination). Tree-ShakingIs DCEa new implementation Javascriptwith traditional programming languages is that JavaScriptmost cases are executed in the browser needs to be loaded via a network, and then parse JavaScriptthe file and execute.

  3. Webpack Tree-Shaking actual codes:
    in Webpackin Tree-Shakingneed with the mode=productionuse of, since Webpackthe Tree-Shakingactual points to achieve a two-step:

  • WebpackTo analyze their own ES6 Modulesintroduction and usage, remove unused importintroduced;
  • With tools (such as uglifyjs-webpack-pluginand terser-webpack-plugin) to delete, these tools are only mode=productionto be used will be.
  1. Configuration sideEffects:
    Webpack project, can be package.jsonused sideEffectsto tell webpackthe code which files have side effects, so that the file can rest assured that the code has no side effects of the use of Tree-Shakingoptimization. If your project is a library or tool libraries, you need to publish to other projects use, and the use of project ES6 Modulespreparation, no side effects, then the project can be package.jsonset up sideEffects:falseto tell use that item webpackcan rest assured that the project Tree-Shaking, without having to Consider side effects.

  2. Tree-ShakingIt is of great significance to front-end projects, an ideal world of ultimate optimization, and another ultimate ideal of front-end evolution. But the ideal is good, the reality is skinny, really play Tree-Shakinga strong role, we also need to maintain good habits in their daily development code:

  • To use the Tree-Shakingnecessity to ensure the module references are ES6standardized, many tools library or library provides ES6syntax library, for example, lodashthe ES6version lodash-es;
  • The introduction of on-demand module, to avoid "a hook", for example, we want to use lodashthe isNumbercan be used import isNumber from 'lodash-es/isNumber';insteadimport {isNumber} from 'lodash-es';
  • Reduce the side effect code in the code. Other component library, for example, AntDesignand ElementUIthese component library, itself developed its own Babelplug-ins, by way of plug-in modules to introduce on-demand, to avoid the fall of the introduction of all the components.

Guess you like

Origin blog.csdn.net/weixin_42614080/article/details/109921452