vue3笔记(18-2)vite 首次打开界面加载慢问题

项目改用 vite 之后,启动确实特别快,但是首次打开界面加载慢的我想去刷一会儿微博(开玩笑)…
本篇记录我在熟悉项目之后对项目构建做的一些优化尝试。

基础知识

  1. vite 开发环境下,模块以原生 ESModule 的形式(es6原生的模块加载机制)被浏览器加载;
  2. vite 没有对代码进行打包压缩处理,所以服务启动很快;下载的文件是没有被处理过的源码,所以要比 webpack 处理过的文件大很多;
  3. 项目启动后浏览器第一次加载才会慢;慢的主要原因是 vite 需要动态的解析依赖,并打包,引入;

浏览器调试工具 waterfall

waterfall 性能检测详解详解:
Queueing:排队
Stalled:阻塞。请求访问该URL的主机是有并发和连接数限制,必须要等之前的执行完成才能执行之后的,stalled 代表这段时间的耗时
DNS Lookup:域名解析所耗时间
Initial connection:初始化连接时间。这里一般是 TCP 3次连接握手时间
SSL:https 特有,是一种协议
Request sent:发送请求所消耗的时间
Waiting:等待响应时间(这里一般是最耗时的)
Content Download:下载内容所需要消耗的时间

vite 首次加载慢的原因

在查看 waterfall 之后,发现首次加载中 Waiting 阶段时间耗费较长,等待响应时间就是 vite 在编译的时间。

解决方案一(未成功)

这个方案是网上查阅资料后基本统一的解决方法,但是尝试后发现在 vite4 中并不适用,特别是推荐的安装的两个包,安装也没有成功,所以方案一仅仅是做一个记录。
vite.config.ts中添加配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
{
optimizeDeps: {
include: [
'vue',
'map-factory',
'element-plus/es',
'element-plus/es/components/form/style/index',
'element-plus/es/components/radio-group/style/index',
'element-plus/es/components/radio/style/index',
'element-plus/es/components/checkbox/style/index',
'element-plus/es/components/checkbox-group/style/index',
'element-plus/es/components/switch/style/index',
'element-plus/es/components/time-picker/style/index',
'element-plus/es/components/date-picker/style/index',
'element-plus/es/components/col/style/index',
'element-plus/es/components/form-item/style/index',
'element-plus/es/components/alert/style/index',
'element-plus/es/components/breadcrumb/style/index',
'element-plus/es/components/select/style/index',
'element-plus/es/components/input/style/index',
'element-plus/es/components/breadcrumb-item/style/index',
'element-plus/es/components/tag/style/index',
'element-plus/es/components/pagination/style/index',
'element-plus/es/components/table/style/index',
'element-plus/es/components/table-column/style/index',
'element-plus/es/components/card/style/index',
'element-plus/es/components/row/style/index',
'element-plus/es/components/button/style/index',
'element-plus/es/components/menu/style/index',
'element-plus/es/components/sub-menu/style/index',
'element-plus/es/components/menu-item/style/index',
'element-plus/es/components/option/style/index',
'@element-plus/icons-vue',
'pinia',
'axios',
'vue-request',
'vue-router',
'@vueuse/core',
],
}
}

使用插件来进行上面一段的插入

1
npm i -D vite-plugin-optimize-persist vite-plugin-package-config

包引入失败
git主页有这句话 You no longer need this plugin since Vite 2.9.1
按照提示加了 --legacy 强制装上了,然后手动删除了 node_modules/.vite 文件夹,重新运行代码,速度略微提高。可能还有其他原因,或者是我自己的配置问题,在以后实验后继续更新。

解决方案二(待调研…)

Q & A

“no such file or directory, rename ‘/node_modules/.vite/deps_temp’ -> ‘/node_modules/.vite/deps’”
升级vite

附录
Vite官方文档
vite首次打开界面加载慢问题/解决


vue3笔记(18-2)vite 首次打开界面加载慢问题
https://guoningyan.com/2023/03/19/vue3笔记(18-2)vite首次打开界面加载慢问题/
作者
Ningyan Guo
发布于
2023年3月19日
许可协议