unplugin-vue-components按需导入element-plus样式导致vite加载页面耗时变得很久

vite项目实际使用中,启动确实很快,但是到浏览器访问时,需要很久才能加载出来。

排查后发现是element-plus样式的原因,遂上网搜索。

  1. 让你的Vue代码 “学会” 自动按需引入open in new window
  2. vite首次打开界面加载慢问题解决open in new window
  3. vue3+vite+pinia+element-plus+vi18n生成框架记录。open in new window
  4. 解决vite首次加载很慢的问题open in new window
  5. unplugin-vue-components按需导入element-plus样式导致vite加载页面耗时变得很久open in new window

先说原因,vite之所以启动快,是因为vite启动时并不会像webpack一样对所有代码进行编译/打包/压缩, 他只会对一小部分代码进行一些简单的处理,剩余的工作都交给浏览器,以及运行时进行依赖分析,动态打包,动态引入。

而vite会预加载style,当首次启动 vite 服务时会对 style 进行依赖预构建,因为element-plus的按需样式会导入大量style文件,导致页面会卡住直至style构建完成。

第一、二条中是安装vite-plugin-optimize-persist插件,但第一条中说vite2.9版本之后不需要优化,故没有尝试。 第三、四条中使用fs插件,跳过部分加载,实测无效。 第五条是开发模式不按需加载,生产环境再按需,实测有效。

vite.config.ts代码如下

import Components from "unplugin-vue-components/vite"
import { ElementPlusResolver } from "unplugin-vue-components/resolvers"

export default ({ mode }) => {
  console.log(mode === "development" ? "开发环境 " + mode : "生产环境 " + mode)
  return defineConfig({
    ...
    plugins: [
      ...
      // 自动按需注册导入组件
      Components({
        dirs: ["src/components"], // 要导入组件的目录路径
        extensions: ["vue"],
        deep: true, // 搜索子目录
        dts: false, // 不使用ts
        include: [/\.vue$/, /\.vue\?vue/], // 只识别vue文件
        resolvers: [
          // 使用unplugin-vue-components按需加载样式,开发环境会导致项目异常卡顿
          // 导致原因:vite会预加载style,当首次启动 vite 服务时会对 style 进行依赖预构建,,因为element-plus的按需样式会导入大量style文件,导致页面会卡住直至style构建完成
          // https://github.com/antfu/unplugin-vue-components/issues/361
          //  这里开发环境不按需加载样式,生产环境才按需加载样式
          ElementPlusResolver({
            importStyle: mode === "development" ? false : "sass",
          }),
        ],
      }),
      // https://github.com/antfu/unplugin-vue-components/issues/361
      // 这里自定义一个vite插件,更改src/main.js内容,开发环境全局引入样式
      {
        name: "import-element-plus-style",
        transform(code, id) {
          if (/src\/main.js$/.test(id)) {
            if (mode === "development") {
              return {
                code: `${code};import 'element-plus/dist/index.css';`,
                map: null,
              }
            } else {
              return {
                code: `${code};import 'element-plus/theme-chalk/src/message-box.scss';import 'element-plus/theme-chalk/src/message.scss';`,
                map: null,
              }
            }
          }
        },
      },
    ],
  })
}
Last Updated:
Contributors: haizhiguang