Javascript is required
Michael Hoffmann LogoMichael Hoffmann

Vue Tip: Automatic Global Registration of Base Components

Michael Hoffmann - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Jan 14, 2022
1 min read
|
545 views
Script
Vue Tip: Automatic Global Registration of Base Components Image

Base components are relatively generic components, like basic inputs or buttons. These components are frequently used across our application inside other components.

A typical component import might look like this:

1
import BaseButton from './BaseButton.vue'
2
import BaseIcon from './BaseIcon.vue'
3
import BaseInput from './BaseInput.vue'
4
export default {
5
components: {
6
BaseButton,
7
BaseIcon,
8
BaseInput,
9
},
10
}

These imports are necessary to be able to reference the components inside our template:

1
<BaseButton>
2
<BaseIcon name="search" />
3
</BaseButton>
4
<BaseInput v-model="searchText" />

Using webpack or Vue CLI we can use require.context to globally register only these very common base components.

Here's a code example from the official Vue docs to globally import base components in your app's entry file (e.g. src/main.js):

1
import { createApp } from 'vue'
2
import upperFirst from 'lodash/upperFirst'
3
import camelCase from 'lodash/camelCase'
4
import App from './App.vue'
5
6
const app = createApp(App)
7
8
const requireComponent = require.context(
9
// The relative path of the components folder
10
'./components',
11
// Whether or not to look in subfolders
12
false,
13
// The regular expression used to match base component filenames
14
/Base[A-Z]\w+\.(vue|js)$/
15
)
16
17
requireComponent.keys().forEach((fileName) => {
18
// Get component config
19
const componentConfig = requireComponent(fileName)
20
21
// Get PascalCase name of component
22
const componentName = upperFirst(
23
camelCase(
24
// Gets the file name regardless of folder depth
25
fileName
26
.split('/')
27
.pop()
28
.replace(/\.\w+$/, '')
29
)
30
)
31
32
app.component(
33
componentName,
34
// Look for the component options on `.default`, which will
35
// exist if the component was exported with `export default`,
36
// otherwise fall back to module's root.
37
componentConfig.default || componentConfig
38
)
39
})
40
41
app.mount('#app')

If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:

New Vue & Nuxt tips delivered to your inbox:
I will never share any of your personal data.