Fast + Vue3 + VueRouter Lazy Load Routes According to Files

I am currently working on implementing Domain-Driven Design (DDD) to Vue, and the project structure looks like this:

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

The goal is for src/App/router/index.ts to populate all routes under src//router/index.ts. Here 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 issue I'm experiencing (as I am still learning TypeScript, please be patient with me) is that no routes are being generated even though I have pushed the objects into routes, and there are no error messages being displayed. The console only shows a warning stating:

[Vue Router warn]: No match found for location with path "/"
.

If you could guide me in the right direction, I would greatly appreciate it. Thank you!

Answer №1

After much exploration, I have finally found the solution.

The import.meta.glob function returns a Promise object, which explains why the routes variable was empty initially as it had not yet resolved.

I discovered that by using import.meta.glob with the parameter {eager: true}, you can avoid dealing with Promises altogether. Here is the revised code:

//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) {
  // Since it's eagerly loaded, there are no Promises to deal with.
  routes.push(importedRoutes[modules]);
}

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

export default router;

Answer №2

Upon reviewing the solution provided, I have identified an error related to the array not being flattened properly and still appearing as an object. Below is the revised solution:

import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'

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

for (const modules in importedRoutes) {
  routes.push(importedRoutes[modules])
}

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

export default router

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing vue.js to insert a new user into the user array stored in a JSON file

I'm encountering an issue with vue.js where I am unable to successfully add a new user to the user array. Despite console.logging "this.user" when calling the function on submit, I am not seeing a new box with the new user or the new user being added ...

Vue application experiencing never-ending update cycle following array assignment

Here is the JavaScript code I am working with: const storage = new Vue({ el: '#full-table', delimiters: ['[[', ']]'], data: { events: [], counter: 0, }, methods: { eventCounter: fu ...

I am encountering an issue where my Vue navbar is successfully changing the route but not updating the corresponding router-view

I have been working on a single-page application using Vue and I encountered an issue with the navbar when navigating through routes. The problem is that after the first click on a navbar item, the route changes successfully but the router-view does not up ...

What is the best way to adjust and filter an array based on a single value?

Here is an array that needs to be modified: [ {name: "test", value: "test", group: 0}, {name: "test1", value: "test2", group: 0}, {name: "test3", value: "test3", group: 1}, {name: "te ...

Incorporating an image within a v-for loop in Vuetify

I am planning to incorporate images at a later stage, but I am currently utilizing v-for and facing a dilemma of how to seamlessly introduce the image within the loop without disrupting its flow. <template> <v-card> <p v-for="item ...

A guide on retrieving information from a JSON file in Vite with ReactJS

Note vitejs build tool is utilized for creating a reactjs-app. Question During development, I can successfully access data.json on the server. However, when it comes to production, I encounter an issue where data.json cannot be retrieved. How can this be ...

I am deciding between using CommonJS or ES module for my sub packages in a Yarn workspace for my Next.js project. Which one

Currently working on a Next.js monorepo project using TypeScript and yarn workspace. Within the yarn workspace, there are two packages: /web and /api. The /web package is a next.js project, while /api serves as a shared subpackage utilized by /web. /my-pr ...

Navigating an object in TypeScript: the right approach

Curious if there might be a bug in TypeScript? Just seeking clarification on whether my code is incorrect or if there is an actual issue with the language. interface Something { key1: string; key2: number; key3: boolean; } const someObject: S ...

Issue with Vue 3 binding when select option is not displaying in updated values, causing select to remain blank instead of changing to an empty value

Having two components - an Input and a Select, where the options displayed in the select depend on what is inputted in the Input. If the selected option is not present in the new set of options, either choose the default option or the first option "select ...

Advantages of optimizing NodeJS/TypeScript application by bundling it with webpack

Currently, I am working on a Node/Express application and I am interested in incorporating the most recent technologies. This includes using TypeScript with node/Express along with webpack. I have a question: What advantages come with utilizing webpack t ...

Define an object in TypeScript without including a specific field type in the definition

Let's consider a scenario where there is an interface called Book: interface Book { id: number info: { name: string, } } Next, a list named bookList is defined: const bookList: Book[] = [ { id: 1, info: { ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...

Issue with Vue JS component on blade template page

Having trouble loading a Vue component into a Laravel blade file? Despite making changes, the content of my vue file isn't showing up in the blade file - even though there are no errors in the console. Any suggestions on how to resolve this issue woul ...

The hierarchy of importance in React ViteJs for CSS modules

Working on my React project with ViteJs, I rely on Material UI for the theme and components. To maintain code readability, especially for elements requiring multiple style property lines, I decided to create a separate module.scss file to handle the CSS as ...

Is it possible to retrieve and utilize multiple Enum values in Typescript?

Combine enum values to retrieve corresponding enum strings. Consider the following scenario: enum EnumDays { NONE = 0, SUN = 1, MON = 2, TUE = 4, WED = 8, THU = 16, FRI = 32, SAT = 64, ALL = 127 } If I pass a value o ...

I am seeking to modify the CSS of the parent component upon the loading of the child component in Angular

In my Angular blog, I have a root component with a navigation bar containing router links to create a single-page application. My goal is to darken the background around the link when the child component loads. Currently, the link highlights only when pres ...

Facing issues with vertical Tab display in Bootstrap using Vue.js - unexpected results

Below is the script I am working with: <vue-tabs class="row" direction="vertical" value="Description"> <div v-for="(siteParts, index) in sitePartLine"> <v-tab :title="sitePartLine[index].serial_no" v-if="sitePartLine[i ...

Utilize a prefix when importing Vue from the node_modules directory

Setting up my development environment on Ubuntu 20.04 involves using the following tools: PhpStorm 2020.3 as my IDE CodeIgniter v4 Vue 3.x Tailwind CSS+UI After creating a test project, I followed the documentation and ran the following commands: npm ins ...

Can you provide guidance on how to specifically specify the type for the generics in this TypeScript function?

I've been diving into TypeScript and experimenting with mapped types to create a function that restricts users from extracting values off an object unless the keys exist. Take a look at the code below: const obj = { a: 1, b: 2, c: 3 } fun ...

Manage interfaces and structures

I am looking to implement user roles in my application. Here is a snippet of the code I would like to use: export interface User{ name: string roles: Roles[] } interface Roles{ ADMIN: new Permissions(1,1,1,1,1), MOD: new Permissions(1,0,1,1,0,0), [. ...