首先在讲述vite优化之前,我们先来分析一下和传统的项目管理构建工具的区别,以webpack为例,它是利用plugin插件和loader加载器对项目的所有模块和依赖统一通过入口文件进行编译,从而变成我们html所需要的js格式渲染我们的页面。
随着浏览器的发展,逐渐的已经支持了 ES 模块
因此Vite在设计时考虑在浏览器请求源码时进行转换并按需提供源码。根据情景动态导入代码,即只在当前屏幕上实际使用时才会被处理。
优势:
这样就避免了随着应用体积的增大,导致了启动服务缓慢,一处代码更新界面需要数秒钟才能显示的问题。运行速度真的没得说。


当然我们今天说的不止是这些,既然选择了vite框架,自然不会考虑浏览器的兼容性,我们更多的还是关注vite本身的性能。
优势即劣势
正是因为vite本身是动态加载的资源,当某个路由的依赖项比较多的时候,加上你可能使用了某些组件库的按需加载(比如element-plus),在进入页面时可谓是很慢,而且页面都是会像卡壳了一样刷新一次。
技术层观察的表现是,network加载了很多资源,同时在cmd终端会显示:
下午7:01:09 [vite] ✨ new dependencies optimized: element-plus/es/components/message-box/style/index 下午7:01:09 [vite] ✨ optimized dependencies changed. reloading 下午7:01:23 [vite] ✨ new dependencies optimized: element-plus/es/components/form/style/index 下午7:03:57 [vite] vite.config.ts changed, restarting server...
这是因为需要按需写入组件与样式导致的,那么怎么解决这一问题呢,我们更希望在开发环境下,能提高我们的运行速度,而且让生成环境的包体积更小。然而,好像没有太好的解决方案,因为第一次按需加载按照vite的设计就必须要写入。
换个思路,那么我只能在开发环境下全局加载组件,打包时再执行按需加载了…
// 自定义插件 ./plugins/fullImportPlugin import * as path from 'path' import type {
Plugin, ResolvedConfig } from 'vite' export default function fullImportPlugin () {
let config: ResolvedConfig return <Plugin>{
name: 'fullImportElementPlus', async configResolved (conf) {
config = conf }, transform (code, id) {
// 判断当前处理的是否是 _src/main.ts_ if (path.join(config.root, 'src/main.ts') === id) {
const name = 'ElementPlus' // 引入 ElementPlus 和 样式 const prepend = `import ${
name} from 'element-plus';\nimport 'element-plus/theme-chalk/src/index.scss';\n` code = code.replace('.mount(', ($1) => `.use(${
name})` + $1) return prepend + code } return code } } }
// vite.config.ts import {
ElementPlusResolver } from 'unplugin-vue-components/resolvers' import unElementPlus from 'unplugin-element-plus/vite' import unComponents from 'unplugin-vue-components/vite' import fullImportPlugin from './plugins/fullImportPlugin' const config = {
plugins:[] } if ( modes === 'development'){
config.plugins.push(fullImportPlugin()) } else {
config.plugins.push(unElementPlus({
useSource: true })) config.plugins.push(unComponents({
dirs:[], dts: true, resolvers: [ ElementPlusResolver() ] })) } export default config
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/218100.html原文链接:https://javaforall.net
