SystemJS not initialising my app

I have built an app in Typescript using modules. The typescript compiler bundles all modules together into one main.js file. I use SystemJS to load the modules as follows:

<script src="js/system.js"></script>  
<script>
      System.import('js/main.js').then(function(App) {
          let a = new App();
       });
</script>

The loading works, but there is no app returned. I’m not sure how to make my code return the App so that I can make an instance! Currently main.js looks like this:

System.register("message", [], function (exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var Message;
    return {
        setters: [],
        execute: function () {
            Message = class Message {
                constructor(str) {
                    console.log(str);
                }
            };
            exports_1("Message", Message);
        }
    };
});
System.register("app", ["message"], function (exports_2, context_2) {
    "use strict";
    var __moduleName = context_2 && context_2.id;
    var message_1, App;
    return {
        setters: [
            function (message_1_1) {
                message_1 = message_1_1;
            }
        ],
        execute: function () {
            App = class App {
                constructor() {
                    console.log("I am an app");
                    let m = new message_1.Message("testing modules");
                }
            };
            exports_2("App", App);
        }
    };
});

What do I need to add to make main.js return the app?
Incidentally, the SystemJS website says that I need to use “system-production.js” since my modules are already bundled. But that doesn’t work!

Hi @BarnabyJones,

As your main.js file is a bundle, rather than an ordinary module, you have to make a couple of changes to your code to get it to run:

<script src="https://cdn.bootcss.com/systemjs/0.20.13/system.js"></script>
<script src="js/main.js"></script>
<script>
  System.import('app').then(function(module) {
    let a = new module.App();
    // ...
  });
</script>
  1. On the 2nd line, I’ve added a script tag to load the bundle file
  2. As you using a bundle, you need to replace the filename in the import() call with the name of the module (in this case, just ‘app’)
  3. It seems that the return value of import() resolves to an object with the value that your module exports attached as a property. I’ve just called the return value module, so the App constructor can be referenced as module.App
3 Likes

Thanks, this works! I didn’t realise I had to load the bundle as a regular file instead of using import!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.