混合 TypeScript 和 Meteor - 跨多个文件的类 [英] Mixing TypeScript and Meteor - Classes across multiple files
问题描述
对于任何不正确的术语,我们深表歉意.对于那些不熟悉 Meteor 的人,它具有明确定义的脚本加载顺序.我正在尝试创建许多包含类的 *.ts
文件,就像您在 C# 的 *.cs
文件中看到的那样.我想在彼此之间引用这些 *.ts
文件,并最终从 main.ts
中引用.
Apologies for any incorrect terminology. For those not familiar with Meteor, it has a well-defined order of script loading. I'm trying to create many *.ts
files containing a class, like you'd see in C#'s *.cs
files. I want to reference these *.ts
files between each other, and ultimately from a main.ts
.
编译 Car.ts:
class Car {
constructor(public age: number) { }
}
生成 Car.js:
var Car = (function () {
function Car(age) {
this.age = age;
}
return Car;
})();
使用 Meteor,我想要以下输出:
With Meteor, I want the following output:
Car = (function () {
function Car(age) {
this.age = age;
}
return Car;
})();
这样 Car 就可以从另一个文件 main.ts 中引用:
So that Car can be referenced from another file, main.ts:
/// <reference path="car.ts"/>
Meteor.startup(function () {
console.log(Car); // Hopefully prints [Function: Car]
var a: Car = null; // Compiles
});
我可以通过修改 Car.ts 来接近:
I can get close by modifying Car.ts:
declare var Car;
class Car_ {
constructor(public age: number) {}
}
Car = Car_;
但这会产生一个混乱的输出:
But this produces a kludgy output:
var Car_ = (function () {
function Car_(age) {
this.age = age;
}
return Car_;
})();
Car = Car_;
并且需要一个笨拙的 main.ts:
And necessitates a kludgy main.ts:
/// <reference path="car.ts"/>
Meteor.startup(function () {
console.log(Car); // Prints [Function: Car_]
var a: Car_ = new Car(); // Yuck!
});
有什么建议吗?我可能把它看得太像 C# 应用程序了.
Any advice? I might be treating this like too much like a C# application.
推荐答案
一个解决方案涉及设置全局对象:
One solution involves setting the global object:
class Car {
constructor(public age: number) {}
}
global.Car = Car;
编译为:
var Car = (function () {
function Car(age) {
this.age = age;
}
return Car;
})();
global.Car = Car;
我对这个解决方案不太满意,因为 global
是 nodejs 特定的东西,不能在使用 window
的浏览器中工作.结果证明 this
在浏览器和服务器上都有效:
I'm not very happy with this solution because global
is a nodejs-specific thing and won't work in a browser, which uses window
. It turns out this
works both in-browser and on server:
class Car {
constructor(public age: number) {}
}
this.Car = Car;
编译为:
var Car = (function () {
function Car(age) {
this.age = age;
}
return Car;
})();
this.Car = Car;
不优雅,但更好...
这篇关于混合 TypeScript 和 Meteor - 跨多个文件的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!