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: {
    BaseButton,
    BaseIcon,
    BaseInput,
  },
};

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

<BaseButton>
  <BaseIcon name="search" />
</BaseButton>
<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
  './components',
  // Whether or not to look in subfolders
  false,
  // The regular expression used to match base component filenames
  /Base[A-Z]\w+\.(vue|js)$/
);

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

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

  app.component(
    componentName,
    // 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
  );
});

app.mount('#app');


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