DEV Community

Lucas Vilaboim
Lucas Vilaboim

Posted on • Edited on

2 2

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay