vue3+vite3 project packaging optimization

1 Introduction

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

2. View analysis tool rollup-plugin-visualizer

Using the plug-in in the project rollup-plugin-visualizercan generate a visual code analysis report to see which modules take up space, helping us better understand the file size, dependencies and other information during the build process.

  1. First installed rollup-plugin-visualizerthe plugin. Can be installed using npmor :yarn
yarn add rollup-plugin-visualizer -D
npm i rollup-plugin-visualizer -D
  1. Introduce the plugin and add it to the plugin list vite.config.js.rollup-plugin-visualizer
import {
    
     visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({
    
    
  plugins: [
  vue(), 
  visualizer({
    
    
    open: true, //在默认用户代理中打开生成的文件
    gzipSize: true, // 收集 gzip 大小并将其显示
    brotliSize: true, // 收集 brotli 大小并将其显示
    filename: "stats.html", // 分析图生成的文件名
  }),
})

Many of the configured parameters are default. If you have no special needs, you don’t need to add parameters. Below I will add a table to explain the existing parameters:

parameter type explain
filename/file string Generate file name for analysis
title string html tab title
open boolean Open file with default server proxy
template string Selectable chart types
gzipSize boolean Collect the size of gzip compressed files into a graph
BrotliSize boolearn Collect brotli compressed package size into chart
emitFile boolean Use emitFile to generate files. Simply put, if this attribute is true, the packaged analysis file will appear under the packaged file package, otherwise it will be in the project directory.
sourcemap boolean Calculate size using sourcemap
projectRoot string, RegExp The root directory of the file, which is in the packaged directory by default
  1. Run the command package to generate analysis graphs. After executing npm run buildthe command, wait for a moment to generate the analysis view. The view will automatically pop up and be saved in the project root directory. The file name is the filenamename of the parameter just now ( stats.html)
npm run build
  1. In the directory where the generated package file is located, a stats.htmlfile named will be generated, which is the generated visual report.
    Open stats.htmlthe file and you will see an interactive visual chart showing the size, dependencies and other information of each module in the packaged file. You can use this chart to identify which modules take up more space so you can optimize your code.
    Insert image description hereThe larger the square in the view analysis, the larger the space occupied by the file and the higher the requirements for network bandwidth and access speed. If a website contains a large number of large files, users will need to download more data when visiting the website, which will cause the website to load slower and the user experience to be worse.

3. Lazy loading of routes

Routing lazy loading is usually implemented by using dynamic import ( Dynamic Import) syntax, such as Vueusing in the project import()to import components that need to be lazy loaded. When the user accesses the corresponding route, the component will be loaded asynchronously, achieving the effect of on-demand loading.

export const constantRoute = [
	{
    
    
	    path: '/login',
	    component: () => import('@/views/login/index.vue'),
	    name: 'Login',
	    meta: {
    
    
	        title: '登录', //菜单标题
	        hidden: true, //代表路由标题在菜单中是否隐藏  true:隐藏 false:不隐藏
	        icon: 'Promotion',
	    },
	},
	{
    
    
	    path: '/',
	    component: () => import('@/layout/index.vue'),
	    name: '/',
	    meta: {
    
    
	        title: '',
	        hidden: false,
	
	    },
	    redirect: '/home',
	    children: [{
    
    
	        path: '/home',
	        component: () => import('@/views/home/index.vue'),
	        meta: {
    
    
	            title: '项目总览',
	            hidden: false,
	            icon: 'HomeFilled',
	        },
	    },],
	},
	{
    
    
	    path: '/user',
	    component: () => import('@/views/user/index.vue'),
	    name: 'User',
	    meta: {
    
    
	        title: '个人中心',
	        hidden: true,
	    },
	},
	{
    
    
	    path: '/404',
	    component: () => import('@/views/404/index.vue'),
	    name: '404',
	    meta: {
    
    
	        title: '找不到数据',
	        hidden: true,
	    },
	},
]

4. Introduction of third-party library CDN

Third-party libraries can be introduced into the project as needed CDN. Using CDNthird-party libraries can improve the performance and development efficiency of the project, reduce the size of the project, and also reduce the burden on the server and improve user experience.

  1. Install plugin
npm install vite-plugin-cdn-import -D
yarn add vite-plugin-cdn-import -D
  1. vite.config.jsConfigure in
import {
    
     defineConfig } from 'vite';
import compression from 'vite-plugin-compression';
export default defineConfig({
    
    
  // 其他配置项...
  plugins: [
    // 其他插件...
    // 第三方库CDN引入
    importToCDN({
    
    
      prodUrl: "https://unpkg.com/{name}@{path}",
      modules: [
        autoComplete('vue'),
        autoComplete('axios'),
        {
    
    
          name: "vue-router",
          var: "VueRouter",
          path: "4.1.3",
        },
        {
    
    
          name: "element-plus",
          var: "ElementPlus",
          path: "2.2.14",
          css: "2.2.14/dist/index.css",
        },
        {
    
    
          name: "@element-plus/icons-vue",
          var: "ElementPlusIconsVue", // 根据main.js中定义的来
          path: "2.0.9",
        },
        {
    
    
          name: "pinia",
          var: "Pinia",
          path: "2.0.34",
        },
        {
    
    
          name: "lodash",
          var: "Lodash",
          path: "4.17.21",
        },
      ],
    }),
  ],
});

5. Use gzip compression

gzipCompression is a commonly used data compression algorithm that reduces the size of files, thereby reducing their transfer time and space usage. gzipThe compression algorithm is based on DEFLATEalgorithms that use Huffman coding and LZ77algorithms to achieve efficient data compression.
When using gzipcompressed files, the files are converted into a compressed and encoded format. This format can reduce file size by reducing redundant data and using a more compact encoding. Compressed files usually .gzhave an extension.

  1. Install plugin
yarn add vite-plugin-compression -D
npm i vite-plugin-compression -D
  1. vite.config.jsConfigure in
import {
    
     defineConfig } from 'vite';
import compression from 'vite-plugin-compression';
export default defineConfig({
    
    
  // 其他配置项...
  plugins: [
    // 其他插件...
    compression({
    
    
      algorithm: "gzip", // 指定压缩算法为gzip,[ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
      ext: ".gz", // 指定压缩后的文件扩展名为.gz
      threshold: 10240, // 仅对文件大小大于threshold的文件进行压缩,默认为10KB
      deleteOriginFile: false, // 是否删除原始文件,默认为false
      filter: /\.(js|css|json|html|ico|svg)(\?.*)?$/i, // 匹配要压缩的文件的正则表达式,默认为匹配.js、.css、.json、.html、.ico和.svg文件
      compressionOptions: {
    
     level: 9 }, // 指定gzip压缩级别,默认为9(最高级别)
      verbose: true, //是否在控制台输出压缩结果
      disable: false, //是否禁用插件
    }),
  ],
});

Insert image description here

6. Introduce third-party libraries as needed

For some larger third-party libraries, such as Element UIor Ant Design, you can consider introducing components or styles on demand instead of introducing them all. To introduce components or styles on demand, you can refer to the official documents of these third-party libraries, which describe how to introduce components or styles on demand.

7. Use Tree Shaking

treeshakingAlso known as "tree shaking optimization". To put it simply, it is to remove useless code while ensuring that the running results of the code remain unchanged. Vue3, many ApIimports support treeshakingoptimization. That is to say, only package what you use APIand ignore those that are not used.

Vue3RollupIt will be used by default treeshakingand no additional configuration is required. But there is a condition, it must be ES6 modulea module.

8. Eliminate console and debugger

  1. vite 4.XThe version is no longer integrated terserand needs to be downloaded by yourself.
yarn add terser -D
npm i terser -D
  1. vite.config.jsConfigure in
import {
    
     defineConfig } from "vite";  
export default defineConfig({
    
      
    build: {
    
      
        minify: 'terser', // 启用 terser 压缩  
        terserOptions: {
    
      
            compress: {
    
      
                pure_funcs: ['console.log'], // 只删除 console.log 
                //drop_console: true, // 删除所有 console
                drop_debugger: true, // 删除 debugger  
            }  
        }  
    }  
})  

9. Subcontracting strategy

By default, when the browser repeatedly requests a static resource with the same name, it will directly use the cached resource. Using this mechanism, we can package code that is not frequently updated into a separate JSfile, which can reduce HTTPrequests and reduce server pressure.

manualChunks custom segmentation

// vite.config.js
import {
    
     defineConfig } from 'vite'

export default defineConfig({
    
    
  build: {
    
    
    rollupOptions: {
    
    
      output: {
    
    
        manualChunks: id => {
    
    
          // 将 node_modules 中的代码单独打包成一个 JS 文件
          if(id.includes('node_modules')) {
    
    
            return 'vendor'
          }
        }
      }
    }
  }
})

Insert image description here

You can see that the dependent module has generated a separate JSfile. In this way, even if we modify main.jsthe code in and repackage, the dependent file vendor.b3aecacd.jswill not change, and the browser will not initiate a request for this file again. If there are many dependent modules, the performance will be greatly improved.

10. Image compression

According to the project's requirements for clarity, we can use vite-plugin-imageminplug-ins to appropriately compress the images:

  1. Install npm i vite-plugin-imagemin -Dplugin
  2. vite.config.jsConfigure in
// vite.config.js
import {
    
     defineConfig } from 'vite'
import viteImagemin from 'vite-plugin-imagemin'

export default defineConfig({
    
    
  plugins: [
    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
          }
        ]
      }
    })
  ]
})

Note: viteImageminIt is difficult to install in China and errors are prone to occur. You can try the following solutions.
viteImageminReport an error

  1. Use configure yarnwithin package.json(recommended)
"resolutions": {
    
    
	"bin-wrapper": "npm:bin-wrapper-china"
}
  1. To use it npm, hostjust add the following configuration to the computer file
199.232.4.133 raw.githubusercontent.com
  1. Install using cnpm(not recommended)

Guess you like

Origin blog.csdn.net/DZQ1223/article/details/133064563