Utilizing Angular 14 to dynamically import modules during execution

I'm experimenting with dynamically importing modules in Angular 14 where the module paths are determined at runtime, but encountering the following error:

Error: Cannot find module 'src/app/plugin1/plugin1.module'

Github repro

Manually specifying the import path works fine:

let module = await import("src/app/plugin1/plugin1.module").then(m => (m as any)[Object.keys(m)[0]]);

However, dynamic values pose a problem:

@Input() path: string;
...
let module = await import(this.path).then(m => (m as any)[Object.keys(m)[0]]);

The plugin module has been included in tsconfig, tsconfig.app.json:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],
    "module": "esnext"
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts",
    "src/**/*.ts",
    "src/app/plugin1/plugin1.module"
  ],
  "exclude": [
    "src/**/*.spec.ts",
    "src/test.ts",
    "src/environments/*"
  ]
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {...}

 [...]
 <hr />
<h1>Update</h1>
<p>In an attempt to make it work, I created this solution. However, since the strings must be explicitly typed out, they cannot be loaded through a loop. The entries are not added to any tsconfig files.</p>
<p>Any alternative solutions would be greatly appreciated.</p>
<pre><code>@Injectable({ providedIn: "root" })
export class ModuleLoaderService {

 [...]

import { Component [...] from "@angular/core";
import { ModuleLoaderService } from "../services/module-loader.service";

@Component({...})
export class HeroLoaderTempComponent {...}

Answer №1

While working on my Angular project locally, I encountered a similar issue. Give this a shot:

  1. Type this in your edge browser:
    edge://flags/#allow-insecure-localhost
  2. Activate it.

I'm not entirely sure why, but after doing this, my files loaded without any errors in the console. Hopefully, this tip proves helpful for your development as well.

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

Tips for expanding the functionality of the d3-selection module using TypeScript

I am currently working on a project that involves TypeScript and d3. I have already installed 'd3' and '@types/d3', and my use of d3 looks like this: import * as d3 from 'd3'; const x = d3.scaleLinear ... Everything was goin ...

Tips for transforming Http into HttpClient in Angular 5 (or higher than 4.3)

I have successfully implemented code using Http and now I am looking to upgrade it to use the latest HttpClient. So far, I have taken the following steps: In App.module.ts: imported { HttpClientModule } from "@angular/common/http"; Added HttpClientModul ...

Exploring the possibilities of combining colspan and ngFor in an Angular material 6 table

Angular Material is being utilized for table rendering in my project. https://i.sstatic.net/uwYG2.png Code: <ng-container matColumnDef="type"> <th mat-header-cell *matHeaderCellDef> Workout type </th> <td mat-cell *matCellDef= ...

Updating a unique field with the same value causes a failure in the TypeORM update process

I am working with a service model in TypeORM, where I have a field called service_name that must be unique. However, when I attempt to update the table with the same value for service_name, it triggers a unique constraint violation error. I'm puzzled ...

Troubleshooting TypeScript window augmentation not functioning in individual modules

I would like to extend the window object with a new property. This can be achieved by adding the following code: // global.d.ts import { IConfig } from './src/models'; export {}; declare global { interface Window { _env: IConfig; ...

Using JavaScript, align an image's coordinates with a specific coordinate within its parent container

I am looking to change the position of my relative image dynamically so that it aligns with a fixed pointer's coordinate that is absolute to it ...

Properly transform a set of conditions from If statements to R.cond

I have a series of If statements that I need to convert to Ramda's conditional function. However, when I try to do so, I encounter an error saying that "Never is not assigned to Element." It seems like I am making a mistake somewhere: if (cond1) ret ...

Guide on accessing the REST API of a Spring Boot Application using an Angular 8 client program, along with tackling CORS problem

I have developed a Spring Boot Application where I am looking to integrate a Web API into my Angular 8 client-side architecture. When trying to access the server-side URL directly from the Angular application in modern browsers, I am encountering CORS iss ...

Struggling to remove CLI from my Mac operating system

I seem to be stuck on CLI version 8.3.21 while using MacOS Big Sur. I'm not currently in a project folder and have deleted all node_modules directories from my existing Angular projects. To try and remove it, I've attempted the following commands ...

Tips for Concealing and Bypassing Array String Elements in Angular 4/6 with Typescript or Html

Currently, I am working on a feature where clicking on a specific item in the list of branches should remove or hide that particular item and display it in another section as the selected branch. The swapping functionality is working fine, but the item sti ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

retrieve a nested object's property using a dynamic string

Here is the object model I am working with: export class FrcCapacity { constructor( public id?: number, public frcId?: number, public capGroupId?: number, public capGroup?: CapGroup, public salesProductId?: number, public p1?: num ...

Modifying the text of a material UI button depending on a particular condition

I have a component that uses the Material UI button, and I need to change the text of the button based on a condition. If the order amount is 0, I want it to display "cancel", otherwise, it should show "refund". Can someone guide me on how to achieve thi ...

Error in NextJS Middleware Server: Invalid attempt to export a nullable value for "TextDecoderStream"

I've recently created a straightforward Next.js application using bun (version 1.0.4, bun create next-app), incorporating app routing with Next.js version 13.5.4 and a designated source directory. My goal was to implement a middleware that restricts a ...

Determining the type of an overloaded method within a generic function

I am currently working on developing a versatile function that can subscribe to an event emitter. The function subscribe is designed to take 3 arguments: event name, event handler, and the event emitter to connect to. I am looking for ways to ensure accur ...

Unexpected Failure in Angular 7 Compilation

My angular app was functioning perfectly, but suddenly it stopped compiling. I received the following message: ng build --prod 10% building modules 3/6 modules 3 active ...ogress\kendo-theme-default\dist\all.cssBrowserslist: caniuse-lite i ...

Sorry, Computed styles are not available in IE 11 Edge DevTools

Currently facing an issue with a component element rendering differently on IE11, however the DevTools for both IE and Edge aren't showing any CSS in the Styles or Computed tab. What is the correct way to debug this situation? Comparison from left to ...

What is the process for converting a string into JSON keys and subkeys?

In my Angular 2 project, I have implemented a custom translator to translate text into different languages. Currently, the translator uses a string as a key to retrieve the translations, like this: let key = 'hello world' export const LANG_EN_T ...

Async validation for Angular 2 to check if the username or email is already

I am looking to incorporate asynchronous validation using the Github API. Your assistance in this matter would be greatly appreciated. export class UsernameValidator { static usernameTaken(control: FormControl): Promise<Validatio ...

Can one choose an ancestral namespace in TypeScript?

I am encountering an issue with generating TypeScript code that includes nested namespaces. The specific problem arises when there is a namespace inside of another namespace, causing the inner one to overshadow the outer one. namespace A { export t ...