动态导入使用

文档地址:https://cn.vitejs.dev/guide/features.html#glob-import

webpack 中:

  1. / https://webpack.js.org/guides/dependency-management/
  2. require.context('./test', false, /\.test\.js$/);

Vite 中:

  • import.meta.glob

该方法匹配到的文件默认是懒加载,通过动态导入实现,构建时会分离独立的 chunk,是异步导入,返回的是 Promise,需要做异步操作:

  1. const Components = import.meta.glob('../components/**/*.vue');
  2. // 转译后:
  3. const Components = {
  4. './components/a.vue': () => import('./components/a.vue'),
  5. './components/b.vue': () => import('./components/b.vue')
  6. }
  • import.meta.globEager

该方法是直接导入所有模块,并且是同步导入,返回结果直接通过 for…in循环就可以操作:

  1. const Components = import.meta.globEager('../components/**/*.vue');
  2. // 转译后:
  3. import * as __glob__0_0 from './components/a.vue'
  4. import * as __glob__0_1 from './components/b.vue'
  5. const modules = {
  6. './components/a.vue': __glob__0_0,
  7. './components/b.vue': __glob__0_1
  8. }

如果仅仅使用异步导入 Vue3 组件,也可以直接使用 Vue3 defineAsyncComponent API 来加载:

  1. // https://v3.cn.vuejs.org/api/global-api.html#defineasynccomponent
  2. import { defineAsyncComponent } from 'vue'
  3. const AsyncComp = defineAsyncComponent(() =>
  4. import('./components/AsyncComponent.vue')
  5. )
  6. app.component('async-component', AsyncComp)

配置全局 scss

文档地址:https://cn.vitejs.dev/config/#css-preprocessoroptions

配置在 vite.config.ts 得 css.preprocessorOptions.additionalData 中:

  1. // vite.config.ts
  2. export default defineConfig({
  3. css: {
  4. preprocessorOptions: {
  5. // 添加公共样式
  6. scss: {
  7. additionalData: '@import "./src/style/style.scss";'
  8. }
  9. }
  10. },
  11. // 省略其他配置
  12. })

vite 项目第一次启动打开页面很慢?

https://blog.csdn.net/pzy_666/article/details/123017630