problem_01_自动注册项目中的组件时所遇到的问题

动态导入组件时 import.meta.glob 设置 import 为 default 且在自动注册时没判断 默认导出、命名导出 导致的问题。

错误1

将 import 设置为 import 时 export { default as xxx } from './src/xxx.vue' 会报无default错误
error during build: xxxx "default" is not exported by xxx imported by xxx

错误2

因为错误1而将组件的导出方式改成了 import xxx from 'xxx.vue';export default xxx 打包引用组件 浏览器提示 ReferenceError: Cannot access 'xxxx' before initialization 在检查所有文件的导入顺序之后发现还存在这个问题 最终猜测是存在循环引用或者暂时性死区(感觉不会出现这个情况只有一个xxx.tsx使用了xxx.vue)
最后只能将 import 去除保证默认导出、命名导出 都可以导入

代码
修改之前
import { type App } from 'vue'
import '../style.less'

const components = import.meta.glob('./**/index.ts', {
  eager: true,
  import: 'default'
}) as any

console.log('components', components)

// 导出组件库
export default function install(app: App) {
  for (const [_key, value] of Object.entries(components)) {
    const comp = value as any
    console.log('组件名:', comp.name)
    app.component(comp.name, comp)
  }
}
修改后
const components = import.meta.glob('./**/index.ts', {
  eager: true
})

// 导出组件库
export default function install(app: App) {
  for (const [_key, value] of Object.entries(components)) {
    // 兼容两种导出方式:默认导出或命名导出
    const component = (value as any).default || (value as any)
    if (component.name) {
      app.component(component.name, component)
    } else {
      console.warn(`组件 ${_key} 缺少 name 属性,无法自动注册`)
    }
  }
}
posted @ 2025-03-17 14:33  tsuru  阅读(15)  评论(0)    收藏  举报