Mokkapps Logo

Vue Tip: Automatic Global Registration of Base Components

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
January 14, 2022
1 Minuten Lesezeit
- Ansichten

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

A typical component import might look like this:

import BaseButton from './BaseButton.vue';
import BaseIcon from './BaseIcon.vue';
import BaseInput from './BaseInput.vue';
export default {
  components: {

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

  <BaseIcon name="search" />
<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):

import { createApp } from 'vue';
import upperFirst from 'lodash/upperFirst';
import camelCase from 'lodash/camelCase';
import App from './App.vue';

const app = createApp(App);

const requireComponent = require.context(
  // The relative path of the components folder
  // Whether or not to look in subfolders
  // The regular expression used to match base component filenames

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName);

  // Get PascalCase name of component
  const componentName = upperFirst(
      // Gets the file name regardless of folder depth
        .replace(/\.\w+$/, '')

    // Look for the component options on `.default`, which will
    // exist if the component was exported with `export default`,
    // otherwise fall back to module's root.
    componentConfig.default || componentConfig


If you liked this tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github