Skip to content

Instantly share code, notes, and snippets.

@abdoulmouctard
Created December 2, 2023 11:04
Show Gist options
  • Save abdoulmouctard/549dff055a5f9fbb70e683a481cce06c to your computer and use it in GitHub Desktop.
Save abdoulmouctard/549dff055a5f9fbb70e683a481cce06c to your computer and use it in GitHub Desktop.
import { App, defineAsyncComponent } from 'vue'
// Function to convert a string to kebab case
const toKebabCase = (str) =>
str
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/\s+/g, '-')
.toLowerCase()
// Dynamically register components by scanning the components directory
const importAllComponents = () => {
const components = {}
const componentContext = import.meta.globEager('@/components/**/*.vue')
for (const path in componentContext) {
console.log(path);
const componentConfig = componentContext[path]
const componentName = toKebabCase(path.substring(path.indexOf('components/') + 'components/'.length).replace(/\.\w+$/, '').replace(/\//g, '-'))
components[componentName] = defineAsyncComponent(() => import('@/' + path.slice(path.indexOf('components/'))))
console.log(componentName, components);
}
return components
}
// Get an object of modules for components
const registerComponents = {
install(app: App) {
for (const [componentName, componentConfig] of Object.entries(importAllComponents())) {
app.component(componentName, componentConfig)
}
},
}
export default registerComponents
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment