Vite3+vue3 project packaging optimization 3 – CDN acceleration, file compression

1. CDN online acceleration

Content Delivery Network (CDN for short) is a distributed content distribution network built on a data network, which allows users to request resources from the nearest server to improve the response speed of network requests.

Usually, we request dependent modules to use CDN, while requesting project code still uses its own server.

During the development of Vite + Vue3 projects, tool libraries such as element-plus and lodash-es will have a lot of file dependencies. We can try to reduce the request pressure of “single system” by configuring CDN. (Generally, our project has only one server, which is called a single system)

Digital management platform
Vue3 + Vite + VueRouter + Pinia + Axios + ElementPlus
Vue permission system case
personal blog address

Install the CDN management plugin

# npm way
npm i vite-plugin-cdn-import -D

# yarn way
yarn add vite-plugin-cdn-import -D

Taking lodash-es as an example, in the vite.config.ts file, configure the CDN corresponding to the module

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// Use the CDN plugin
import vitePluginCDN from 'vite-plugin-cdn-import'

export default defineConfig({
  // array of plugins needed by plugins
  plugins: [
    vue(),
    vitePluginCDN({
      // Configure modules that require CDN acceleration
      modules: [
        { name: 'lodash-es', var: '_', path: 'https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js'}
      ]
    })
  ]
})

After successfully building with the npm run build command, Vite will automatically insert the CDN resource into the html through the script tag (as shown in the figure below). In this way, requesting lodash resources will generate an acceleration buff, and the package size of the project will be greatly reduced.

**[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended Save the picture and upload it directly (img-RsWoJx4D-1684914383410)(./project plugin.assets/image-20230524135023768.png)]**

Problems with using CDN: Once there is a problem with the dependent website, our project will fail. It is recommended to leave a backup solution for maintenance. If the company has the conditions, you can use the company’s own CDN to ensure security

2. gzip compression

gzip is a compression format, which can greatly reduce the code size and improve network performance. It is often configured and enabled in project packaging and Web services.

The opening method of gzip in the current project is relatively simple, just configure vite-plugin-compression:

Install plugin:

# npm way
npm i vite-plugin-compression -D

# yarn way
yarn add vite-plugin-compression -D

The vite.config.ts file is configured as follows

import { defineConfig } from 'vite'
import viteCompression from 'vite-plugin-compression'

export default defineConfig({
  plugins: [viteCompression()]
})

Configuration parameters

  • filter: filter, which types of files are compressed, the default is /.(js|mjs|json|css|html)$/i
  • verbose: true: Whether to output the compression result on the console, the default is true
  • threshold : enable compression file size limit, the unit is byte, the default is 0
  • disable : false: Whether to disable compression, the default is false
  • deleteOriginFile : Whether to delete the original file after compression, the default is false
  • algorithm : the compression algorithm used, the default is gzip
  • ext : the suffix of the generated compressed package

Parameter configuration method

viteCompression({
    verbose: true, // Whether to output the compression result on the console
    disable: false, // Whether to disable, equivalent to the switch here
    threshold: 10240, // Only when the volume is greater than the threshold will it be compressed, the unit is b, 1b=8B, 1B=1024KB, then our place is equivalent to more than 9kb, and it will be compressed
    algorithm: 'gzip', // compression algorithm, optional [ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
    ext: '.gz', //file suffix
})

Execute the packaging command, the console information is as follows:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture Save it and upload directly (img-BFByo1cj-1684914383411)(./project plugin.assets/image-20230524143017627-1684909818955-1.png)]

It is not difficult to find that after gzip compression, the file size is greatly reduced.

Put the packaged project into the server directory, and the server starts the gzip service, so that it can be accessed in the browser through the project address. Nginx is configured as follows:

server{
    #gzip
    #Enable the gzip function
    gzip on;
    #Enable gzip static compression function
    gzip_static on;
    #gzip cache size
    gzip_buffers 4 16k;
    #gzip http version
    gzip_http_version 1.1;
    #gzip compression level 1-10
    gzip_comp_level 5;
    #gzip Compression Type
    gzip_types text/plain application/javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary on;
}

When a compressed static resource is requested in the browser, the server will set the response header content-encoding:gzip according to the type supported by the browser, telling the browser how to decompress it.

It should be noted that browser decompression also takes time. If the project size is not very large, it is not recommended to use gzip for compression.

Use a browser to access the project in the server, open the console -> network, as follows:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture Save it and upload directly (img-omc5jm3R-1684914383412)(./project plugin.assets/image-20230524144525345.png)]

Note: If not, please right-click the column -> Response Header Configuration (Header Options -> Response Headers -> Content-Encoding) to configure

3. Image compression

According to the project’s requirements for clarity, we can use the vite-plugin-imagemin plug-in to properly compress the image

Install

# npm way
npm i vite-plugin-imagemin -D

# yarn way
yarn add vite-plugin-imagemin -D

Configure various image compression parameters in vite.congi.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteImagemin from 'vite-plugin-imagemin'

export default defineConfig({
  plugins: [
  vue(),
    viteImagemin({
      gifsicle: {
        optimizationLevel: 7,
        interlaced: false
      },
      optipng: {
        optimizationLevel: 7
      },
      mozjpeg: {
        quality: 20
      },
      pngquant: {
        quality: [0.8, 0.9],
        speed: 4
      },
      svgo: {
        plugins: [
          {
            name: 'removeViewBox'
          },
          {
            name: 'removeEmptyAttrs',
            active: false
          }
        ]
      }
    })
  ]
})