[Vue] Routes auto generator

Zhentiw發表於2024-11-24

Need to follow some rules:

Each folder should has a page.js configuration to save the meta data.
// page.js

export default {
  title: "About",
  menuOrder: 1,
};

Generator.js:

const pages = import.meta.glob('../views/**/page.js', {
    eager: true,
    import: 'default'
})
const comps = import.meta.glob('../views/**/index.vue')

const routes = Object.entries(pages).map(([path, meta]) => {
    const compPath = path.replace('page.js', 'index.vue');
    const path = path.replace('../views', '').replace('/page.js', '') || '/'
    const name = path.split('/').filter(Boolean).join('-') || 'index'
    return {
        path,
        name,
        component: comps[compPath],
        meta
    }
})

相關文章