我一直在玩 typescript,试图将它集成到我们现有的 javascript/requirejs 项目中。
作为设置,我有 Visual Studio 2013 with Typescript for vs v 0.9.1.1。 Typescript 被配置为(在 Visual Studio 中)以 amd 格式编译模块。
这是我发现的适合我的方法(当然可能有更好的方法)
-
使用 amd-dependency 告诉 typescript 编译器将所需的模块添加到必须加载的组件列表中
- 在要导出的类的构造函数中,使用 requirejs 的 require 函数来实际获取导入的模块(此时这是同步的,因为上一步)。为此,您必须参考 require.d.ts
作为旁注,但由于在我看来它是打字稿必不可少的,并且因为它让我有点头疼,所以在示例中我展示了两种导出使用接口的类的方法。接口的问题是它们用于类型检查,但它们没有产生真正的输出(生成的 .js 文件是空的),它会导致类型为“私有类的导出”的问题
我找到了两种导出实现接口的类的方法:
- 只需向接口添加一个 amd 依赖项(就像在 Logger.ts 文件中一样)
并导出一个包含该类的新实例的类型化变量
导出的类可以直接消费(即myClass.log('hello'));
- 不要将 amd- 依赖添加到接口中(就像在 Import.ts 文件中一样)
并导出一个函数(即 Instantiate()),该函数返回一个类型为 any 的变量,其中包含该类的新实例
导出的类可以通过这个函数来消费(即 myClass.instantiate().log('hello'))
似乎第一个选项更好:您不需要调用实例化函数,而且您可以使用一个类型化的类。缺点是 [empty] 接口 javascript 文件确实会传送到浏览器(但无论如何它都会缓存在那里,也许你甚至正在使用缩小,在这种情况下这根本不重要)。
在接下来的代码块中,有 2 个 typescript 模块加载了 requires (amd):Logger 和 Import。
ILogger.ts 文件
interface ILogger {
log(what: string): void;
}
Logger.ts 文件
///<reference path="./ILogger.ts"/>
//this dependency required, otherwise compiler complaints of private type being exported
///<amd-dependency path="./ILogger"/>
class Logger implements ILogger {
formatOutput = function (text) {
return new Date() + '.' + new Date().getMilliseconds() + ': ' + text;
};
log = function (what) {
try {
window.console.log(this.formatOutput(what));
} catch (e) {
;
}
};
}
//this approach requires the amd-dependency above for the interafce
var exportLogger: ILogger = new Logger();
export = exportLogger;
在另一个 ts 文件中使用 Logger.ts(Import.ts)
///<reference path="../../../ext/definitions/require.d.ts"/>
///<amd-dependency path="Shared/Logger"/>
///<amd-dependency path="./IImport"/>
class _Import implements IImport{
ko: any;
loggerClass: ILogger;
constructor() {
this.ko = require('knockout');//require coming from require.d.ts (in external_references.ts)
this.loggerClass = require('Shared/Logger');
}
init(vm: any) {
this.loggerClass.log('UMF import instantiated...');
}
}
////Alternative Approach:
////this approach does not require adding ///<amd-dependency path="./IImport"/>
////this can be consumed as <imported_module_name>.instantiate().init();
//export function instantiate() {
// var r : any = new _Import();// :any required to get around the private type export error
// return r;
//}
//this module can be consumed as <imported_module_name>.init();
var exported: IImport = new _Import();
export = exported;
IImport.ts 文件
interface IImport {
init(vm: any): void;
}
要直接从 javascript 使用 Import 模块,请使用类似的东西(对不起,我没有尝试过这个,但它应该可以工作)
define (['Import'], function (import)
{
//approach 1
import.init();
////approach 2
//import.instantiate().init();
});