CreateAsyncModule using an import statement from a variable

When trying to load a component using defineAsyncComponent, the component name that should be rendered is retrieved from the backend. I have created a function specifically for loading the component.

const defineAsyncComponentByName = (componentName: string | undefined) => {
  if (componentName) {
    return defineAsyncComponent(
      () => import(`../${componentName}/${componentName}.vue`)
    )
  }
}

However, during runtime, an error occurs and the component fails to render.

CustomComponent.vue?t=1701850583908:194 Error: Unknown variable dynamic import: ../CustomComponent/CustomComponent.vue
    at dynamic-import-helper:7:96
    at new Promise (<anonymous>)
    at default (dynamic-import-helper:6:12)
    at CustomComponent.vue:54:12
    at load (runtime-core.esm-bundler.js:2369:62)
    at setup (runtime-core.esm-bundler.js:2449:7)
    at callWithErrorHandling (runtime-core.esm-bundler.js:158:18)
    at setupStatefulComponent (runtime-core.esm-bundler.js:7327:25)
    at setupComponent (runtime-core.esm-bundler.js:7288:36)
    at mountComponent (runtime-core.esm-bundler.js:5683:7) 'AsyncComponentWrapper' 'async component loader'

I need to solve this issue. As an update, I modified the function as follows.

const defineAsyncComponentByName = (componentName: string | undefined) => {
  if (componentName) {
    const importString = `../${componentName}/${componentName}.vue`
    return defineAsyncComponent(() => import(importString))
  }
}

While this change fixed the problem locally, it doesn't work in production. Additionally, Vite displays a warning on the command line.

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.

Answer №1

I've recently developed a pinia store that efficiently registers all dynamic components.

import { defineStore } from 'pinia'

export const dynamicComponentsStoreId = 'dynamicComponents'

export const useDynamicComponentsStore = defineStore(dynamicComponentsStoreId, {
  state: () => ({
    dynamicComponents: new Map<string, any>(),
  }),
  actions: {
    registerComponent(type: string, component: any) {
      this.dynamicComponents.set(type, component)
    },
    getComponent(type: string) {
      return this.dynamicComponents.get(type)
    },
  },
})

dynamicComponentsStore.registerComponent(
    'CustomComponent',
    markRaw(
      defineAsyncComponent(
        () => import(`./components/CustomComponent/CustomComponent.vue`)
      )
    )
  )

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

stop all HTML5 videos when a specific video is played using jQuery

I am facing an issue with 10 HTML5 videos on the same page, CHALLENGE Whenever I click on different videos, they all start playing simultaneously... <div><video class="SetVideo"></video><button class="videoP"></button>< ...

Tackling JavaScript: Exploring Ternary Short Circuit and If Short Circuit

I am attempting to optimize the code by using a ternary operator to quickly return false. My understanding was that using a ternary in this scenario would have the same outcome as the if statement below it, which is to instantly return false if the lengths ...

How can Material UI Textfield be configured to only accept a certain time format (hh:mm:ss)?

Looking for a way to customize my material ui textfield to allow input in the format of hh:mm:ss. I want to be able to adjust the numbers for hours, minutes, and seconds while keeping the colons automatic. Any suggestions would be welcomed. ...

What steps can be taken to obtain the fully computed HTML rather than the source HTML?

Is there a way to access the final computed HTML of a webpage that heavily relies on javascript to generate its content, rather than just the source HTML? For example, if a page contains script functions that dynamically generate HTML, viewing the page sou ...

Retrieve the image and insert it using an img tag

Working on a project, I want to include Instagram profile pictures by embedding them. Although I have the image URL, I am struggling to integrate it into my HTML page. Take a look at this sample: This provided link displays the Instagram profile picture. ...

Expanding the Functionality of Vue Lifecycle Hooks

In my specific use case, I need to execute a method on each component when it is mounted. One possible solution could be to create the method as a global mixin and then call it like this: mounted(){ this.mySpecialMethod(); } But I am curious if there ...

Is there a way to selectively include a filter in ng-repeat within a directive?

Utilizing an element directive across multiple views, the directive iterates through each 'resource' in a list of resources using ng-repeat="resource in resources". Different page controllers determine which resources are fetched from the API by ...

Wicked PDF - Pausing to Allow AJAX Request Completion

My challenge lies in creating a PDF using WickedPDF, where all my static HTML/CSS content loads perfectly. However, I am facing an issue with certain elements on the page which are populated through AJAX requests—they do not appear in the generated PDF. ...

Alert: Github Dependabot has flagged Babel as vulnerable to arbitrary code execution when compiling meticulously designed malicious code

My Github Repository's Security section is flagging this issue as Critical for both my Frontend and Backend code. I'm having trouble grasping the nature of this alert. Can someone explain what flaw it represents? After updating my dependencies, ...

TypeScript functions with Generic Constraints return specific values rather than just types

function createGenericCoordinates<Type extends number | string>( x: Type, y: Type ) { return { x, y }; } const genericCoordinates = createGenericCoordinates(1, 2); // Error (TS2322) // Type 3 is not assignable to type 1 | 2 genericCoordinates ...

Execute a function only once when using it in conjunction with ng-repeat in AngularJS

I need a way to ensure that a specific function is only called once when used in conjunction with ng-if and ng-repeat. <td ng-if="!vm.monthView && vm.yearView=='contract-year'" nginit="vm.ContractYearBaselines()" class="baseline-data ...

Steps to open and configure a Mobile-Angular modal from another controller

Is it possible to use a modal in Angular JS for mobile devices without compromising the layout? I'm having trouble setting up the controller for my modal inside my main controller and passing parameters. Should I consider using ui-bootstrap for this p ...

Is there a way to place two input fields from different forms side by side on the same line?

Here are two forms extracted from an html page: <form method="get" action="search/s" id="number"> <div style="text-align: center;"> <input type="text" id="regNo" name="regNo" size="30" maxLength="50" > or ...

Revamp State before redirecting using React Router Dom

In my current project, I am facing an issue with redirecting after updating the state successfully. The technologies I'm using include React 16.12.0 and React Router DOM 5.1.2. Here's the scenario: I have a button that, when clicked, should updat ...

Retrieve an Array Containing a Mix of Objects and Functions in Typescript

Let's address the issue at hand: I spent several months working with a custom React Hook using plain JavaScript, and here is the code: import { useState } from 'react'; const useForm = (initialValues) => { const [state, setState] = ...

Automatically submitting forms without having to refresh the page

I have been searching for answers online, but none of them seem to help me. Additionally, I am struggling to grasp the concept of Ajax. I need everything to happen on a single page without any refreshing until the entire form is submitted. <form id=" ...

Experimenting with async generator using Jest

It has become clear that I am struggling with the functionality of this code, especially when it comes to testing with Jest. Despite my efforts to use an await...of loop, I am not getting any output. The file path provided to the generator is correct and I ...

Learn how to achieve a sleek animation similar to the famous "Ken Burns effect" by utilizing the CSS property "transform" instead of "object-position". Check out the demo to see it in action!

I am currently exploring how to create an animation similar to the "Ken Burns" effect using CSS transform properties. While I have been using object-position to animate, I am facing challenges with the fluidity of the movement. I am seeking help to achiev ...

The functionality of React-router-dom protected routes seems to be malfunctioning

Understanding Protected Routes in React.js: While looking at the implementation of protected routes, you may notice that 'false' is being directly used in the if statement. However, even with this condition, the page is still accessible. Why doe ...

Different perspectives displayed simultaneously on a single page, achieved without the need for routes

On my page, users have the ability to sort items using various filters. When the filter is set to Newest, the items are simply listed by name. But when the filter is set to By collection, the items within a specific collection are displayed under that col ...