optimization

Optimizing webpack packaging speed has always been a pain point for all front-end developers. In order to speed up packaging and compilation, various techniques have emerged to optimize.

Among them, cache technology is an optimization method which can greatly improve the packaging speed and shorten the overall packaging time.

Webpack babel-loader Cache principle

Babel-loader can use cache technology when packaging, but the cache of babel-loader must be compiled once before the indexed files and file compilation results are cached in memory.

During subsequent compilations, if it is found that the indexed file has already been cached, the result of the compiled cache is directly referenced.

Cons: Must be packed once

HardSourceWebpackPlugin plug-in

Persistent caching of results to hard disk. The plugin’s mechanism is to mark the results with the file’s hashCode when the file is first compiled. Associate the compiled results with hashCode.

The second time the file is compiled, the local cache results are loaded first (SSD is very fast). The plug-in then computes the hashCode again from the file that needs to be compiled, and if the Code already exists in the cache, it skips compilation and prints the compiled result.

Here are a few questions to clear things up.

In fact, the cached result is not the final packaging result, but the result set compiled by Babel-loder. In the final packaging (merging the compilation result) case, if the imported file changes, the output file will load the compiled result from the cache and repackage it again to write dist, Because the output file does not change, it only changes when it is imported.

How to use it?

npm install hard-source-webpack-plugin --save
Copy the code

Add it to the webpack.config.js plug-in field

plugins: [
        new HardSourceWebpackPlugin(),
  ...
  ]
Copy the code

webpack 5

The effect of the HardSourceWebpackPlugin plugin is remarkable, and this feature point is now included in webpack5. Details through https://webpack.js.org/configuration/other-options/#cache to view.

When cache.type: “filesystem” is set, webpack internally enables filesystem caching and memory caching in a hierarchical manner. The priority for

Memory cache -> file cache -> Just-in-time compilation