The resolution of the dynamic imported Vue component was not successful

Upon attempting to import a dynamic component using the import() function, I encountered the following error:

[Vue warn]: Failed to resolve async component: function () {
    return __webpack_require__("./src/components/types lazy recursive ^\\.\\/field\\-.*$")("./field-" + _this.type);
}
Reason: Error: Loading chunk 0 failed.

Unfortunately, the cause of this error eludes me. Despite adjusting the esModule to false in the vue-loader config as per the Release Notes, the issue persists.

The project was set up using vue-cli 2.9.2 with the webpack template, and below is the code snippet of the problematic component:

<template>
    <div>
        <component :is="fieldType">
            <children/>
        </component>
    </div>
</template>

<script>
export default {
    name: 'DynamicComponent',
    props: {
        type: String,
    },
    computed: {
        fieldType () {
            return () => import(`./types/type-${this.type}`)
        }
    }
}
</script>


[RESOLVED]
The aforementioned code functions as intended. The root of the issue stemmed from the Loading chunk 0 failed error resulting from an edge case. By configuring webpack's output to {publicPath: '/'}, the chunks were being delivered relative to the root instead of their origin. This discrepancy became evident when calling the import function from an external server, where the linked chunk URL was mismatched. To rectify this, I had to adjust the webpack configuration to

output: {publicPath: 'http://localhost:8080/'}
.

Answer №1

The main issue lies with the import() function being asynchronous (it returns a Promise), as indicated by the error message you received:

[Vue warn]: Failed to resolve async component

A more effective approach is to utilize a watch as demonstrated in the following example (within the Promise.then(), update the componentType value), and then use either the beforeMount or mounted hook to ensure proper initialization of props=type:

<template>
    <div>
        <component :is="componentType">
            <children/>
        </component>
    </div>
</template>

<script>
import DefaultComponent from './DefaultComponent'

export default {
    name: 'DynamicComponent',
    components: {
        DefaultComponent
    },
    props: {
        type: String,
    },
    data() {
        return {
            componentType: 'DefaultComponent'
        }
    },
    watch: {
        type(newValue) {
            import(`./types/type-${newValue}`).then(loadedComponent => { this.componentType = loadedComponent })
        }
    },
    mounted() {
        import(`./types/type-${this.type}`).then(loadedComponent => { this.componentType = loadedComponent })
    }
}
</script>

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

Looking for regex to extract dynamic category items in node.js

Working on node.js with regex, I have accomplished the following tasks: Category 1.2 Category 1.3 and 1.4 Category 1.3 to 1.4 CATEGORY 1.3 The current regex is ((cat|Cat|CAT)(?:s\.|s|S|egory|EGORY|\.)?)(&#xA0;|\s)?((\w+)?([. ...

How can we determine in JavaScript whether a certain parameter constitutes a square number?

I've developed a function that can determine whether a given parameter is a square number or not. For more information on square numbers, check out this link: https://en.wikipedia.org/?title=Square_number If the input is a square number, it will ret ...

Error: Headers cannot be set once they have already been sent. I am perplexed as to why this is occurring

I can't seem to pinpoint the source of the problem...After researching the meaning of this error, it appears that I may be either sending a request or response twice somewhere in my code. However, I have thoroughly reviewed my code and cannot find any ...

What is the ideal JavaScript framework for implementing drag-and-drop, resize, and rotation features?

I am planning to create a web application that involves images and text with user handle functionalities such as drag-and-drop, resizing, and rotating. Although I have tried using JQuery UI js to implement drag-and-drop, rotate, and resize, I have encount ...

await for Vue to finish updating before continuing

My Vue component is tasked with rendering a large hierarchical data structure. I recognize that there may be opportunities to enhance the performance of this specific component, such as implementing lazy loading strategies and transforming it into an inter ...

In order to streamline our production environment, I must deactivate Vue.js devtools, while ensuring they remain active during development mode

Is there a way to prevent users from inspecting the app using devtools in production mode while keeping it enabled for local/development mode? I've tried setting up .env and .env.production files with the VUE_APP_ROOT_API variable but it doesn't ...

Learn how to implement form validation on a sliding form in just 5 easy steps using jQuery

I am new to programming and I struggle to comprehend complex JavaScript code written by others. Instead of using intricate code that I don't understand, I would like to request help in creating a simplified jQuery script for me to implement. Current ...

Maintaining the active state in Bootstrap, even when manually entering a URL, is essential for smooth

Check out this fully functional plnkr example: http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview This example includes a navigation with 2 links (routing to 2 ui-router states), and a jQuery method that ensures the active class remains on the active lin ...

Designing a layout for a chat application that is structured from the bottom up

I'm currently in the process of designing a web application for a chat platform. I have access to an API that provides a list of messages: chatsite.com/api/thread/1/messages/ [ { "id": 2, "sender": { "id": 2, ...

Discovering the process of retrieving information from Firebase using getServerSideProps in NextJs

I've been exploring ways to retrieve data from Firebase within GetServerSideProps in NextJs Below is my db file setup: import admin from "firebase-admin"; import serviceAccount from "./serviceAccountKey.json"; if (!admin.apps.len ...

What is the best method to securely install a private Git repository using Yarn, utilizing access tokens without the need to hardcode them

My initial thought was to utilize .npmrc for v1 or .yarnrc.yml for v2/3/4, but in all scenarios, Yarn does not even attempt to authenticate with Github. nodeLinker: node-modules npmScopes: packagescope: npmAlwaysAuth: true npmAuthToken: my_perso ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...

Establish remote functionality for a JSON AJAX PHP form

Recently, I encountered an issue with my Javascript code that interprets JSON from PHP. Surprisingly, it works perfectly fine on my local server, but when I attempt to transfer the script to a different server, it fails to function. To address this, I have ...

Ways to extract values from a JSON output using comparisons

I am dealing with a JSON data structure that contains information about various teams. My task is to compare the values in the teams array with the values stored in html_content.position[i]. In this comparison, the index i needs to be dynamically set withi ...

Executing jQuery AJAX requests in a chain with interdependent tasks

I am struggling to grasp the concept of magic deferred objects with jQuery. Consider the following code snippet: function callWebService(uri, filter, callback) { var data = {}; if (filter && filter != '') data['$filter&apos ...

CAUTION: Attempted to load angular multiple times while loading the page

I encountered a warning message while working on my project, causing errors in calling backend APIs due to duplicate calls. Despite attempting previously suggested solutions from the forum, I am stuck and seeking assistance. Can anyone provide guidance? Be ...

Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values. Here is the co ...

The functionality of toLowerCase localeCompare is restricted in NuxtJs VueJs Framework

Encountered a peculiar issue in NuxtJs (VueJs Framework). I previously had code that successfully displayed my stores in alphabetical order with a search filter. When I tried to replicate the same functionality for categories, everything seemed to be work ...

The gear icon in the video player is not showing up when I try to change the

I am currently trying to implement a feature that allows users to select the quality of the video. I am using videojs along with the videojs-quality-selector plugin, but even though the video runs successfully, the option to choose the quality is not appea ...

What is the best way to combine a collection of strings and HTML elements in a React application?

I am facing a challenge with my list of names. I typically use .join to add commas between each name, but one specific item in the list needs to display an icon of a star next to it based on a certain condition. The issue is that using join turns everyth ...