Essential bonus items for optimizing and packaging the front end of Vue projects

Essential bonus items for optimizing and packaging the front end of Vue projects

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
  },

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")

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:)

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')
    }
  }
}

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 increase access speed
  • Placing some static resources: css, .js, pictures, and videos on a third-party CDN server can speed up access.

benefit:

  1. Reduce the size of the application package
  2. Speed ​​up access to static resources
  3. 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
    ]
  }
}

webpack configuration externals configuration items

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

Injected into index.html via 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...
}

Find public/index.html and inject css and js in sequence by configuring CDN Config.

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>

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 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 concludes this article about the essential bonus items for the front-end of Vue project optimization and packaging. For more relevant Vue project optimization and packaging content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to the blank page after vue.js packaged project
  • Detailed explanation of Vue project optimization and packaging
  • Steps to package and release the Vue project
  • Record of the actual process of packaging and deployment of Vue project
  • Detailed explanation of Vue project packaging

<<:  Solution to the problem of not being able to access the home page when adding a tomcat container to Docker

>>:  Detailed explanation of the underlying implementation of descending index, a new feature of MySQL 8

Recommend

uni-app implements NFC reading function

This article shares the specific code of uni-app ...

Docker image access to local elasticsearch port operation

Using the image service deployed by docker stack,...

docker cp copy files and enter the container

Enter the running container # Enter the container...

SQL interview question: Find the sum of time differences (ignore duplicates)

When I was interviewing for a BI position at a ce...

Difference between MySQL btree index and hash index

In MySQL, most indexes (such as PRIMARY KEY, UNIQ...

A detailed introduction to deploying RabbitMQ environment with docker

Prerequisites: Docker is already installed 1. Fin...

How does Vue solve the cross-domain problem of axios request front end

Table of contents Preface 1. Why do cross-domain ...

MySQL query learning basic query operations

Preface MySQL is the most popular relational data...

Analysis of the principle and usage of MySQL continuous aggregation

This article uses examples to illustrate the prin...

MySQL database operations (create, select, delete)

MySQL Create Database After logging into the MySQ...

Example of implementing the skeleton screen of WeChat applet

Table of contents What is a skeleton screen How t...

Three notification bar scrolling effects implemented with pure CSS

Preface The notification bar component is a relat...

Detailed explanation of MySQL data grouping

Create Group Grouping is established in the GROUP...