Search code examples
typescriptsystemjs

Using System.js in HTML file to invoke a typescript class method


I'm trying out Typescript and System.js. The Typescript compiler is running with the -w flag.

I'd like to invoke a method when the page loads, I can import play, but not access it with 'then':

HTML file:

<!doctype html>
<head>
  <script src='//cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.41/system.js'> </script>
  <script>
    System.import('./play.js').then(function(play) { 
      play.start(); 
    });
  }
  </script>
</head>
<body>
</body>

play.ts file:

export class Play {
  start() {
    alert('hello...');
  }
}

I get the error: Uncaught (in promise) TypeError: play.start is not a function. Any ideas?


Solution

  • System.import result is a module, not a class. Returned module has references to all things exported from it, so you can get Play class as play.Play, but to call start() method you have to create an object of that class first, using new. Something like this should work:

      <script>
        System.import('./play.js').then(function(play) { 
          var player = new play.Play();
          player.start(); 
        });
      }
      </script>