Vue project optimization background

The project was built with VUE-CLI3, and the project grew with the demand. The amount of code is also increasing. The file size of the project increases as well. But that’s where it gets really, really tricky. We also need to find a solution to deal with this, to improve the efficiency of the project. Before we think about optimization, let’s look at what kind of optimization we need to do in the structure of the previous project.

Optimization of past projects

In previous projects, our code responded to the user through server-side rendering. In this project structure. In the case of the code, it is up to the developer to introduce the relevant code base according to their own needs. Control of the code is basically handled according to team specifications. So the code introduced in the page is the code that the current page needs to execute. Code optimization is mainly shown in:

  1. Js, CSS code common code extraction, as needed to introduce
  2. Js, minimum compression of CSS code
  3. Image file compression
  4. Gzip compression

And so on. Related optimizations. We will not consider the processing of other properties here. Performance is handled primarily on a project-by-project basis. Leave the project performance optimization, in fact, are not convincing. Performance optimization varies from project to project. For example, a performance optimization plan that is suitable for one project may not be suitable for another project.

Vue – cli3 optimization

Vue-cli3 is primarily built on top of Webpack and Webpack-dev. So the focus should also be on optimizing our code by learning webPack-related configuration features. There are two ways to configure Webpack in VUE-CLI3. Two ways: ChainWebpack and configureWebpack. You can see the official tutorial for chainWebpack. With reference to the official document of VUE-CLI3, we began to further think about the actual optimization method. Let’s create a new vue.config.js file

module.exports = {

}
Copy the code

Before optimizing, let’s take a look at the project’s code. The project here is a test code I wrote that uses Element-UI for the interface.

  1. Minimization: code optimization, which we will do with chainWebpak. This is handled using Optimization in the WebPack configuration. Before we optimize, let’s take a look at the response code of the relevant file:

module.exports = {
  chainWebpack: config= > {
    config.optimization.minimize(true); }}Copy the code

Then we run our project and can see how the code works.

  1. Split code Split code is to put some related files into the corresponding file. So let’s set it up.
module.exports = {
    
    chainWebpack: config= > {
        config.optimization.minimize(true);
        config.optimization.splitChunks({
          chunks: 'all'}}})Copy the code

splitChunks

  1. Extract common code and use free CDN resources. First of all, why would a file be so big? To do further optimization. The main reason why this file is so large is that we have introduced different module libraries, such as vue, vuex, VUe-Router, Element-UI and other common libraries. So do we extract them? The answer is yes. We need to use externals to configure:
module.exports = {
    
    chainWebpack: config= > {
        config.optimization.minimize(true);
        config.optimization.splitChunks({
          chunks: 'all'
        })
        config.externals({
            vue: 'vue'.vuex: 'vuex'.'vue-router': "'vue-router'".'element-ui': "'element-ui'"}}})Copy the code

Ignore our module packaging with the externals parameter. Then we rerun the project to see what happens.

Our code has been reduced to 2.8m. However, there is a problem here that our code did not execute and reported an error. Because we need to introduce VUE, vuex, VUE-Router and so on into the project interface. We need to do something with the HTML. Instead of downloading the code and putting it into the project, we’re going to use free resources on the web.

Add these links to the index.html page. And then let’s run it and see what happens.

  1. Extract the CSS code into a single file.

Notice that we don’t see the CSS request in our request. That is because the CSS code is in the JS file, it will execute JS, will dynamically generate the CSS code style tag. So you put your CSS code in JS. This is also one of the causes of large files. At this point we need to extract the CSS code into the file. Here we just need to configure the CSS:


module.exports = {
  css: {
      extract: true
  },
  chainWebpack: config= > {
    config.optimization.minimize(true);
    config.optimization.splitChunks({chunks: 'all'})
    config.externals({
        vue: 'Vue'.vuex: 'Vuex'.'vue-router': "VueRouter".'element-ui': "'element-ui'"}}})Copy the code

Then we run the project. The CSS configuration can be seen in the official documentation.

Notice that our code continues to decrease. The programming is already 2.3m, the other units are K. CSS file we also found. Here we also need to extract a CSS file, which is the Element-UI style file. We are now using a native element UI style, which we have changed to a free resource

We need to comment it out here. Then add the free resources to the HTML file

Then run the project. Find a CSS file starting with Vendor, which is reduced from 205K to 8.3K

Notice that we also have 2.3 megabytes of files here. I’m here we have to continue to optimize. Here is the reason why the file is large. We also introduced the vue-codemirror component, which we can also solve using free resources. Vue, vuex, vuE-router configuration, we are not redundant description. This component uses the codemirror style. We need to bring it in. The final effect.

It’s already compressed to 1.4 meters. After the above steps, the effect is more obvious. Because we are using the development environment model here, there is some extra code, but it is also necessary in this environment. Such as hot loading, webpack-dev-server plug-ins.

  1. Gzip compression.

Gzip compression, here we need to introduce a plug-in: compression-webpack-plugin. To complete the compression of JS files. To install the plug-in:

npm install --save-dev compression-webpack-plugin
Copy the code

Then introduce the relevant code:


const CompressionWebpackPlugin = require('compression-webpack-plugin')

const compress = new CompressionWebpackPlugin(
  {
    filename: info= > {
      return `${info.path}.gz${info.query}`
    },
    algorithm: 'gzip'.threshold: 10240.test: new RegExp(
      '\ \. (' +
      ['js'].join('|') +
      '$'
    ),
    minRatio: 0.8.deleteOriginalAssets: false})module.exports = {
  css: {
      extract: true
  },
  configureWebpack: {
      plugins: [compress]
  },
  chainWebpack: config= > {
    config.optimization.minimize(true);
    config.optimization.splitChunks({chunks: 'all'})
    config.externals({
        vue: 'Vue'.vuex: 'Vuex'.'vue-router': "VueRouter".'element-ui': "'element-ui'"}}})Copy the code

Here we just do the gzip of the js file. Then we will generate a.gz file. Let’s restart the project. But you can’t see the effect. Because the gz file is not visible to the browser. At this point, we need to configure the server. Current application servers, such as Nginx, Apache, etc., all support Gzip compression. If installed on such a server, there is no need for compression through this plug-in. We can just enable their own gzip functionality. The purpose of doing this is to better understand the compression effect of gZIP files. Here we also need to add devServer configuration:

const compress = new CompressionWebpackPlugin(
  {
    filename: info= > {
      return `${info.path}.gz${info.query}`
    },
    algorithm: 'gzip'.threshold: 10240.test: new RegExp(
      '\ \. (' +
      ['js'].join('|') +
      '$'
    ),
    minRatio: 0.8.deleteOriginalAssets: false})module.exports = {
  devServer: {

    before(app, server) { 
      app.get(/.*.(js)$/, (req, res, next) => { 
        req.url = req.url + '.gz';
        res.set('Content-Encoding'.'gzip'); next(); })}// compress: true
  },
  css: {
    extract: true
  },
  configureWebpack: {
    plugins: [
      compress
    ]
  },
  chainWebpack: config= > {
    config.optimization.minimize(true);
    config.optimization.splitChunks({chunks: 'all'})
    config.externals({
        vue: 'Vue'.vuex: 'Vuex'.'vue-router': "VueRouter".'element-ui': "'element-ui'"."vue-codemirror": "'vue-codemirror'"}}})Copy the code

Then restart the project and you will find that our Js files have been compressed from 1.4m files to over 300K. The effect is obvious.

We have basically completed the overall optimization. More detailed optimization, we need to explore. Note: devServer can be set to **compress: true ** in gzip compression. You do not need to add the compression or modify the request mode.

Optimization of thinking

In terms of vuE-CLI3 project framework, it is basically repackaged based on Webpack, so the most important thing for us is to understand the relevant optimization configuration of Webpack to complete our optimization of the project. Now there are more and more plug-ins, but the most essential way of optimization, or the same. With the previous project optimization method is similar. More detailed operation, you can continue to study. I hope it was helpful. I welcome you to point out any problems.

Attachment: the vue – cli3 project framework to optimize video share the download address: https://pan.baidu.com/s/1q2ELgOrikuiwqjg2IfXk-g key: qx1q

Article reprint please contact us (One Line Team)