Angular 7 ERROR ReferenceError: SystemJS is not defined

Angular 7 ERROR ReferenceError: SystemJS is not defined

我正在使用 systemjs 创建一个 angular 7 项目以动态加载模块。

当我尝试使用它时,出现以下错误:

 ERROR ReferenceError: SystemJS is not defined

我的 package.json 包含 systemjs: 2.1.1

我在 angular.json

中添加了部分脚本的 systemjs 路径
"./node_modules/systemjs/dist/system.js"

我声明 SystemJs 在我的服务中使用它:

declare const SystemJS;

我正在尝试在这个函数中这样使用:

loadModuleSystemJS(moduleInfo: ModuleData): Promise<any> {
    const url = this.source + moduleInfo.location;
    SystemJS.set('@angular/core', SystemJS.newModule(AngularCore));
    SystemJS.set('@angular/common', SystemJS.newModule(AngularCommon));
    SystemJS.set('@angular/router', SystemJS.newModule(AngularRouter));
    SystemJS.set('@angular/platform-browser/animations', SystemJS.newModule(BrowserAnimations));

    // now, import the new module
    return SystemJS.import(`${url}`).then((module) => {
      return this.compiler.compileModuleAndAllComponentsAsync(module[`${moduleInfo.moduleName}`]).then(compiled => {
        return module;
      });
    });
  }

也许我错过了什么,

你能帮帮我吗?

自 Angular 6 起,您必须提供来自 node_modules 的绝对路径。像这样:

{
  ...
  "projects": {
    "demo": {
      ...,
      "architect": {
        "build": {
          ...
          "options": {
            ...
            "scripts": [ "node_modules/systemjs/dist/system.js" ]
          },
          ...
        },
        ...
      }
    }
  },
  ...
}

这里有一个 Sample StackBlitz 供您参考。

请注意,我在记录 typeof SystemJS.set

app.component.ts 中使用了它

请务必使用此版本: https://github.com/systemjs/systemjs/releases/tag/0.21.5 据我所知,2.1.1 与过去的 api 不兼容。顺便说一句,但是,在上面答案的示例中,使用了版本“0.21.4 Dev”。

我在相应的 github 问题中回答了这个问题:https://github.com/systemjs/systemjs/issues/1940#issuecomment-490280011

tldr:systemjs@<2 有一个 window.SystemJS 全局变量,但 systemjs@>=2 没有。使用 window.SystemSystem 而不是 SystemJS。您还需要 follow the instructions in the systemjs readme 让您的 webpack 配置不干扰 System.import() 调用。