The mysterious unknown variable dynamically imported: ../views/Admin/Home.vue in Vue3-vue-router4 has sparked curiosity

When utilizing Vue3, Vuerouter4, and Vite

I am attempting to import components and routes into the vue router, but I am encountering an error (only for the route that contains children in my paths):

https://i.sstatic.net/TFGvr.png

This is my router code:

    import { createRouter, createWebHistory } from "vue-router";
import paths from "./path";
import { TokenService } from "@/services/storage.services.js";

// Function to define routes
function route(options) {
  let path = options.path;
  let view = options.view;
  let name = options.name;
  let meta = options.meta ? options.meta : "";
  let children = options.children ? options.children : null;
  let redirect = options.redirect ? options.redirect : null;
  let currentRoute = {
    name: name || view,
    path,
    meta,
    component: (resolve) => import(`@/views/${view}.vue`).then(resolve),
  };
  
  // Handle child routes
  if (children && Array.isArray(children)) {
    children = children.map((path) => {
      path.view = view + "/" + path.view;
      return path;
    });
    currentRoute["children"] = children.map((path) => route(path));
  }
  
  // Handle redirects
  if (redirect) {
    currentRoute["redirect"] = redirect;
  }
  
  return currentRoute;
}

// Create a new router instance
const router = createRouter({
  history: createWebHistory(),
  routes: paths
    .map((path) => route(path))
    .concat([{ path: "/:pathMatch(.*)", redirect: "admin/home" }]),
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    if (to.hash) {
      return { selector: to.hash };
    }
    return { left: 0, top: 0 };
  },
});

export default router;

The paths defined in paths.js:

 export default [
      {
        path: "/admin",
        name: "Admin",
        view: "Admin",
        redirect: "Admin/Home",
        
        // Nested child routes
        children: [
          {
            path: "Home",
            name: "Home",
            view: "Home",
            meta: {
              auth: true,
              title: "Dashboard",
            },
          },
          // Other nested routes...
        ],
      },
      
      // Additional paths...
    ];

Any insights on what could be causing the error specifically for the admin route with children?

Answer №1

I encountered the issue of changing "../views/" to "/src/views/" and it resolved the problem. It appears that using '..' did not direct it to the src folder!! Appreciation goes out to @Mohammad Masoudi

Answer №2

This may not be the optimal solution for your issue. When you execute the project in production mode, errors related to dynamic imports may occur. A possible solution is to utilize the rollup/plugin-dynamic-import-vars package. For more information, check out this resource: https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars

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 integration of signalR with jquery mobile is posing several challenges

Recently, I started working with jquery mobile and signalR to implement a calling feature in my mobile app. However, I encountered an error that looks like this: http://localhost:2286/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%2 ...

The entry '0-0' already exists for the key 'local_part', please enter a unique value

Creating a simple API to handle GET, POST, DELETE, and UPDATE requests. The GET method is functioning correctly, but encountering an issue with the POST method. When attempting to post data, an error is being encountered: error: Error: ER_DUP_ENTRY: ...

The function `open` is not a valid prop for the `Dialog` component

Upon clicking an icon, a dialog box containing a form should appear for either adding a tab or deleting a specific tab. I have utilized reactjs, redux, and material-ui for the components. While I am able to display the dialog box when the icon is clicked, ...

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

Determine how the scale of a transform changes over time by calculating the function of elapsed time [ transform: scale(x, y

I am currently working on a container that can be expanded and collapsed simply by clicking on a chevron icon. The functionality to collapse or expand the container resides within a function called transformAnimation. This function code closely resembles t ...

Personalize rejection message in the context of Promise.all()

Hello, I am currently working on customizing the error response in case a promise from an array fails. After referencing Handling errors in Promise.all, I have come up with the following code. However, I may need to make some adjustments to achieve the de ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Using Axios to Integrate an API - Displaying a Username and Password Pop-up

I have been given a project that involves API integration. I have successfully retrieved data from the API, but there is a pop-up appearing asking for a username and password. Although I have these credentials, I would like to log in without that pop-up ap ...

Error: The variable "deleted1" is not declared and cannot be used on the HTML button element's onclick

Hello, I need assistance from someone. I encountered an error message after trying to delete a row even though I have declared the button already. Error: deleted1 is not defined at HTMLButtonElement.onclick Could it be due to the script type being modul ...

In JavaScript, the return statement is used to halt the execution of any subsequent statements

I encountered a situation where I need to stop the execution of the next function call if the previous function has a return statement. However, I noticed that even though there is a return statement in the "b" function below, the next function call still ...

Updating the URL path within the CSS file post Vue production build

I have set up my application on a subdomain, for example: https://www.example.com/subdomain/app/. Within the scss files of my application, I am using certain fonts. font-family: 'Gibson' src: url('/static/fonts/gibson/regular/gibson ...

JavaScript: Collection of Pictures

I've recently begun my journey into HTML and JavaScript by working on a basic website that showcases four images using a for loop. However, upon viewing the website in a browser, I noticed that only the names of the images are displayed, not the actua ...

Is there a way to adjust the scrolling speed of a background image to be slower than the rest of

I'm searching for an example similar to this: Are there any efficient javascript solutions available? I've had difficulty implementing the code I've come across so far. ...

Creating beautifully formatted PDFs using pdfmake in AngularJS

I have a HTML popup displaying data retrieved from the server, and I am attempting to download this data as a PDF using the pdfmake plugin. While I am able to generate the PDF file, the challenge lies in replicating the HTML page layout in the PDF. Here is ...

Using .htaccess for a 301 Redirect

I am currently working on setting up 301 redirects, and regardless of whether I implement the redirect in .htaccess or use a meta or javascript redirect, they all seem to be working. However, there is an issue where the old URL or directory is being append ...

The variable was not properly sent to the backing bean

I am experiencing an issue with a certain piece of code. I have a variable called fieldToStore that is defined. When I alert it or check its value in the firebug console, everything seems fine. However, when I pass it to myBean, it always ends up being und ...

Ways to navigate to a different page in React when a user clicks?

When working on my react app, I encountered an issue where the useHistory hook was undefined. How can I troubleshoot this problem and ensure that useHistory is properly defined? App.js import 'bootstrap/dist/css/bootstrap.css' import React f ...

The CSS hamburger menu halves in size when being closed

I have successfully created a CSS/JS hamburger menu with a transforming icon upon clicking. However, I encountered a bug where, upon clicking the 'close' button on the hamburger, the navigation menu cuts behind the header, resulting in a messy ap ...

Utilizing JavaScript and its scope to include text within an HTML document

I am currently working on a program that receives input from the user twice, specifically a risk carrier and a sum (although it is just a placeholder for now), groups these two values together, and then repeats the contents in a loop. You can see the progr ...

What is the best way to retrieve the overall error status from the Material UI DataGrid?

I am currently utilizing the Material UI DataGrid element to display information from an EXCEL file. Each Excel document consists of numerous column titles with specific types assigned to them. As an example: const columns = [ { "field&quo ...