Automatic Component Loading with Vite

Loading global components in Vue 3 has never been easier, thanks to one of the features of Vite called Glob Import.


It's very easy to auto-import components in Vue 3. If it's just one or two components, the process can be done manually.

JS
import {createApp} from 'vue';
import GlobalComponent from './GlobalComponent.vue';
const app = createApp({})
app.component('GlobalComponent', GlobalComponent);

But, what if we want to auto-import an entire directory? For example, /components. This is where Vite and its Glob import come to our aid. Let's dive in ⚡️

Global components with Vite Glob import

First, we can use Glob import to select all files with the .vue extension.

JS
const components = import.meta.globEager('./components/*.vue');

This results in an object with this structure:

JS
{
    './components/AppComponent.vue'
:
    Module,
        './components/HelloWorld.vue'
:
    Module
}
}

As you can see, as a property we have the path to the component, and as a value, the module of the component itself.

Now, we can convert components into an Array with Object.entries and load them with the component method of the newly created Vue instance.

JS
Object.entries(components).forEach(([path, component]) => {
    myApp.component(
        path
            .split('/')
            .pop()
            .replace(/\.\w+$/, ''),
        component.default
    );
});

Note that along the way, we have to perform several operations:

  • Break the path into different segments, separated by / using the split method of Array.
  • Keep the last segment using the pop method of Array.
  • Remove the extension from the segment using the replace method of strings and a regular expression.

With all this, we already have the ability to auto-import global components in Vue 3 with Vite.

Here is the complete code:

JS
import {createApp} from 'vue';
import './style.css';
import App from './App.vue';
const components = import.meta.globEager('./components/*.vue');
const myApp = createApp(App);
Object.entries(components).forEach(([path, component]) => {
    myApp.component(
        path
            .split('/')
            .pop()
            .replace(/\.\w+$/, ''),
        component.default
    );
});
myApp.mount('#app');

Demo

Juan Andrés Núñez
Juan Andrés Núñez
Frontend Engineer. Vue.js Specialist. Professional Teacher. Stoic.