Quick + Vue Router - Lazy Loading Modules

For my personal project, I am using Vite alongside Vue 3 and have integrated vue-router@4 for managing routes. Since all of my modules share the same set of routes, I created a helper function:

import { RouteRecordRaw } from 'vue-router'
import pluralize from 'pluralize'
import Str from '@supercharge/strings'

export function createRoutes(name: string): Array<RouteRecordRaw> {
    const plural = pluralize.plural(name)
    const path = Str(plural).trim().lower().kebab().get()
    const module = Str(plural).trim().studly().get()
    const titleSingular = Str(pluralize.singular(name)).title().get()
    const titlePlural = Str(plural).title().get()

    return [
        {
            path: `/${path}`,
            name: titlePlural,
            component: () => import(`@/views/${module}/index.vue`),
        },
        {
            path: `/${path}/:id`,
            name: titleSingular,
            component: () => import(`@/views/${module}/Single.vue`),
        },
        {
            path: `/${path}/new`,
            name: `New ${titleSingular}`,
            component: () => import(`@/views/${module}/New.vue`),
        },
    ]
}

A problem arises because Vite does not seem to support dynamic imports.

3:05:29 pm [vite] warning: 
G:/Dev/world-building/client/src/router/util.ts
21 |        path: `/${path}/new`,
22 |        name: `New ${titleSingular}`,
23 |        component: () => import(`@/views/${module}/New.vue`)
   |                                ^
24 |      }
25 |    ];
The above dynamic import cannot be analyzed by vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.

  Plugin: vite:import-analysis
  File: G:/Dev/world-building/client/src/router/util.ts

I checked the provided link to understand the limitations, but my approach seems to align with the supported formats.

Why isn't my code functioning properly? Everything looks correct, yet I keep receiving the warning mentioned above (and encounter an error in the console when attempting to access routes using dynamic imports).

As additional information, the error displayed in the console reads:

TypeError: Failed to resolve module specifier '@/views/Galaxies/index.vue'

Answer №1

UPDATE: The latest version of Vite, 3.x (specifically 3.0.0-alpha.7), now includes support for aliases in dynamic imports. To get this update, run the following command:

npm i -D vite@alpha

Check out the demo using Vite 3


Vite 2.x: The reason your code is not working is because the import paths are violating a specific rule:

Imports should start with either ./ or ../.

To resolve this issue, you can replace @ with the resolved path. Assuming that @is aliased to <projectRoot>/src, and if router.js is located in <projectRoot>/src, you should replace @ with ./:

return [
  {
    path: `/${path}`,
    name: titlePlural,
    component: () => import(`./views/${module}/index.vue`),
  },                         👆
  {
    path: `/${path}/:id`,
    name: titleSingular,
    component: () => import(`./views/${module}/Single.vue`),
  },                         👆
  {
    path: `/${path}/new`,
    name: `New ${titleSingular}`,
    component: () => import(`./views/${module}/New.vue`),
  },                         👆
]

Check out the demo using Vite 2

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

The sequence of operations when assigning in Typescript with || and utilizing the array .find method

I need to ensure that the operations in my assignment are happening in a specific sequence. As far as I can tell, it should be following the order listed below. However, I have not been able to locate any documentation on TypeScript that definitively confi ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

What does Typescript compile when aiming for ES5 / ES3?

I'm currently grappling with the nuances of when the Typescript compiler decides to transpile code in order to align it with my designated target ECMAScript version (ES5 or ES3). As an example, TSC has no problem transpiling for(var int of intArray); ...

What is the best way to exceed the capacity of a function in TypeScript by incorporating optional

I've been working on converting some code from JavaScript to TypeScript, and I have a specific requirement for the return type of a function. The function should return void if a callback parameter is provided, otherwise it should return Promise<o ...

How about setting variables in Vue router as an alternative to controlling component visibility?

Utilizing URL parameters to set variables in my Vue application is a goal of mine. While I initially thought vue-router would be the perfect solution, it appears to be more catered towards handling the showing and hiding of components within a router-view ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...

Utilizing Vuex to manage the state of modal components within a list of child components

I am attempting to utilize vuex to maintain a value that controls the visibility of a modal in a child component. The parent component renders the child component multiple times in a list, but the modal consistently displays only the last item in the list. ...

Typescript: Utilizing a generic array with varying arguments

Imagine a scenario where a function is called in the following manner: func([ {object: object1, key: someKeyOfObject1}, {object: object2, key: someKeyOfObject2} ]) This function works with an array. The requirement is to ensure that the key field co ...

Loop through each instance of a data record in a JSON document using Vue's v-for directive

I am currently working on a project that involves extracting data from a website that monitors traffic jams and maintenance work. My goal is to specifically retrieve information about traffic jams and display them individually. The code I am using utilize ...

The Authorization header in POST and PATCH fetch requests is stripped by Typescript

I have developed an API in C# that utilizes JWT tokens for authorization. On the frontend, I store these tokens in local storage and retrieve them when making a request. GET or DELETE requests work seamlessly, as I can verify through console.log() that t ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

The operation of moveImage does not exist

Currently, I am attempting to incorporate setInterval with my moveImage function in order to modify the position of an image. Here is a snippet of my code: <template> <div class="randImg"> <img v-bind:style="{top: imgTop + 'px&ap ...

Can you explain the purpose of the child-flex option within a v-flex component in Vuetify?

Reviewing the Vuetify online documentation regarding Grid Systems and Unique Layouts, it was noted that the v-flex tag used for the Orange block includes a child-flex parameter. <v-flex d-flex xs12 sm2 child-flex> <v-card color="orange l ...

What are some strategies for distinguishing between callable and newable types?

I seem to be facing a challenge related to narrowing, specifically the differentiation between Fnc (callable) and Class (newable). The code snippet provided functions in Playground, but the autocomplete feature is lacking, as shown in the first image. My ...

What is the best way to organize information in a table based on the date

This is my data table https://i.stack.imgur.com/1DNlj.png in the displayed table, the registration dates are sorted with the oldest date at the top. However, I aim to have the newest data displayed first. Below is the code snippet I am using: this.dataSo ...

Develop a fresh class by inheriting from HTMLDivElement and expanding its prototype

My goal is to add a new method to the HTMLDivElement prototype without cluttering the HTMLDivElement itself with my custom methods. This has led me to attempt creating a new class that extends the HTMLDivElement. export class ScrollableElement extends HTML ...

``Incorporating event and parameter as arguments for a function in an Angular application: a tutorial

I am trying to incorporate a checkbox in Angular where if it is enabled, the event.target.checked value is true, and if it is disabled, the event.target.checked value is false. When clicking the checkbox, I need to call a function where I want to pass the ...

Is there a way to utilize an Event Emitter to invoke a function that produces a result, and pause until the answer is provided before continuing?

Looking for a way to emit an event from a child component that triggers a function in the parent component, but with a need to wait for a response before continuing. Child @Output() callParentFunction = new EventEmitter<any>(); ... this.callParen ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

Tips for handling delayed HTTP API responses in Angular

While working on my project, I encountered a delay in response when using the this.ServiceHandler.getTxnInfo([], params) API. To handle this, I implemented the use of setTimeout along with async/await. Despite these modifications, my promise ended up being ...