技术实践

在 Vue 3中注册 Global 组件

在 Vue 3中注册 Global 组件,自动遍历文件注册全局组件

羊先生的头像
羊先生2021.05.20 · 1 分钟阅读 · 35 阅读
在 Vue 3中注册 Global 组件封面
文章正文还需 1 分钟

自动遍历文件注册全局组件

js 复制代码
import { createApp } from 'vue'
import App from './App.vue'
import upperFirst from 'lodash.upperfirst'
import camelCase from 'lodash.camelcase'

const app = createApp(App)

const requireComponent = require.context(
  // The relative path of the components folder
  './components',
  // Whether or not to look in subfolders
  true,
  // The regular expression used to match base component filenames
  /Base[A-Z]\w+.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)

  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )

  // Register component globally
  app.component(
    componentName,
    // Look for the component options on `.default`, which will
    // exist if the component was exported with `export default`,
    // otherwise fall back to module's root.
    componentConfig.default || componentConfig
  )
})

app.mount('#app')