【问题标题】:Typescript modules and systemjs. Instantiate class from inline script打字稿模块和 systemjs。从内联脚本实例化类
【发布时间】:2016-04-01 01:11:31
【问题描述】:

我正在使用系统模块选项将 typescript 模块转换为 javascript。我正在浏览器中执行此操作。

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

如何使作为模块一部分的类可从未通过 systemjs 加载的 javascript 代码中使用?例如。在页面中嵌入 javascript?

【问题讨论】:

    标签: javascript typescript systemjs


    【解决方案1】:

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

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

    app.ts:

    export let value = 'ABCASF';
    

    在脚本标签中你可以写:

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

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

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

    example.ts:

    export class Example {
      constructor(public someValue: string, private someOtherValue: number) {
    
      }
    
      public method() {
        return this.someOtherValue;
      }
    }
    

    并且在脚本标签中这样:

      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 加载模块。我想从页面内联 javascript 中使用该模块中的一个类。
    • @user3591122 哈哈..那么我的第一个答案就是正确的!我误会了。
    • @user3591122 我再次编辑了答案,这对你有用吗? :)
    • 如果不是,我可以在您专门导出类的地方给出答案。
    • 太棒了,这行得通,我赞成你的回答,尽管直到我的代表是 15 岁时才会显示
    猜你喜欢
    • 2016-05-30
    • 2016-08-19
    • 2018-08-14
    • 2014-07-19
    • 2017-05-05
    • 2021-12-04
    • 2013-08-27
    • 2018-07-12
    • 2018-04-18
    相关资源
    最近更新 更多