Typescript modules and systemjs. Instantiate class

2020-03-08 00:18发布

问题:

I am transpiling a typescript module to javascript with the system module option. I am executing this in a browser.

I am able to consume this module when the code to initialize the module class generated by typescript is also loaded using systemjs system.import.

How can i make the class which is part of a module available from javascript code not loaded through systemjs? E.g. embeded javascript in the page?

回答1:

You can use SystemJS to import the module in Javascript.

Assuming you have a module named app.ts that exports a variable named value.

app.ts:

export let value = 'ABCASF';

In a script tag you can write:

System.import('app.js').then(function(appModule) {
  console.log(appModule.value);
}, console.error.bind(console));

Keep in mind that the module name you have to give to System.import might vary according to your setup.

TypeScript classes get transpiled to ES5 functions so you can make use of them in javascript this way.

example.ts:

export class Example {
  constructor(public someValue: string, private someOtherValue: number) {

  }

  public method() {
    return this.someOtherValue;
  }
}

And in the script tag this way:

  System.import('example.js').then(function(example) {
    // Example class is a function on the module 
    // use new to make a new instance
    var value = new example.Example('a', 5);

    // work as usual 
    console.log(value.method());

  }, console.error.bind(console));