【问题标题】:Typescript AMD implementation bad with Javascript / RequireJSJavascript / RequireJS 的 Typescript AMD 实现不好
【发布时间】:2013-04-19 06:26:18
【问题描述】:

如果我有这个 ts 模块:

export function say(){
    console.log("said");
}

我使用 amd 选项编译它,我可以很容易地从 ts 客户端使用它:

import foo = module("tsmodule")
foo.say();

export var x = 123;

但是,如果我有与 ts 模块等效的 javascript:

define(["require", "exports"], function(require, exports) {
    function say() {
        console.log("said");
    }
    exports.say = say;
})

没有办法轻松使用它。最简单的解决方案:

// of course you can use .d.ts for requirejs but that is beside the point
declare var require:any;

// will fail with error module has not been loaded yet for context
// http://requirejs.org/docs/errors.html#notloaded
var useme = require("jsmodule")
useme.say();

export var x = 123;
import foo = module("tsmodule")
foo.say();

由于错误 http://requirejs.org/docs/errors.html#notloaded 而失败。由于“jsmodule”未传递给生成的打字稿中的定义调​​用。

我有两种解决方法

  • 不要使用导入/导出(语言功能丢失)
  • 使用 require([]) (仍然无法导出依赖于 require([]) 调用的内容)

有限制:https://github.com/basarat/typescript-requirejs。还有其他方法吗?如果不能,你可以在这里投票:https://typescript.codeplex.com/workitem/948 :)

【问题讨论】:

    标签: requirejs typescript


    【解决方案1】:

    如果你想加载一个 JavaScript 模块,你总是可以使用(记录不充分的)amd-dependency 标签:

    /// <amd-dependency path="jsmodule" />
    

    这会将jsmodule 放入您定义调用的依赖数组中。

    然后提供一个声明文件,您可以在其中简单地声明

    module useme {
        function say(): void;
    }
    

    【讨论】:

    • 显然是一个未记录的功能,不适用于我的 tsc 版本 0.9.0 alpha。让我卸载/安装到 0.8 版
    • 哎呀,他们在 0.9 中删除了这个?!我正在使用 0.8.1.1。
    • 适用于 0.8.3 。但不是在 0.9.0alpha
    • 很高兴知道。我希望它们在 0.9+ 中包含类似的功能,因为我非常依赖此功能
    • 0.9a 应该缺少一些实用程序位。希望amd-dependency 是其中之一。我希望他们没有永久删除它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2012-04-14
    相关资源
    最近更新 更多