Describes a wave


Recently the front-end interview has been tested webpack optimization should be many, no doubt webpack optimization is one of the knowledge points we must master the front-end, so this article from the packaging speed analysis, packaging optimization. I’m going to skip the basic usage of Webpack and just go through it.

One, packaging analysis

1.1 Analysis of packaging speed

The speed-measure-webpack-plugin is used here. You can check the packaging time of each plugin and loader to compare the difference before and after optimization.

npm i speed-measure-webpack-plugin -D
Copy the code

Configuration of cli2, with cli3 is different

	//webpack.config.js ------------->cli2
	const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
    const smp = new SpeedMeasurePlugin();

    module.exports = smp.wrap(webpackConfig, {
      plugins: [
      	// The plugins used]});// cli3
    const SpeedMeasurePlugin = require('speed-measure-webpack-plugin')
    const smp = new SpeedMeasurePlugin({
      outputFormat: 'human'
    })
    module.exports = {
      configureWebpack: smp.wrap({
        plugins: []})}Copy the code

After configuring the re-run item, you can see the lethal dose:

1.2 Packing Volume

Look at the packaging speed, but also look at the size of the module. Installing a plug-inwebpack-bundle-analyzer, can be installed in the port after8888

To configure it, simply import it and write it directly to plugins

const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const webpackConfig:{
	...
    plugins: [...new BundleAnalyzerPlugin()  // Be sure to place it after other plug-ins]}Copy the code

Second, packaging optimization

2.1 Multi-threaded Packaging

At present, there are three multithreading packages used more:Copy the code
  • Thread-loader (recommended for webpack4.0)

  • parallel-webpack

  • HappyPack

In my older projects, HappyPack. Allows Webpack to do this by splitting tasks into multiple sub-processes for concurrent execution, and then sending the results back to the main process. The installation

npm install --save-dev happypack
Copy the code
//webpack.config.js
const HappyPack = require('happypack')
const os = require('os')
//os.cpus returns an array of objects containing information about each CPU/ kernel installed
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length })


const webpackConfig:{
	...
    plugins: [...new BundleAnalyzerPlugin()  // Be sure to place it after other plug-ins
    ++++
    new HappyPack({
      id: 'happy-js'.loaders: ['babel-loader? cacheDirectory=true'].threadPool: happyThreadPool,// Share the process pool})].module: {
		rules:[
        	 {
              test: /\.js$/.// loader: 'babel-loader', // happypack instead
              loader: 'happypack/loader? id=happy-js'.// Add new HappyPack build loader
              include: [resolve('/'), resolve('test'), resolve('.. /.. /node_modules/webpack-dev-server/client'],},]}}Copy the code

2.2 Code Compression

The older version of webpack is uglifyjs-webpack-plugin, while the newer version is terser-webpack-plugin. We use uglifyjs-webpack-plugin here

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')


plugins: [new UglifyJsPlugin({
        uglifyOptions: {
          mangle: {      
            safari10: true    
        },
          compress: {
            warnings: false.drop_debugger: false.// Remove debug and console
            drop_console: false.parallel: true.// Use multiple processes running in parallel to speed up builds}},sourceMap: config.build.productionSourceMap,
        cache: true.parallel: true}),]Copy the code

2.3 Enabling Cache

2.3.1 hard – source – webpack – the plugin

The hard-source-webpack-plugin is available from webpack4.0 and is easy to install

npm i -D hard-source-webpack-plugin
Copy the code
//	webpack.config.js
  	const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

    module.exports = {
      / /...
      plugins: [
        new HardSourceWebpackPlugin() // <- just add this line of code]}Copy the code

2.3.2 dllPlugin

Currently, DLLS are no longer maintained. The main principle is to pack third-party dependencies in advance and bring the packaged JSON mapping files into the project so that you don’t have to pack the same third-party dependencies every time

The usage method is more cumbersome than hardSourceWebpackPlugin:

	/ / new webpack. DLL. Conf. Js
    const webpack = require('webpack');
	const path = require('path');
    
    module.exports = {
        entry: {
            vendor: ['vue'.'vuex'.'vue-router'. Required dependency]},output: {
        	path: path.resolve(__dirname, '.. /static/js'),
            filename: 'dll.[name].js'
        },
        plugins: [
            new webpack.DllPlugin({
                path: '[name]-manifest.json'.name: '[name]'.context: __dirname 
            })
        ]
    }
Copy the code

Perform webpack – config . / build/webpack. DLL. Conf. Js will generate DLL in static/js folder. Vendor. Js and mainfest is generated in the root directory. The json, then in webpack. Config. Introduced in js

     // webpack.base.conf.js
     const manifest = require('.. /manifest.json')    

     // in the plugin
     plugins: [
       new webpack.DllReferencePlugin({
           mainfest
        })
     ]
Copy the code

Finally, map it into index.html

<script type="text/javascript" src="/static/js/dll.vendor.js"></script>
Copy the code