Typescript modules and systemjs. Instantiate class from inline script

萝らか妹 提交于 2019-11-30 21:32:31

问题


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));


来源:https://stackoverflow.com/questions/36313093/typescript-modules-and-systemjs-instantiate-class-from-inline-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!