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

Is there an issue with loading CSS and JavaScript in mobile view on a website built with CodeIgniter?

My experience with codeigniter has been great so far, but I encountered an issue when trying to view my work on different devices. Here is the problem: Web: Broswer View | Browser (Responsive Design View) Mobile: Screenshot 1 | Screenshot 2 _htaccess: ...

Having trouble with Simplemodal showing link content in the modal window

Having trouble getting the modal window to display content from another link? I'm pretty sure I've connected them correctly using the right classes. This is the basic JavaScript provided by . jQuery(function ($) { // Load dialog on page load //$ ...

Launching the ngx Modal following an Angular HTTP request

Trying to trigger the opening of a modal window from an Angular application after making an HTTP call can be tricky. Below is the content of app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/pla ...

Vuetify does not support Tailwind CSS styles

Initially, I integrated Tailwind CSS into my project. However, during the development process, I decided to give Vuetify a try. After adding Vuetify along with vuetify-loader, I encountered an issue where Vuetify functionality was working fine but the styl ...

Creating an Observable from static data in Angular that resembles an HTTP request

I have a service with the following method: export class TestModelService { public testModel: TestModel; constructor( @Inject(Http) public http: Http) { } public fetchModel(uuid: string = undefined): Observable<string> { i ...

Leveraging AJAX for transmitting form information to a php script without relying on jQuery

I want to explore AJAX by implementing a basic form data submission to a php script and database. For educational purposes, I've reached a standstill after hitting the "Create Profile" button with no action. Could someone spot any syntax or structural ...

button click event blocked due to unforeseen circumstances

Recently, I've been attempting to change the CSS properties of a div by triggering a click event. However, no matter what I do, it doesn't seem to be working and it's starting to frustrate me. Can anyone shed some light on why this might be ...

Is your $http request causing an XML parsing issue?

I'm attempting to utilize the $HTTP method from angularJS to access my restful web service. On entering my web service URL in the browser, I receive a result of APPLICATION/JSON type. {"id":20418,"content":"Hello, World!"} The URL for my web servic ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

Is there a way to convert a button into clickable text that performs the same function as the original button?

Seeking a solution to transform a button into clickable text with the same functionality. Explored resources like Google, StackOverFlow, and Youtube for answers. This is the current code snippet representing the button: <button onclick="mainApp.l ...

Securing the Firebase Admin SDK JSON file within a NextJS project for optimal protection

I'm currently working on a NextJS app that uses the Firebase Admin SDK, but I'm unsure of where to securely store the JSON file containing all the keys. It seems that integrating secret keys in JSON files with an .env.local file is not possible. ...

Error arises on Github when submitting a pull request due to a conflicted package

When facing conflicts in the package.json file while submitting a pull request, what is the best approach to resolve them? I usually attempt using git pull origin, but it tends to generate numerous merge commits. ...

Leveraging a variable in Python for XPATH in Selenium

I have a variable that looks like this: client_Id = driver.execute_script("return getCurrentClientId()") I want to update the XPATH by replacing the last value (after clientid=2227885) with the client_Id variable. So: prog_note = wait.until(EC.p ...

remain on the multi drop down page for a specified duration

I have created a dropdown menu with a second level drop-down page that is a form. Now, I want the second level drop-down page to stay open longer, so I have used the following JavaScript code: <script> var timer; $(".parent").on("mouseover", functio ...

Enhancing a validation form with the 'onblur' event handler

Exploring the realm of JavaScript, I find myself intrigued by the concept of creating a validation form that activates upon clicking out of the input field. Implementing various techniques to integrate this feature into an existing form has been both chall ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

What could be causing ng-repeat to malfunction?

My ng-repeat is not working with the table - only the header part is being displayed in the output. I have checked my binding and it seems to be correct, but I know I am missing something. Can someone please help me figure out what I am doing wrong? JAVA ...

ASP.NET DIV is experiencing issues with Jquery functionality, causing it to flicker and remain fixed in place

As a beginner in JQuery, I am facing an issue with my code in asp.net. Whenever I click on linkbuttons, the behavior is not as expected. The div flickers and does not change its direction. My goal is to move the DIV left or right by 200px, but no matter wh ...

Error TS2322: The specified type 'Element' cannot be assigned to the type 'boolean'

I'm just beginning to explore TypeScript and I ran into an issue while trying to type my constant dialogFuncMap. I received an error (listed in the comments below). Why am I getting this error if the type of state is boolean? And how can I resolve it ...

Ensure that you select just one checkbox in Vue 3

Trying to implement a functionality in Vue 3 where only one checkbox can be selected in a list of checkboxes. The checkbox input is located within the child component, and I need to monitor changes within the child component. If a checkbox is selected, the ...