Issue with Vue 3: defineAsyncComponent is not able to resolve .vue files or split chunks properly

I'm currently attempting to dynamically load Vue 3 components in an asynchronous manner. I have come across a function called

defineAsyncComponent

which is intended to be utilized as shown below:

const GameUI = defineAsyncComponent(()=>import(filePath));
app.component("GameUI", GameUI);

In this context, the filePath is exactly:

'./components/GameUI/GameUI.element.vue'

When I run the application in this way, it results in the following error:

Uncaught (in promise) Error: Cannot find module './components/GameUI/GameUI.element.vue'
    at eval (eval at ./src lazy recursive)

However... if I modify the filePath code to import the path as a string:

const GameUI = defineAsyncComponent(()=>import('./components/GameUI/GameUI.element.vue'));

The application functions correctly, as it successfully locates the component.

I prefer not to use hardcoded strings, as I have numerous components that I want to load asynchronously.

One of my primary objectives is to load the web application incrementally, loading components as needed rather than all at once during startup.

I discovered that if I add a comment like this:

const GameUI = defineAsyncComponent(()=>import(/* webpackChunkName: "GameUI" */ './components/GameUI/GameUI.element.vue'));

The JavaScript segment for the GameUI component should be separated into its own chunk.js file, however, I keep receiving everything in a few .js chunk files, which contradicts the asynchronous loading I am aiming for.

I am using vue-cli-service, and my vue.config.js is configured like this:

module.exports = {
  productionSourceMap: false,
  css: {
    loaderOptions: {
        sass: {
          additionalData: process.env.NODE_ENV === 'production'
            ? '$baseURL:"/dist/";'
            : '$baseURL:"/";'
        }
    }
      },
  publicPath: process.env.NODE_ENV === 'production'
  ? '/dist/'
  : '/',
    devServer: {
      https: true,
      port:"",
      host:'website.com',
      disableHostCheck: true,
      cert: (fs.readFileSync('cert.pem')+""),
      key: (fs.readFileSync('privkey.pem')+""),
      ca: (fs.readFileSync('ca.pem')+""),
    }
  };

I have attempted various solutions I found online, but many were lacking in explanation. I am essentially following the same steps as some online articles I came across, yet I am unable to identify the issue on my end.

The main issues I am encountering are:

  • Unable to load .vue files from variables, only direct strings.
  • Unable to separate the code into different .js files for each asynchronously loaded component.

Answer №1

The method you are attempting to use is not effective because you are passing a variable as the value to defineAsyncComponent.

As per the restrictions on async imports, importing a component using a variable is not supported. Instead, you should follow this approach:


// Assuming the component name to load is GameUI.element
const component = 'GameUI.element' // can be retrieved dynamically
const GameUI = defineAsyncComponent(()=>import(`./components/GameUI/${component}.vue`));

app.component("GameUI", GameUI);

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 images on the carousel fail to load unless I adjust the window size

After investing countless hours into finding a solution, I am still unable to resolve this issue. The problem lies within my use of a Carousel and setting the images through a javascript file. Strangely enough, upon loading the page, only the first image ...

How can I disable the automatic generation of index paths from embedded documents in mongoose?

It appears that mongoose is automatically generating indexes for embedded documents. Is there a setting to disable the automatic index creation feature? For instance, the code snippet https://github.com/Automattic/mongoose/blob/master/lib/schema.js#L940 s ...

Customize nestjs/crud response

For this particular project, I am utilizing the Nest framework along with the nestjs/crud library. Unfortunately, I have encountered an issue where I am unable to override the createOneBase function in order to return a personalized response for a person e ...

Construct an array through the power of Ajax

Currently, I am facing an issue with building an array using ajax. The 'test' array is structured correctly, but the 'translations' array has a flawed structure (as seen in my console output). In Chrome console: https://i.sstatic.net/m ...

Utilize Ajax to invoke a function simultaneously with another Ajax call that includes preventDefault to submit the data

I am currently implementing two AJAX calls within my form. The first call is used to dynamically update the options in the second select element based on the value selected in the first select element. This call reaches out to a PHP page to process the dat ...

Struggling with lag in MaterialUI TextFields? Discover tips for boosting performance with forms containing numerous inputs

Having some trouble with Textfield in my MateriaUI project. The form I created has multiple inputs and it's a bit slow when typing or deleting values within the fields. Interestingly, there is no lag in components with fewer inputs. UPDATE: It appear ...

Exploring Nuxt3: Child routes and highlighting the active class in a navigation bar

Currently, I have a navigation menu where one of the links directs to "/users" (Nuxt3 project). When navigating to the "/users" route, there is a subnavigation link leading to "/users/groups". However, when I arrive at the "/users/groups" route, the main ...

Can Mongoose be integrated into a Next.js API environment?

My current project involves creating a website for my sister to showcase and sell her artwork. Utilizing Next.js, I have set up the framework where the website displays the artwork by fetching an array from a database and iterating through it. Let's ...

Compose a tweet using programming language for Twitter

How can I send a message to a Twitter user from my .NET application? Are there any APIs or JavaScript code that can help with this task? Any assistance would be greatly appreciated. ...

Reaching out to a particular individual with a message

In my coding dilemma, I am trying to make a bot send a message every minute to a particular user, not all users. The struggle is real! guild.members.cache.forEach(member => { setInterval(() => { member.send('hello').catch(error =&g ...

A Guide to Accessing Numbered Properties within an Object

I am working with a large Object that has over 700 properties, all numbered. How can I efficiently iterate through each of these numbered properties? { '0': { emails: { categorized: [Object], all: [Object], primary: &a ...

Sending dynamic data from PHP to jQuery flot pie chart

In my PHP code, I have defined 3 variables. $record = "283-161-151"; $rec = explode("-", $record); $win = $rec[0]; $draw = $rec[1]; $loss = $rec[2]; The variables $win, $draw, and $loss are displaying correctly, indicating they are working as intended. ...

Serialize the elements within an array using JSON.stringify

I'm trying to convert an object into a string, but for some reason it's not working correctly: function httpRequest(url) { this.url = url; this.headers = []; } var req = new httpRequest("http://test.com"); req.headers["cookie"] = "version=1 ...

Utilizing module.exports and ES6 for exporting imports

I am currently facing an issue trying to import a function into a file and then export it from that file. It seems like a fairly straightforward task, but for some reason I am having trouble getting it to work. search_action.js function search_actions() ...

The "Next" button fails to function after a replay has been completed

I created a small quiz app to practice my JS skills. Everything seems to be working fine, except for one issue - when I click on replay, the quiz box shows up but the 'Next' button stops functioning. There are no console errors and I'm strug ...

Organize Dates in React Table

I need help with sorting the Date column in my code. Currently, the sorting is being done alphabetically. Here is the JSON data and code snippet: JSON [ { "date": "Jun-2022" }, { "date": "Jul-2022" } ...

Accordion feature that loads JSON data dynamically with AJAX

I am facing a challenge with my HTML structure and corresponding CSS styling. The HTML code includes an accordion container with multiple sections that can be expanded or collapsed. <div class="accordion-container"> <ul class="accordion"> ...

Limits on zooming with THREE.js Orbit controls

I've encountered an interesting limit while using Orbit controls. The zooming functionality is tied to the radius of the spherical coordinates of the camera in relation to the orbiting axis. Here's how it functions: Whenever the user scrolls, t ...

Tips for avoiding unnecessary re-renders

The component I created sends props to both the checkbox and range components. During testing, I noticed that when a change was made in the range component, the checkbox also re-rendered even though it wasn't changed, and vice versa. Issue: When ...

Detect if the content loaded in the web view is a PDF file and provide a downloadable option

I am using wkWebView to access research papers from IEEE, Science Direct, and other sources. When I click on a PDF in the research papers, it gets loaded into the webview. Is there a way to detect and enable a download icon in wkWebView? Attempted Solutio ...