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

Example code for converting html table data to Json format

The javascript function for converting <table&g...

Common Linux English Error Chinese Translation (Newbies Must Know)

1.command not found command not found 2. No such ...

How to install and use Ubuntu Docker

Table of contents 1. Automatic installation using...

Vue encapsulation component tool $attrs, $listeners usage

Table of contents Preface $attrs example: $listen...

CSS to achieve compatible text alignment in different browsers

In the front-end layout of the form, we often nee...

Vue implements internationalization of web page language switching

1. Basic steps 1: Install yarn add vue-i18n Creat...

How to run tomcat source code in maven mode

Preface Recently, I was analyzing the startup pro...

CentOs7 64-bit MySQL 5.6.40 source code installation process

1. Install the dependency packages first to avoid...

Design Association: Why did you look in the wrong place?

I took the bus to work a few days ago. Based on m...

Test and solution for MySQL's large memory usage and high CPU usage

After the changes: innodb_buffer_pool_size=576M -...

Docker deploys nginx and mounts folders and file operations

During this period of time, I was studying docker...

SQL Optimization Tutorial: IN and RANGE Queries

Preface "High Performance MySQL" mentio...

Web Design TabIndex Element

TabIndex is to press the Tab key to sequentially o...