Jonas
Jonas

Reputation: 5149

SystemJS is not importing

Unable to use Typescript with the SystemJS. This is my test example:


tsconfig.json

{
  "compilerOptions": {
    "module": "System",
    "target": "es2015",
    "outFile": "./lib/mylib.js"
  },

  "include": [
    "./src/mylib.ts"
  ]
}

lib/mylib.ts

export default class MyClass {
    constructor(public readonly msg: string) { }

    public print() {
        console.log(this.msg)
    }
}

test.html

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/6.3.1/system.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/6.3.1/extras/named-register.js"></script>
    <script src="lib/mylib.js"></script>
    <script src="test.js"></script>
</head>
<body>
</body>
</html>

lib/mylib.js

System.register("mylib", [], function (exports_1, context_1) {
    "use strict";
    var MyClass;
    var __moduleName = context_1 && context_1.id;
    return {
        setters: [],
        execute: function () {
            MyClass = class MyClass {
                constructor(msg) {
                    this.msg = msg;
                }
                print() {
                    console.log(this.msg);
                }
            };
            exports_1("default", MyClass);
        }
    };
});

test.js

System.import('mylib').then(() => {
    let mc = new MyClass('My message')
    mc.print()
})

Getting an error: test.js:2 Uncaught (in promise) ReferenceError: MyClass is not defined at test.js:2

I try to use SystemJS as I need to load MyClass locally (without CORS). I would use ES6 modules but module imports are not permitted locally.

Upvotes: 2

Views: 1400

Answers (1)

marpme
marpme

Reputation: 2435

The only problem that I could spot that the browser will try to search for the MyClass on the entire global object to see whether it stores it. But SystemJS loads the modules dynamically and returns them inside the promise, thus you will include it like this:

System.import('mylib').then((importedObject) => {
  const MyClass = importedObject.default
  let mc = new MyClass('My message')
  mc.print()
})

That will simply Return you the importedObject and then you can specify which import you want to use. In this case you want to use the default export as it stores your MyClass.

Upvotes: 2

Related Questions