Vue project Packaging Optimization Guide

Time:2021-8-11

For more information, please collect my blog:http://blog.tianzhen.tech

brief introduction

Vue cli is a very useful tool for Vue project scaffold generation. When a project goes online from the development environment to the production environment, it often encounters some problems: why is the packaged file 2MB large? Why is the loading of resources on the page very slow? Why is irrelevant code packaged in the same file? This paper mainly focuses on some optimization in the packaging process for the projects generated by Vue cli.

The version of Vue cli was V4 when this article was published.

Load routes on demand

If no additional configuration is made, when the front page of the project is opened, the project will load many codes unrelated to the current page at the same time, which affects the loading speed of our front page. The on-demand loading route (lazy loading) can solve this problem. We let webpack automatically identify and package different routing components into separate files.

Thanks to the encapsulation of Vue cli, we only need to write the route in this way to realize the route loaded on demand:

const routes = [
  {
    path: '',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home'),
    Meta: {Title: 'home'}
  }
  {
    path: '/about',
    name: 'about',
    component: () => import('@/views/about'),
    Meta: {Title: 'about'}
  },
]

Asynchronous component

The principle of asynchronous components is similar to that of loading routes on demand. Similarly, we only need to write code in a specific way:

export default {
  name: 'MyPage',
  components: {
    Test: () = > Import ('. / test') // asynchronously introduce components and let webpack package the code
  },
}

Analysis tools

To solve the problem that the packaged file is too large, we must first analyze what causes the file to be large and where the packaged size can be reduced.

Built in Vue cliwebpack-bundle-analyzerPlug in. By default, we modify itpackage.jsonThe packaging command in isnpm run build --reportYou can view visual packaging analysis:

{
  "scripts": {
    "build": "vue-cli-service build --report",
  },
}
$ npm run build

After executing the command, thedistGenerate one more in the directoryreport.htmlFile, open it in the browser, and you can see the analysis:

Vue project Packaging Optimization Guide

As can be seen from the figure, the library of moment occupies a lot of useless space. With this tool, we can analyze which files occupy space.

Package moment.js as needed

moment.jsThe reason for the large space is that the moment contains a large number of language resource files, which we don’t need.

Through the function of webpack itself, these useless contents can be discarded during packaging:

//Create a new vue.config.js in the project root directory
const webpack = require('webpack')
module.exports = {
  configureWebpack: config => {
    const plugins = [
      //Only Chinese language resources are reserved
      new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn/),
    ]
  },
}

Package lodash on demand

lodashIt is also a tool library commonly used in the front end. There are two schemes to reduce its packaging volume.

First, let’s write the code like this, and then choose any of the following methods to complete the optimization:

import { cloneDeep } from 'lodash'

const a = { k: 'v' }
const b = cloneDeep(a)

Use lodash es (recommended)

If you use the ES module, you can install it directlylodash-es

$ npm i lodash-es

Lodash webpack plugin

You can also uselodash-webpack-pluginPlug in to automatically remove unused lodash Code:

Note: this plug-in is in usefindSome necessary dependencies may be deleted, resulting in program errors. The solution is to complete the dependencies or replace themlodash-es

// vue.config.js
const LodashWebpackPlugin = require('lodash-webpack-plugin')

module.exports = {
  configureWebpack: config => {
    const plugins = [
      //Join this article
      new LodashWebpackPlugin(),
    ]
  },
}

Compressed code

The new version of Vue cli automatically compresses the code, so no additional configuration is required. If you are building a project using a legacy cli, you can queryterserRelated usage.

uglifyify.jsMaintenance has been stopped. Do not use this library anymore

Generate gzip file

Nginx can help us automatically compress resources into gzip files. If we can provide a compressed gzip file when packaging, the transmission will be faster.

Use herecompression-webpack-pluginplug-in unit:

$ npm i -D compression-webpack-plugin

To edit the webpack configuration:

// vue.config.js
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']

module.exports = {
  configureWebpack: config => {
    const plugins = [
      new CompressionWebpackPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
        threshold: 10240,
        minRatio: 0.8
      }),
    ]
    //Compress only in the production environment to improve the compilation speed during development
    if (process.env.NODE_ENV === 'production') {
      config.plugins = [...plugins, ...config.plugins]
      config.optimization = {
        splitChunks: {
          cacheGroups: {
            //Extract common module
            commons: {
              chunks: 'all',
              minChunks: 2,
              maxInitialRequests: 5,
              minSize: 0,
              name: 'common'
            }
          }
        },
      }
    }
  },
}

Note: gzip also needs server support. It is generally configured on nginx

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]