vue3+vite3 project packaging optimization
- 1 Introduction
- 2. View analysis tool rollup-plugin-visualizer
- 3. Lazy loading of routes
- 4. Introduction of third-party library CDN
- 5. Use gzip compression
- 6. Introduce third-party libraries as needed
- 7. Use Tree Shaking
- 8. Eliminate console and debugger
- 9. Subcontracting strategy
- 10. Image compression
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-visualizer
can 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.
- First installed
rollup-plugin-visualizer
the plugin. Can be installed usingnpm
or :yarn
yarn add rollup-plugin-visualizer -D
npm i rollup-plugin-visualizer -D
- 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 |
- Run the command package to generate analysis graphs. After executing
npm run build
the 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 thefilename
name of the parameter just now (stats.htm
l)
npm run build
- In the directory where the generated package file is located, a
stats.html
file named will be generated, which is the generated visual report.
Openstats.html
the 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.
The 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 asVue
using in the projectimport()
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
. UsingCDN
third-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.
- Install plugin
npm install vite-plugin-cdn-import -D
yarn add vite-plugin-cdn-import -D
vite.config.js
Configure 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
gzip
Compression is a commonly used data compression algorithm that reduces the size of files, thereby reducing their transfer time and space usage.gzip
The compression algorithm is based onDEFLATE
algorithms that use Huffman coding andLZ77
algorithms to achieve efficient data compression.
When usinggzip
compressed 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.gz
have an extension.
- Install plugin
yarn add vite-plugin-compression -D
npm i vite-plugin-compression -D
vite.config.js
Configure 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, //是否禁用插件
}),
],
});
6. Introduce third-party libraries as needed
For some larger third-party libraries, such as
Element UI
orAnt 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
treeshaking
Also 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
, manyApI
imports supporttreeshaking
optimization. That is to say, only package what you useAPI
and ignore those that are not used.
Vue3
Rollup
It will be used by default treeshaking
and no additional configuration is required. But there is a condition, it must be ES6 module
a module.
8. Eliminate console and debugger
vite 4.X
The version is no longer integratedterser
and needs to be downloaded by yourself.
yarn add terser -D
npm i terser -D
vite.config.js
Configure 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
JS
file, which can reduceHTTP
requests 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'
}
}
}
}
}
})
You can see that the dependent module has generated a separate JS
file. In this way, even if we modify main.js
the code in and repackage, the dependent file vendor.b3aecacd.js
will 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-imagemin
plug-ins to appropriately compress the images:
- Install
npm i vite-plugin-imagemin -D
plugin vite.config.js
Configure 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: viteImagemin
It is difficult to install in China and errors are prone to occur. You can try the following solutions.
viteImagemin
Report an error
- Use configure
yarn
withinpackage.json
(recommended)
"resolutions": {
"bin-wrapper": "npm:bin-wrapper-china"
}
- To use it
npm
,host
just add the following configuration to the computer file
199.232.4.133 raw.githubusercontent.com
- Install using
cnpm
(not recommended)