Angular 7 ERROR ReferenceError: SystemJS is not defined
Asked Answered
T

3

5

I'm creating an angular 7 project with systemjs to load dynamically a module.

When I try to use it, I have this error:

 ERROR ReferenceError: SystemJS is not defined

My package.json contain systemjs: 2.1.1

I added systemjs path to section scripts in my angular.json

"./node_modules/systemjs/dist/system.js"

I declared SystemJs to use it in my service:

declare const SystemJS;

and I'm trying to using like this, in this function:

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;
      });
    });
  }

Maybe I've missed something,

Can you help me ?

Topgallant answered 15/11, 2018 at 15:40 Comment(1)
I've got the same problem even using [email protected], but only when build in --prod mode, when I use ng serve it works as expected. Could you specify the mode you got error?Kristine
G
5

Be sure to use this release: https://github.com/systemjs/systemjs/releases/tag/0.21.5 2.1.1 is not compatible with past api, as far as I can tell. By the way, in the example from the answer above, however, the version "0.21.4 Dev" is used.

Geniagenial answered 10/12, 2018 at 9:8 Comment(0)
M
4

I answered this in the corresponding github issue: https://github.com/systemjs/systemjs/issues/1940#issuecomment-490280011

tldr: systemjs@<2 had a window.SystemJS global variable, but systemjs@>=2 does not. Use window.System or System instead of SystemJS. You'll also need to follow the instructions in the systemjs readme about getting your webpack config to not mess with the System.import() calls.

Messily answered 7/5, 2019 at 22:41 Comment(0)
S
3

Since Angular 6, you have to provide the absolute path from node_modules. Something like this:

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

Here's a Sample StackBlitz for your ref.

Note that I've used it in app.component.ts where I'm logging the typeof SystemJS.set

Shellfish answered 15/11, 2018 at 16:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.