Encountering a VueJS error when trying to locate a module while using a JSON file

I've been tasked with finding a solution to dynamically import pages within vuejs projects that are being built with a CLI tool by my team. I initially attempted to use functions as a string ("() => import(...)") and then evaluate that string, but it didn't work as expected. Currently, I am using the following approach:

{
    "routes": [
        {
            "name": "Login",
            "path": "/login",
            "component": "../../src/pages/auth/login/*"
        },
        {
            "name": "Register",
            "path": "/register",
            "component": "@/pages/auth/register"
        }
    ]
}

After defining the routes in a JSON format, I then pass them into our routes.ts file using a "driver":

import * as dynamicRoutes from './routes.json';

const routes: any[] = [];
dynamicRoutes.default.routes.forEach((elem: any) => {
    const component = async () => await require(elem.component).then((comp: any) => comp);
    routes.push({
        name: elem.name,
        path: elem.path,
        component,
    });
});

export default routes;

However, I am encountering "cannot find module" errors. When I log the output, I observe the following error message when checking the component function: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them.

Is there a way to dynamically pass routes using a JSON file, considering that we need to read from and write to this file in order to keep the routes updated?

Answer №1

Lazy loading Vue components is made easy with dynamic imports. This feature is already incorporated when you set up vue-router

const loadComponent = () => import(elem.component)

Answer №2

When you mention dynamically importing pages, it sounds like you're referring to lazy loading components dynamically. In order to achieve this, you'll need to create a Higher Order Component (HOC) for all of your route components, which can utilize ES6 import() (promise based) to fetch the component. Additionally, you can also make use of webpack magic comments for the same functionality (if you happen to be using webpack). Hope this information proves useful!

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 custom font fails to load on a customized Material UI theme

In my React web application, I tried to implement a custom font by writing the following code: import React, { FunctionComponent } from 'react' import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles' import SofiaPro ...

Different strategies for displaying a singular pie chart on multiple pages

I have implemented a pie chart on an HTML page and now I want to display this chart on multiple other HTML pages. Below is the JavaScript code for creating the pie chart: function piechart() { var chart; var legend; ...

Maximizing JavaScript efficiency: Returning a value within an if statement in an AJAX call

In my function, I have a condition that checks the idType. If it is 1, an ajax call is made to a php file to retrieve the name associated with the specific idName and return it. Otherwise, another example value is returned. function obtainName(idName, idTy ...

The socket io server connection triggers repeatedly

Currently, I am working on developing a simple game using next.js and node.js. However, when I test the game, I notice that there are multiple "connected" logs being displayed. Even though I have only one client (with just a single tab open in Chrome), the ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

The Ajax script is malfunctioning

Currently, I have a program that requires the user to input a city and country. The program then checks the database to see if the city already exists - displaying a warning message using ajax if it does, or adding the city to the database if it doesn&apos ...

Detect and switch the value of a CSS selector using Javascript

Incorporating the subsequent jQuery code to insert CSS styles into a <style id="customizer-preview"> tag within the <head>: wp.customize( 'site_title_color', function( value ) { value.bind( function( newval ) { if ( $( &a ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Tips for creating a hover-activated dropdown menu

How can I create a drop-down menu in my horizontal navigation bar that appears when hovering over the Columns tab? The drop-down menu should include options such as Articles, Videos, Interview, and Fashion. To better illustrate what I am looking for, here ...

Is it possible to implement UseState in Server-Side-Rendering scenarios?

Is it possible to utilize useState (and other react hooks?) with Server Side Rendering? I keep encountering the following error when attempting to execute the code: TypeError: Cannot read property 'useState' of null. Oddly enough, if I disable ...

Consider creating a distinct document for your "scripts"

Within my package.json configuration file, the "scripts" section contains numerous commands structured as shown below. "scripts" { "script1": "command example", "script2": "command example", "script3": "command example", "script4": "command exampl ...

Seeking a light-weight, text-rich editor specifically designed for use on our enterprise website. This editor should be even lighter than TinyMCE

I am in search of a lightweight text editor for an enterprise website, lighter than tinymce with basic buttons for the comment form. It is imperative that the editor also functions properly in IE6. So far, I have tried cleditor 15KB, but it has an issue in ...

Actions cannot be performed on elements generated by ng-repeat

I am facing a challenge where I need to display a list of languages on a page, allowing users to change their selections based on previous choices. To achieve this functionality, I have written the following code snippet: ... <tbody> & ...

Tips on customizing the appearance of mat-card-title within a mat-card

Is there a way to truncate the title of a mat card when it overflows? I tried using the following CSS: overflow:hidden text-overflow:ellipsis white-space: nowrap However, the style is being overridden by the default mat-card style. I attempted to use mat ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

Having difficulty accessing a private channel with Laravel and Vue.js due to pusher integration

I've successfully set up a notification system and everything is working fine when I send notifications to Pusher. However, I encounter an error when trying to listen on a private channel. Below is the code from my bootstrap.js file in Laravel-Echo: ...

What is the process for converting strings or text to EBCDIC using JavaScript?

In the midst of developing a website, I am working on a feature that allows users to input a minimum of 256 characters/strings (with code verification), choose between ASCII or EBCDIC conversion, and view the converted text string displayed on the page bas ...

Showcase fullcalendar events that span across multiple rows and columns

Within my Angular application, I am utilizing the Angular UI Calendar in conjunction with Fullcalendar to display user events. Currently, when a user interacts with an event by clicking on it, only a portion of the event is highlighted. This becomes probl ...

I'm so confused about the operation of each method in this context

I am experimenting with a simple process involving setTimeout function. My goal is to make the letters of a name appear individually and gradually at different times. For example, if the name is NAZ, I want the letters to appear in this order: first N, the ...

Encountering an endless loop while attempting to retrieve data from Firebase in Next.js through the use of useEffect

Currently, I am in the process of setting up a video section for a project using NextJS. The videos are stored in firebase storage. I have implemented a dynamic route that retrieves all videos from a specific reference within the bucket. For instance, if ...