Search code examples
angularangular6systemjs

How do I implement systemjs in Angular 6+?


I'm trying to learn how to make plugins work in Angular, however after adding systemjs I get the following error:

Uncaught ReferenceError: SystemJS is not defined

I implemented systemjs like this:

import { System } from 'systemjs';
declare const SystemJS: System;

import * as angularCore from '@angular/core';
import * as angularCommon from '@angular/common';
import * as angularCommonHttp from '@angular/common/http';
import * as angularForms from '@angular/forms';
import * as angularAnimations from '@angular/animations';
import * as angularPlatformBrowser from '@angular/platform-browser';
import * as angularPlatformBrowserDynamic from '@angular/platform-browser-dynamic';

//error thrown here
SystemJS.set('@angular/core', SystemJS.newModule(angularCore));
SystemJS.set('@angular/common', SystemJS.newModule(angularCommon));
SystemJS.set('@angular/common/http', SystemJS.newModule(angularCommonHttp));
SystemJS.set('@angular/forms', SystemJS.newModule(angularForms));
SystemJS.set('@angular/animations', SystemJS.newModule(angularAnimations));
SystemJS.set('@angular/platform-browser', SystemJS.newModule(angularPlatformBrowser));
SystemJS.set('@angular/platform-browser-dynamic', SystemJS.newModule(angularPlatformBrowserDynamic));

SystemJS.config({ meta: { '*': { authorization: true } } });

What am I missing?

My code where I use systemjs: https://github.com/FrisoDenijs/angular-pluggable-architecture/blob/master/dashboard/src/app/dashboard/dashboard/dashboard.component.ts

My commit with attempted fixes: https://github.com/FrisoDenijs/pluggable-angular-example/commit/4472560da17b69c13809be931f6966d9254d10d1

The repo I use as example: https://github.com/paucls/angular-pluggable-architecture


Solution

    1. Install SystemJS through your package.json (maybe you need to install an older version for your needs).

    2. Add the path to the SystemJS Javascript File to your scripts inside angular.json. That way it is loaded into the global space:

    "scripts": [
      "node_modules/systemjs/dist/system.min.js"
    ]
    
    1. Declare and use it inside your file.
    ...
    declare const SystemJS: System;
    ...
    SystemJS.set('@angular/core', SystemJS.newModule(angularCore));
    

    Step 2 is what you are missing (I guess) and also why it works in the repo you linked; it is done the same way: https://github.com/paucls/angular-pluggable-architecture/blob/master/dashboard/.angular-cli.json

    What your code is doing is not actually importing the SystemJS module itself, it's only importing the type declaration, which is stripped out at runtime. That's why you need to add SystemJS to the scripts-section