前言
最近我自己写了一个项目基于vue3+vite,将静态页面放在自己的低配服务器+github page以及gitee pages上。但是发现了一个奇怪的问题。在进行第一次进行路由跳转的时候出现了一个零点几秒的迟钝。在本地开发的时候没有这个情况出现。在我使用webpack进行打包的时候是没有这个情况的。看了一下网上的大部分基于vite的私人开源项目也都有这个问题。我便去找原因。
找原因
刚刚开始查看是否是代码的问题,又或者是vite-plugin-mock的问题,又或者是vue-router的问题。发现都不是。是在 router.push之后开始的延迟。突然想起来vite是按需加载的。于是我就打开控制台看了看,果真如此。一个页面打开之后会请求许多的js以及css。
如图:
看一看打包文件。
一堆大小只有几kb的文件。这些文件大小不大,但是建立网络链接的时间是非常耗时的。代码开始运行需要等文件请求结束才可以。那能不能把这些几KB的打包在一起呢?
解决方案
于是我就去vite配置里面找,找到cssCodeSplit
cssCodeSplit
类型:
boolean默认:
true启用/禁用 CSS 代码拆分。当启用时,在异步 chunk 中导入的 CSS 将内联到异步 chunk 本身,并在其被加载时插入。
该配置确实可以把所有得到css打包成一个。但是不能把js打包在一起啊。所以也不行。
manualChunks
后来又看到vite的打包使用的是rollup,可以通过build-rollupoptions配置自定义rollup的配置。 rollup没有webpack=》splitChunks=》cacheGroups的属性。但是有manualChunks方法。
manualChunks
Type:
{ [chunkAlias: string]: string[] } | ((id: string, {getModuleInfo, getModuleIds}) => string | void)Allows the creation of custom shared common chunks. When using the object form, each property represents a chunk that contains the listed modules and all their dependencies if they are part of the module graph unless they are already in another manual chunk. The name of the chunk will be determined by the property key.
Note that it is not necessary for the listed modules themselves to be part of the module graph, which is useful if you are working with
@rollup/plugin-node-resolveand use deep imports from packages. For instance
简而言之可以通过文件id(路径)自定义设置key,将相同的key打包成一个文件。这不就和webpack=》cacheGroups=》test方法类似嘛。于是乎按照我的项目需求将打包分成三个大包。
······
build: {
······
rollupOptions: {
output: {
entryFileNames: `assets/entry/[name][hash].js`,
chunkFileNames: `assets/chunk/[name][hash].js`,
assetFileNames: `assets/file/[name][hash].[ext]`,
manualChunks(id) {
if (id.includes("node_modules")) {
return "vendor" //代码分割为第三方包
}
if (id.includes("views/modules")) {
return "views-modules" //代码分割为业务视图
}
if (id.includes("views/common")) {
return "views-common" //代码分割为common页面登录页
}
}
}
}
}
效果:
这样就能实现页面加载的时候按照需求,将我想要的先加载出来,读者也可以根据自己需求按照模块进行划分。
结尾
最后再搭配上vite-plugin-compression配置gzip压缩再加上nginx的gzip支持。可以同时兼顾首屏的快速加载以及后续页面跳转的流畅。对你有帮助的话要点赞哦。
就是听说点赞会加薪、升职、变帅、变美欸~
作者的其他文章: