各位,我正在尝试做一些我认为应该很简单的事情,但我一定做错了什么。我试图在使用 Typescript 的 Meteor 应用程序中有一个清晰的结构。
这是我的要求:
- 所有接口(interface)在客户端和服务器端均可用
- 某些类实现仅在服务器上可用
- 我不想依赖文件加载顺序来让我的应用程序正常工作
- 我需要自己的模块,以免与全局对象(例如 Position 类)发生冲突
- 我需要一个用于服务器的整体包含文件,一个用于客户端和服务器,一个用于客户端(不希望在我的文件之上有 10 个包含文件)
我现在的设置是这样的
- 服务器
- 服务器-book.ts
- 客户
- 已共享
- collection.ts
- 定义
- 服务器
- include.d.ts(包含此文件夹中的所有 .d.ts 文件)
- server-book.d.ts(书籍的服务器特定实现)
- 客户端
- 已共享
- include.d.ts(此处包含所有 .d.ts 文件)
- book.d.ts(图书接口(interface)定义)
- collections.d.ts
- 服务器
在我的每个 .d.ts 文件中
module MyModule { interface Bla {} };
在每个定义类的 .ts 文件中,我有:
module MyModule { export class MyBla implements Bla {}; }
为类生成的所有 .d.ts 文件均由 tsc -d 生成。
没有通过///
现在,当我运行此命令时,我收到 MyModule 未定义的错误:
/// <reference path="shared/include.d.ts"/> /// <reference path="server/include.d.ts"/> Meteor.startup(() => { var temp = new MyModule.ServerBook(); });
错误就发生在 MyModule 上。
我做错了什么?这里正确的设置应该是什么?
谢谢!
最佳答案
我已经在我的 blog 上处理了这个问题。我决定使用邪恶的 eval
命令,因为它为我提供了最简单的使用模块的可能性,直到出现更复杂的东西。
文件 /lib/foo.ts
位于子目录中,因为它必须在 Bar 之前加载。
eval('var Hugo = (this.Hugo || (this.Hugo = {})'); // this will override the automatically emitted var Hugo and assigns it with globally defined Hugo module
module Hugo {
export class Foo {
foo():string {
return 'foo'
}
}
}
文件/bar.ts
/// <reference path="lib/foo.ts"/>
eval('var Hugo = (this.Hugo || (this.Hugo = {})'); // this will override the automatically emitted var Hugo and assigns it with globally defined Hugo module
module Hugo {
export class Bar extends Foo {
bar () : string {
return 'bar';
}
}
}
文件/test.ts
/// <reference path="lib/foo.ts"/>
/// <reference path="bar.ts"/>
var m = new Hugo.Bar();
console.log(m.bar());
console.log(m.foo());
如上所述here ,对于类来说,解决方案就更简单了:
class ExportedClass {
variable : int;
}
this.ExportedClass = ExportedClass;
关于meteor - 将 Meteor.js 中的模块与 Typescript 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28321467/