问题
vue2官网文档中专门介绍如何基础组件的自动化全局注册,这样可以直接使用自定义组件而不用写一堆import,但是vue3的官网文档中却没有提到,只有全局注册。
解决
利用vite3特有的glob-import
自定义插件
- 方案1 懒加载
yarn build打包时每个vue都是独立的js
plugins.ts
import { App, Component, defineAsyncComponent, AsyncComponentLoader } from 'vue'
export const componentsRegistration = {
install: (app: App) => {
const modules: Record<string, AsyncComponentLoader> = import.meta.glob('../components/**/*.vue')
for (const path in modules) {
const componentName = path
.split('/')
.pop()
?.replace(/\.\w+$/, '') as string
const component = defineAsyncComponent(modules[path])
app.component(componentName, component)
}
}
}
- 方案2直接加载
yarn build打包时合成一个js
plugins.ts
import { App } from 'vue'
export interface ComponentModule {
default: Component
}
export const componentsRegistration = {
install: (app: App) => {
const modules: Record<string, ComponentModule> = import.meta.glob('../components/**/*.vue', { eager: true })
for (const path in modules) {
let componentName = path
.split('/')
.pop()
?.replace(/\.\w+$/, '')
componentName = componentName || ''
const module = modules[path]
app.component(componentName, module.default)
}
}
}
使用插件
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { componentsRegistration} from './global/plugins'
const app = createApp(App)
app.use(componentsRegistration)
app.mount('#app')