打字稿模块和systemjs。从内联脚本实例化类 [英] Typescript modules and systemjs. Instantiate class from inline script

查看:99
本文介绍了打字稿模块和systemjs。从内联脚本实例化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用系统模块选项将一个打字稿模块转换为javascript。我在浏览器中执行它。



当初始化typescript生成的模块类的代码也使用systemjs system.import加载时,我能够使用此模块。



如何通过systemjs加载javascript代码中可用的模块的一部分?例如。在页面中嵌入了javascript?

解决方案

您可以使用 SystemJS 在Javascript中导入模块。



假设你有一个名为 app.ts 的模块,它导出一个名为 value 的变量。



app.ts:

  export let value ='ABCASF'; 

在脚本标签中你可以写:



< pre class =lang-js prettyprint-override> System.import('app.js')。then(function(appModule){
console.log(appModule.value);
},console.error.bind(console));

请记住,您必须提供的模块名称 System.import 可能会因您的设置而异。



TypeScript类会被转换为ES5函数,因此您可以通过这种方式在javascript中使用它们。



example.ts:

  export class示例{
构造函数(public someValue:string,private someOtherValue:number){

}

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

并且在脚本以这种方式标记:

  System.import('example.js')。then(function (示例){
//示例类是模块上的函数
//使用new来创建新实例
var value = new example.Example('a',5);

//照常工作
console.log(value.method());

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




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?

解决方案

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

这篇关于打字稿模块和systemjs。从内联脚本实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆