如何在本地Vue项目中批量注册全局组件

157 阅读1分钟

假设在我们的前端Vue2项目中,我们需要将 components-global 文件夹下的所有组件自动注册为全局组件,怎么实现呢?

首先我们可以在 components-global 文件夹下 新建 index.js文件,然后输入下方的代码,

index.js :

// 如果项目基于webpack构建
export default {
    install: function (Vue) {
        const requireComponent = require.context('@/components-global', true, /\.vue$/)
        requireComponent.keys().forEach(filePath => {
            let components
            const componentConfig = requireComponent(filePath)
            if (componentConfig.name === undefined && componentConfig.default) {
                components = componentConfig.default
            }

            Vue.component(components.name, components || componentConfig)
        })
    }
}

// 如果项目基于vite构建
export default {
  install: function (Vue) {
    const components = import.meta.glob('@/components-global/**/*.vue', { eager: true })
    for (const k in components) {
      const component = components[k].default
      if (component.name) {
        Vue.component(component.name, component)
      } else if (component.install) {
        Vue.use(component)
      }
    }
  }
}

最后在main.js中引入并注册即可。

main.js :

import componentsGlobal from '@/components-global'
Vue.use(componentsGlobal)