SoFunction
Updated on 2025-04-05

Detailed explanation of four methods of packaging optimization in Vue project

Preface

By default, third-party dependency packages imported through the import syntax will eventually be packaged into a js file, which will cause the single file to be too large and will block web page loading when the network speed is low, affecting the user experience.

Purpose of packaging optimization:

1. Project startup speed and performance

2. Necessary cleaning of data

3. Reduce the volume after packaging

The first point is the core, and the second point is actually to clean the console

Main directions of performance optimization:

Lazy route loading

Remove the printout of the production version

Dependencies for development version, production version uses online CDN

Project packaging and configuration

1. Asynchronous component configuration (lazy loading of routes)

Once all components are loaded, the first screen is loading slowly. You can configure routes to load on demand.

When building a project, the js package will become very large, affecting page loading. We divide the corresponding components of different routes into different code blocks, and then load the corresponding components when the route is accessed, which can improve access efficiency.

After splitting, the browser does not access a certain route to download the corresponding module. It still downloads all modules when accessing the program for the first time, but each module is divided very small. The modules required when loading the homepage can be downloaded faster, so they can be displayed faster.

There are three steps:

  • Installation package npm install --save-dev @babel/plugin-syntax-dynamic-impor
  • Add plugins to the configuration file
  • Change the route to load on demand
import Vue from 'vue'
import VueRouter from 'vue-router'
 
(VueRouter)
 
const routes = [
  {
    path: '/Login',
    name: 'Login',
    // Lazy loading of routes    component: () => import('../views/Login/')
  },
  {
    path: '/',
    component: () => import('../views/layout/'),
    children: [
      {
        path: '',
        component: () => import('../views/Home/')
      }
    ]
  }
]
 
//or as follows 
const Login = () => import('@/views/Login')
const Reg = () => import('@/views/Reg')
const Layout = () => import('@/views/Layout')

2. Remove the packaged console

The console statement after packaging and online has no effect, so we should remove it, remove manual removal, and also use plug-in to remove console statements in the code.

Installation dependencies: yarn add terser-webpack-plugin -D (npm i terser-webpack-plugin -D)

Modifying the configuration file

// Get the current packaging environment (the specific article will be explained at the end)const env = .NODE_ENV
// Override the default webpack configuration = {
  publicPath: './',  //The white screen is loaded for the first time (the file path problem after packaging)  devServer: {
    port: 3000,
    open: true
  },
  chainWebpack: (config) => {
    ('terser').tap((args) => {
      args[0]..drop_console = true
      return args
    })
  } 
}

3. Use CDN

Use CDN to reduce the volume of the packet. References are made to the CDN network nodes using some dependencies used in the online environment, rather than directly packing them into the package.

The project development stage is different from the production stage. In the development stage, we still need to use the import import dependency method to develop, and then configure CDN external links to obtain project dependencies in the production stage.

By default, the development mode and release mode of Vue project use a packaged entry file (src/). In order to separate the project's development process from the release process, we can use two entry files separately, one for the development environment packaging (this is), and the other for the production environment packaging.

In

// Is it a production environmentconst isProduction = .NODE_ENV !== 'development';
 
// Do you need to use cdn in the local environmentconst devNeedCdn = false
 
// cdn linkconst cdn = {
    // cdn: module name and module scope naming (corresponding to the name of the variable mounted in window)    externals: {
        vue: 'Vue',
        vuex: 'Vuex',
        'vue-router': 'VueRouter',
        'marked': 'marked',
        '': 'hljs',
        'nprogress': 'NProgress',
        'axios': 'axios'
    },
    // cdn's css link    css: [
        
    ],
    // cdn's js link    js: [
        '/vue/2.6.10/',
        '/vuex/3.1.2/',
        '/vue-router/3.1.3/',
        '/axios/0.19.2/'
    ]
}
 
 = {
    chainWebpack: config => {
        // ================= Inject cdn start==============        ('html').tap(args => {
            // Inject cdn only when cdn is needed in production environment or locally            if (isProduction || devNeedCdn) args[0].cdn = cdn
            return args
        })
        // ================= Inject cdn start==============    },
    configureWebpack: config => {
        // Introduced in cdn, the relevant resources should be ignored during construction        if (isProduction || devNeedCdn)  = 
    }
}
 <!-- useCDNofCSSdocument -->
 <% for (var i in  &&
  ) { %>
  <link
          href="<%= [i] %>" rel="external nofollow" 
          rel="stylesheet"
  />
  <% } %>
  <!-- useCDNofCSSdocument -->
 
 
  <!-- useCDNofJSdocument -->
 <% for (var i in  &&
  ) { %>
  <script src="<%= [i] %>"></script>
  <% } %>
  <!-- useCDNofJSdocument -->

build to generate dist directory

Get a dist directory, which contains all the pages, styles, businesses, and third-party packages in the project. The resource file is introduced in the default html file. It is introduced in the project root directory. Double-clicking can be used to open it. You can use the live-sever in vscode.

During the packaging process, the code will be compressed and merged, version downgraded, syntax conversion, etc....

 = {
  publicPath: './',  //Solve path problems  devServer: {
    port: 3000,   //Change the port number    open: true    //After running, the browser will be opened automatically and run  }
}

Summarize

This is the end of this article about the four methods of packaging optimization in Vue projects. For more related Vue projects, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!