Javascript is required
·
1 min read
·
545 views

Vue Tip: Automatic Global Registration of Base Components

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:

1import BaseButton from './BaseButton.vue'
2import BaseIcon from './BaseIcon.vue'
3import BaseInput from './BaseInput.vue'
4export 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):

1import { createApp } from 'vue'
2import upperFirst from 'lodash/upperFirst'
3import camelCase from 'lodash/camelCase'
4import App from './App.vue'
5
6const app = createApp(App)
7
8const 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
17requireComponent.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
41app.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 & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.