使用 Angular 14 在运行时动态导入模块

2024-02-26

我试图在 Angular 14 中动态导入模块,其中模块路径是在运行时设置的,但出现以下错误:

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

Github 重现 https://github.com/baltzarmattsson/lazyapprepro

当我手动输入导入路径时它起作用:

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

但不适用于动态值:

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

插件模块包含在 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": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2020",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

我正在努力实现我们之前使用的目标@herodevs/英雄装载机 https://www.npmjs.com/package/@herodevs/hero-loaderfor,它不适用于 ng14。


Update

创造了这个怪物并使其发挥作用。由于必须显式输入字符串,因此无法通过 for 循环加载它们。条目是not添加到任何 tsconfig 文件中。

任何其他解决方案仍然值得赞赏。

@Injectable({ providedIn: "root" })
export class ModuleLoaderService {

    preloadedModulesByPath: { [path: string]: any };
    isModulesPreLoaded = false;

    async preloadLazyModules() {
        let map = {};
        map["path/to/module1.module"] = await import("path/to/module1.module");
        map["path/to/module2.module"] = await import("path/to/module2.module");
        map["path/to/module3.module"] = await import("path/to/module3.module");
        map["path/to/module4.module"] = await import("path/to/module4.module");
        this.preloadedModulesByPath = map;
        this.isModulesPreLoaded = true;
    }
}
import { Component, ComponentRef, createNgModule, Injector, Input, ViewContainerRef } from "@angular/core";
import { ModuleLoaderService } from "../services/module-loader.service";

@Component({
    selector: 'hero-loader',
    template: "",
})
export class HeroLoaderTempComponent {

    // In format path/to/feature.module#FeatureModule
    @Input() moduleName: string;

    _componentRef: ComponentRef<unknown>;

    constructor(
        private _injector: Injector,
        private _viewRef: ViewContainerRef,
        private moduleLoader: ModuleLoaderService
    ) { }

    async ngOnInit() {
        if (!this.moduleName) {
            return;
        }

        let path = this.moduleName.split("#")[0];
        let moduleName = this.moduleName.split("#")[1];
        let module = this.moduleLoader.preloadedModulesByPath[path];
        module = module[Object.keys(module)[0]];

        try {
            let moduleRef = createNgModule(module, this._injector);
            const component = (moduleRef as any)._bootstrapComponents[0];
            this._componentRef = this._viewRef.createComponent(component, { injector: this._injector, ngModuleRef: moduleRef })
        } catch (e) {
            console.error("Err when loading dynamic module: " + moduleName, e);
        }
    }
}


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Angular 14 在运行时动态导入模块 的相关文章

随机推荐

  • Neo4j 使用属性过滤器通过多个关系定向路径

    作为 Cypher 和 Neo4j 的新手 我在为我的用例构建查询时遇到问题 我正在构建一个简单的 ACL 访问控制列表 并正在寻找一条通过权限关系向上层次结构的路径 一张图或许能更好地解释它 Key Users gt Blue Group
  • C# 源生成器应该刷新/删除发出的文件

    我创建了一个源生成器来扩展满足某些条件的 部分 类 为了检查和查看生成的代码 我通过将以下内容添加到我的项目中来启用这些文件的发射
  • 如何使用 Spring Data ElasticSearch 为 POJO 定义 ElasticSearch 索引字段名称

    我正在使用 Spring Data ElasticSearch 来执行 CRUD 操作 默认情况下 当使用 Document 注释的 POJO 写入 ElasticSearch 索引时 索引字段名称与 POJO 的 Java 属性名称相同
  • WPF:如何冻结数据网格中的列标题

    如何将我的列标题冻结在DataGrid in my WPF窗口 以便当我向下滚动时 标题仍然可见 Edit 这是我的XAML
  • Scrapy 将子站点项目与站点项目合并

    我试图从子网站中抓取详细信息并与网站中抓取的详细信息合并 我一直在通过 stackoverflow 以及文档进行研究 但是 我仍然无法让我的代码工作 看来我从子网站提取附加详细信息的功能不起作用 如果有人能看一下我将非常感激 coding
  • 测试元素的类型 python tuple/list

    如何验证列表或元组中所有元素的类型是否相同并且属于某种类型 例如 1 2 3 test for all int True 1 3 a test for all int False all isinstance n int for n in
  • 日期输入的 onchange [重复]

    这个问题在这里已经有答案了 可能的重复 当 的值发生更改时 会触发哪些事件 https stackoverflow com questions 3940258 what events does an input type number fi
  • 从 grails 项目执行甘特脚本

    我已经编写了自己的甘特脚本 它可以在命令行中正常工作 现在我需要从 grails 项目运行这个脚本 如下所示 def outputMessage try GroovyScriptEngine engine new GroovyScriptE
  • 如何使用 TFS REST API 获取迭代剩余天数

    我目前正在使用REST API version 2 0并连接到我的 TFS 实例PowerShell 我可以得到以下信息 迭代ID迭代名称队员团队成员每天的容量 使用下面的示例 GET https instance DefaultColle
  • 在 C# 中扩展枚举

    在java中 我习惯于扩展枚举值或重写方法 如下所示 enum SomeEnum option1 sv public String toString return Some value option2 private String Pass
  • Scala:我可以依赖集合中项目的顺序吗?

    这是一个相当不愉快的意外 scala gt Set 1 2 3 4 5 res18 scala collection immutable Set Int Set 4 5 1 2 3 scala gt Set 1 2 3 4 5 toList
  • Firebase 控制台中出现“您的操作被禁止”问题

    我创建了一个 Android 项目 现在我想将 Firebase 添加到我的 Android 项目中 我在 firebase 控制台上注册我的应用程序 现在 当我尝试将 sha 1 密钥添加到项目中时 出现以下错误 我在谷歌和 stacko
  • Reactjs - 必须返回有效的 React 元素(或 null)

    我有以下简单的代码 var data email email protected cdn cgi l email protection email email protected cdn cgi l email protection var
  • 对特定类的通用约束,为什么? [复制]

    这个问题在这里已经有答案了 我一直在阅读有关利用泛型约束的内容 我发现泛型可以被限制为struct class new Class and Interface 前三个背后的原因非常明显 但我实在无法理解why and when约束到一个类
  • javascript中当数组键包含字符串时删除数组键

    我在 javascript 中有一个数组 如下所示 arr md51234 md55234 我试图通过执行以下操作从中删除一个项目 delete arr md51234 但这似乎不起作用 还有其他方法可以删除这个吗 dystroy 提供了答
  • Java 日期和时间 API 有什么问题? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我经常遇到关于 Java 的负面反馈Date以及其他与日期时间相关的课程 作为一名 NET 开发人员 我无法完全 没有使用过它们 理解它们到底出
  • jQuery.Deferred 异常:$(...).datepicker 不是函数

    提前致谢 我已经搜索并实施了 document ready function ui datepicker datepicker and function if Modernizr inputtypes date input type dat
  • 如何在Netty中使用多个ServerBootstrap对象

    我正在尝试使用 Netty 4 0 24 在一个应用程序 一个主要方法 中创建多个服务器 多个 ServerBootstrap 我看到了这个问题 答案 但它留下了许多未解答的问题 Netty 4 0多端口 每个端口有不同的协议 https
  • 如何在ejb 3.0中实现缓存?

    我有一位客户陷入 EJB 3 0 环境中 没有 Singleton 没有bean管理的并发 考虑到ejb规范禁止线程管理和同步 如何实现缓存 本质上 我想要一个非同步对象缓存来执行一些昂贵的操作 EJB 3 0 规范第 21 1 2 章中规
  • 使用 Angular 14 在运行时动态导入模块

    我试图在 Angular 14 中动态导入模块 其中模块路径是在运行时设置的 但出现以下错误 Error Cannot find module src app plugin1 plugin1 module Github 重现 https g