DEV Community

Lucas Vilaboim
Lucas Vilaboim

Posted on • Edited on

Register Global components in Vue 3

UPDATE: there is an official guide now.

Vue 2 docs has a great way to automatically register base components.
Fortunately this keeps working in Vue 3 with minimal changes.

Get started

As soon as we start a project using vue-cli and Vue 3 we will see something like this in the main.js file:

createApp(App).mount('#app')
Enter fullscreen mode Exit fullscreen mode

Let's change it up a bit to add our base components:

const app = createApp(App)

app.mount('#app')
Enter fullscreen mode Exit fullscreen mode

Before mount the app we will add our registration.

Here we require all components that are inside components folder:

const requireComponent = require.context(
  './components',
  true,
  /Base[A-Z]\w+.(vue|js)$/
)
Enter fullscreen mode Exit fullscreen mode

If you prefer to have folders and index.vue files for components you need to change the regex:

/Base[A-Z]\w+\/index.vue$/
Enter fullscreen mode Exit fullscreen mode

Finally, you need to iterate over all components and register them using the Vue instance we assigned to app variable:

requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName)

  const componentName = upperFirst(
    camelCase(
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )

  app.component(
    componentName,
    componentConfig.default || componentConfig
  )
})
Enter fullscreen mode Exit fullscreen mode

Is this real life?

There is a demo app to show the real life implementation.

Top comments (0)