Created
September 23, 2024 07:41
-
-
Save Gkiokan/a70ed4170c5713ff05d777ac3b664a8c to your computer and use it in GitHub Desktop.
Vue autoload Components and register globally
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: Gkiokan Sali | |
* Date 2024-09-22 | |
* Note: | |
* Put this file in your src/components folder | |
* and import it in your main.ts / entrypoint | |
* call autoRegisterComponents(app) to do so | |
* -- | |
* Hint: | |
* If you wanna perfect this, put the vue cycle hook methods inside | |
* and then you can use it as a Plugin via app.use(AutoRegisterComponents) | |
**/ | |
import { App, DefineComponent } from 'vue'; | |
/** | |
* Automatically register all components from the components folder. | |
*/ | |
export default function autoRegisterComponents(app: App) { | |
// Import all .vue files in the components folder | |
const components: Record<string, { default: DefineComponent<{}, {}, any> }> = { | |
...import.meta.glob('./autoload/**/*.vue', { eager: true }), | |
...import.meta.glob('./icons/**/*.vue', { eager: true }), | |
...import.meta.glob('./ui/**/*.vue', { eager: true }), | |
} | |
for (const path in components) { | |
const component = components[path].default; | |
// Extract the file name and use it as the component name | |
const componentName = path.split('/').pop()?.replace(/\.\w+$/, ''); | |
if (componentName) { | |
app.component(componentName, component); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment