Vite Vue注册全局组件

103 阅读1分钟

require.context 在Vite中会报错,提示require不存在,所以要借助vite 提供的glob()

components目录下面创建Global目录,并在目录下面创建index.ts

import type {Component, App} from 'vue'

const globalComponent = (app: App) => {
    const comp = import.meta.glob("./*.vue")
    Object.keys(comp).forEach(key => {
        comp[key]().then((module: any) => {
            const name = key.replace(/\.\/|\.vue/g, '');
            app.component(name, module.default)
        })
    })
}

export default globalComponent

然后在main.ts中引入改ts文件

import globalComponent from "@cg/index"
const app = createApp(App)
globalComponent(app)

这样就能主动将Global目录下面的vue文件注册成全局组件