Detailed explanation of Vue project optimization and packaging

Detailed explanation of Vue project optimization and packaging

Preface

After the Vue project is developed, before packaging and releasing the project, an essential operation is project optimization, which is also a plus for programmers. Follow the steps of this article to see how to optimize the project~

1. Routing lazy loading

1. Why do we need lazy loading of routes?

When I just ran the project, I found that all the js files and css files were loaded as soon as I entered the page. This process was very time-consuming. If you load the corresponding js and css files of the corresponding page when you open the page, the page loading speed will be greatly improved.

2. How to implement lazy loading of routes

Vue official documentation: Routing lazy loading

The code is as follows (example):

{
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
Copy code

3. Magic comments in lazy loading of routes

You can customize the name of this file by specifying webpackChunkName in the comment. The code is as follows (example):

components = () => import(/* webpackChunkName:"login"*/ "../component/Login.vue")
Copy code

2. Analyze the package size

1. Demand

I want to know the size of each file in the packaged file. So that we can analyze and optimize the code.

2. How to generate package analysis files

Run npm run preview – --report in the terminal. This command will perform dependency analysis from our entry point main.js and analyze the size of each package. Finally, a report.html file will be generated in the generated dist folder. After opening it, you can see the space occupied by the files used in our project.

(The effect diagram is as follows:)

insert image description here

3. Webpack configuration excludes packaging

1. Demand

Exclude some infrequently used packages from the generated package files. For example, xsxl.js and element.js shown in the figure above can be excluded from the generated files.

2. Exclude packaging

Find vue.config.js and add the externals item as follows:

The code is as follows (example):

configureWebpack: {
  //Configure the title of the single page application page name: name,
  externals: {
     /**
      * externals object attribute parsing.
      * Basic format:
      * 'Package name': 'The name introduced in the project'
      *  
    */
    'vue': 'Vue',
    'element-ui': 'ElementUI',
    'xlsx': 'XLSX'
  },
  resolve: {
    alias: {
      '@': resolve('src')
    }
  }
}
Copy code

IV. Citing online resources

1. Demand

After we performed the previous step, the package generated was much smaller. However, without these dependent packages, the project cannot be run online. Then we need to reference resources in the network to support the operation of our code.

2. CDN

The full name of CDN is “Content Delivery Network”, which is called content distribution network in Chinese. We use it to improve access speed and put some static resources: css, .js, pictures, videos on a third-party CDN server to speed up access speed.

benefit:

  • Reduce the size of the application package
  • Speed ​​up access to static resources
  • Use browser cache to cache unchanged files for a long time

3. Implementation steps

Note : In the development environment, file resources can still be taken from the local node_modules, and only when the project is online do you need to use external resources. At this point we can use environment variables to distinguish. The details are as follows:

The code is as follows (example):

In the vue.config.js file:

let externals = {}
let cdn = { css: [], js: [] }
const isProduction = process.env.NODE_ENV === 'production' // Determine whether it is a production environment if (isProduction) {
  externals = {
      /**
      * externals object attribute analysis:
      * 'Package name': 'The name introduced in the project'
    */
      'vue': 'Vue',
      'element-ui': 'ELEMENT',
      'xlsx': 'XLSX'
  }
  cdn = {
    css: [
      'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // element-ui css style sheet],
    js: [
      // vue must be at first!
      'https://unpkg.com/[email protected]/dist/vue.js', // vuejs
      'https://unpkg.com/element-ui/lib/index.js', // element-ui js
      'https://cdn.jsdelivr.net/npm/[email protected]/dist/xlsx.full.min.js', // xlsx
    ]
  }
}
Copy code

webpack configuration externals configuration items

configureWebpack: {
  //Configure the title of the single page application page name: name,
  externals: externals,
  resolve: {
    alias: {
      '@': resolve('src')
    }
  }
}
Copy code

Injected into index.html之through html-webpack-plugin : Configure in vue.config.js file:

chainWebpack(config) {
  config.plugin('preload').tap(() => [
    {
      rel: 'preload',
      fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
      include: 'initial'
    }
  ])
  //Inject cdn variable (will be executed when packaging)
  config.plugin('html').tap(args => {
    args[0].cdn = cdn // Configure cdn to the plugin return args
  })
  // Omit the rest...
}
Copy code

Find public/index.html and configure CDN Config to inject css and js in sequence. Modify the content of head as follows:

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= webpackConfig.name %></title>
      <!-- Import style -->
      <% for(var css of htmlWebpackPlugin.options.cdn.css) { %>
        <link rel="stylesheet" href="<%=css%>">
        <% } %>

    <!-- Import JS -->
    <% for(var js of htmlWebpackPlugin.options.cdn.js) { %>
      <script src="<%=js%>"></script>
    <% } %>
  </head>
Copy code

5. Pack and remove console.log

1. Demand

After the project is packaged and launched, remove all console.log in the code

2. Code Demonstration

Configure in the vue.config.js file: The code is as follows (example):

chainWebpack(config) {
    config.optimization.minimizer('terser').tap((args) => {
      args[0].terserOptions.compress.drop_console = true
      return args
    })
}

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • A brief discussion on vue project packaging optimization strategy
  • Vue project packaging and compilation optimization solution
  • Vue project packaging optimization method (making the packaged js file smaller)

<<:  The difference between Input's size and maxlength attributes

>>:  Quickly obtain database connection information and some extensions through zabbix

Recommend

Detailed steps to deploy lnmp under Docker

Table of contents Pull a centos image Generate ng...

Detailed installation tutorial of zabbix 4.04 (based on CentOS 7.6)

1. Preparation before installation: 1.1 Install J...

JS cross-domain solution react configuration reverse proxy

Cross-domain solutions jsonp (simulate get) CORS ...

Summary of Linux system user management commands

User and Group Management 1. Basic concepts of us...

JavaScript implements the nine-grid mobile puzzle game

This article shares the specific code for JavaScr...

An enhanced screenshot and sharing tool for Linux: ScreenCloud

ScreenCloud is a great little app you didn’t even...

JavaScript MouseEvent Case Study

MouseEvent When the mouse performs a certain oper...

vue $set implements assignment of values ​​to array collection objects

Vue $set array collection object assignment In th...

Docker Compose one-click ELK deployment method implementation

Install Filebeat has completely replaced Logstash...

Vue.js application performance optimization analysis + solution

Table of contents 1. Introduction 2. Why do we ne...

Founder font library Chinese and English file name comparison table

Founder Type Library is a font library developed ...

MySQL password is correct but cannot log in locally -1045

MySQL password is correct but cannot log in local...

How to implement remote connection for Redis under Linux

After installing Redis on Linux, use Java to conn...