Skip to content

Instantly share code, notes, and snippets.

@jirehnimes
Last active September 13, 2023 08:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jirehnimes/2fcb31a2cbe7bb0c722a96f49e4cbf8f to your computer and use it in GitHub Desktop.
Save jirehnimes/2fcb31a2cbe7bb0c722a96f49e4cbf8f to your computer and use it in GitHub Desktop.
vue3-global-registration-of-components.md

How to register your global components dynamically in Vue 3?

components/base/index.ts

import { App } from 'vue';

const requireComponent = require.context(
  // The relative path of the components folder
  './',
  // Whether or not to look in subfolders
  false,
  // The regular expression used to match base component filenames
  /[A-Z]\w+Base\.vue$/,
);

const register = (app: App<Element>): void => {
  requireComponent.keys().forEach((fileName) => {
    // Get component config
    const componentConfig = requireComponent(fileName);
    // Get component name
    const componentName = fileName.split('/').pop()?.replace(/\.\w+$/, '') as string;

    app.component(componentName, componentConfig.default || componentConfig);
  });
};

export default {
  register,
};

main.ts

import { createApp } from 'vue';

import BaseComponents from './components/base';

const app = createApp(App);

BaseComponents.register(app);

app.mount('#app');
@jahid32
Copy link

jahid32 commented Oct 15, 2022

Hi, I am try to implement your solution but getting following erro
Uncaught ReferenceError: require is not defined.
I am using vitjs for scaffolding my project

@mouradsm
Copy link

Same error here

@atach
Copy link

atach commented Sep 13, 2023

I also get an error in VUE3/VITE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment