Home > Back-end >  Vite Vue3 VueRouter Dynamic Import Routes Based on File
Vite Vue3 VueRouter Dynamic Import Routes Based on File

Time:01-06

I'm trying to implement DDD to Vue, and the structure is as below:

src
- App
  - ...
  - router
    - index.ts
- Dashboard
  - ...
  - router
    - index.ts
- ...

The idea is for src/App/router/index.ts to populate all routes under src//router/index.ts. Below is the content of the main router file

//src/App/router/index.ts

import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";

const importedRoutes = import.meta.glob<Object>("@/**/router/index.ts", { import: 'default' });
const routes: Array<RouteRecordRaw> = [];

for (const modules in importedRoutes) {
  importedRoutes[modules]().then((route: any) => {
    routes.push(route);
  });
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes
});

console.log(router.getRoutes());

export default router;

And here is the content of src/Dashboard/router/index.ts

//src/Dashboard/router/index.ts

import DashboardView from "@/Dashboard/DashboardView.vue";

const routes = {
  name: "dashboard",
  path: "/",
  component: DashboardView,
}

export default routes;

The problem I'm facing (I'm still learning on Typescript, please be kind) is that there are no routes generated from though I've pushed the objects into routes, and there are no errors thrown as well. The console just have a warning with [Vue Router warn]: No match found for location with path "/".

Please show me the way. Thank you!

CodePudding user response:

So I've explored myself and found the answer.

import.meta.glob returns a Promise object, that's why the routes was empty, since it has not resolved.

I found that import.meta.glob accepts the parameter {eager: true} so you don't have to deal with Promise. So here's the solution:

//src/App/router/index.ts

import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw
} from "vue-router";

const importedRoutes = import.meta.glob<Object>("@/**/router/index.ts", { import: 'default', eager: true });
const routes: Object[] = [];


for (const modules in importedRoutes) {
  // No Promises since it's eager loaded.
  routes.push(importedRoutes[modules]);
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes as RouteRecordRaw[]
});

export default router;
  • Related