Home > database >  Is there a way to import a folder structure in Vite
Is there a way to import a folder structure in Vite

Time:07-28

I have a bunch of sub-folders plus a few .vue components in the src/pages folder. With webpack I was able to get a list of the page paths and name with code like this:

export default require
  .context("../pages", true, /^\.\/.*\.vue$/)
  .keys()
  .map(page => page.slice(2).replace(".vue", ""))
  .filter(page => page !== "Index")
  .map(page => ({
    file: page,
    title: createTitle(page),
    path: slugify(kebabCase(page))
  }));

Vite doesn't seem to support this. I tried const pages = import.meta.glob('../pages/*.vue') but this only works for files, not files inside sub-folders.

Any idea how I can achieve this with Vite?

CodePudding user response:

I think you're looking for something like vite-plugin-pages :

installation :

npm install -D vite-plugin-pages

which requires vue-router to be installed :

npm install vue-router

Add to your vite.config.js:

import Pages from 'vite-plugin-pages'

export default {
  plugins: [
    // ...
    Pages(),
  ],
}

Router config :

import { createRouter } from 'vue-router'
import routes from '~pages'

const router = createRouter({
  // ...
  routes,
})

There're also other plugin like unplugin-vue-components to resolve components and vite-plugin-vue-layouts to resolve layouts

CodePudding user response:

I found a way. It's not perfect but not terrible either:

const pages = import.meta.glob('../pages/*.vue')
const folders = import.meta.glob('../pages/*/*.vue')
const both = {...pages, ...folders}
export default both

This is a refinement:

const pages = import.meta.glob('../pages/**/*.vue')
export default pages
  • Related