Since it takes about 30 minutes for a new project to send and pack, it seriously delays the end time, so I specially check relevant documents to optimize the packaging speed and strive to leave work earlier, ^_^.

Analyzing package files

To optimize, analyze. We first want to know what is slowing down our packaging speed?

Generate file analysis after packaging

We can use the webpack-bundle-Analyzer plug-in to analyze the generated files we pack

  • The installation
npm i webpack-bundle-analyzer -D
Copy the code
  • use

Modify the webpack.prod.conf.js file

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin // After the build is complete, The browser will automatically open localhost: 8080 webpackConfig. Plugins. Push (new BundleAnalyzerPlugin ({analyzerPort: 8080, generateStatsFile:false}))Copy the code

You can see the details of the packed file through the picture

The packaging progress bar is displayed, showing the percentage of the packaging progress

Simple-progress-webpack-plugin can display the percentage of packaging

  • The installation
npm i simple-progress-webpack-plugin -D
Copy the code
  • use

Modify the webpack.prod.conf.js file

const SimpleProgressWebpackPlugin = require( 'simple-progress-webpack-plugin')... plugins: [ new SimpleProgressWebpackPlugin() ] ...Copy the code

The effect is as follows:

Control of resource and dependency packages

As can be seen from the above progress, during the packaging process, the lag is too long in the compressed area. When the project becomes more and more bloated, we need to sort out the static resources and dependent packages of the project.

  • Pictures too large can be compressed, here is a good compression link

  • Dependencies that are not used in a project can be removed, and dependencies that can be referenced on demand can be referenced on demand

The use of ElementUI and Echarts in the project are all references to vue. prototype, now on demand references.

Reduce file search scope

  • Set up theresolve.aliasField to avoid packaging if relative path access orimportFiles are searched and parsed layer by layer
resolve: {
  alias: {
    The '@': resolve('src')}}Copy the code
  • The reasonable configurationextensionsextension

Resolve. Extensions can automatically resolve the identified extensions, but if there are too many extensions, the resolution process will be too much, so we need to properly configure the extension, do not configure too many extensions, the project references many files, the extension is put first, our project is mostly vue, JS files. You can just use those two.

resolve: {
  extensions: ['.vue'.'.js']}Copy the code
  • loaderPreprocessing file incrementincludeMatch specific conditions

After the matching directory is specified during the preprocessing of various files, WebPack will not loop through other directories when parsing files, speeding up the parsing speed.

happypackMultithreaded execution

Webpack performs single-threaded preprocessing of files, and we can use Happypack to multithread processing of files.

  • The installation
npm i happypack  -D
Copy the code
  • use

Modify the webpack.base.js file

const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
module: {
  rules: [
    {
      test: /\.js$/,
      loader: 'happypack/loader? id=babel'// Replace 'happypack/loader' include: [resolve('src')]}]}, plugins: [new HappyPack({// id id of the loader that needs to be processed:'babel'Loaders: [{loader:'babel-loader',
        options: {
          presets: ['es2015'],
          cacheDirectory: true
        }
      }
    ],
    threadPool: happyThreadPool
  })
]
Copy the code

babel-plugin-dynamic-import-nodeAsynchronous loading

The babel-plugin-dynamic-import-node plugin replaces import() with require compilation

  • The installation
npm i babel-plugin-dynamic-import-node -D
Copy the code
  • use

Modify the. Babelrc file

"env": {
  "development": {
    "plugins": ["dynamic-import-node"]},"production": {
    "plugins": ["dynamic-import-node"]}}Copy the code

Note: There are no Chunk Files after using the plugin build.

DllPluginThe subcontract

Isolate third-party packages through the DllPlugin plugin

  • newwebpack.dll.conf.js
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require("clean-webpack-plugin");

module.exports = {
  entry: {
    vendor: [
      'vue'.'vue-router'.'vuex'.'axios'.'element-ui'.'echarts'
    ]
  },
  output: {
    filename: '[name]_dll_[hash:6].js'Resolve (__dirname,'.. /static/dll'),
    library: '[name]_dll_[hash:6]'
  },
  plugins: [
    new CleanWebpackPlugin({ 
      root: path.resolve(__dirname, '.. /static/dll'),
      dry: false// Enable delete file}), new webpack.dllPlugin ({name:'[name]_dll_[hash:6]',
      path: path.resolve(__dirname, '.. /static/dll'.'[name].dll.manifest.json')]}});Copy the code
  • Modify thewebpack.prod.conf.js

Add DLL. Js to HTML dynamically using add-asset-html-webpack-plugin.

Need to pay attention to

  1. Add-asset-html-webpack-plugin was introduced after HtmlWebpackPlugin.

  2. There is a problem with html-webpack-plugin depending on package version 4.0.0-alpha. The path added to the plugin will be undefined

const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin'); . Plugins: [/ / insert DLL json new webpack DllReferencePlugin ({context: path. Join (__dirname), the manifest: require ('.. /static/dll/vendor.dll.manifest.json')}), new HtmlWebpackPlugin (), / / insert DLL js new AddAssetHtmlPlugin ([{publicPath: config. Build. AssetsPublicPath +'static/dll/', // The path injected into the HTML outputPath:'static/dll/'Filepath: resolve()'static/dll/*.js'), // File paths includeSourcemap:false.typeOfAsset: "js"}]]Copy the code

conclusion

After the above optimization, the package of the project lasts from 30 minutes to less than 2 minutes. There is still room for optimization on the whole, and other optimization methods such as CDN can be used.

Other summary articles:

  • Background management project summary
  • Component communication processing scheme

Welcome to pay attention to the public number, we communicate and progress together.