如果您不使用模块系统加载文件,并且不将代码放在模块/命名空间中,则不需要导出。
例如,这应该可以正常工作:
class MyClass {
private x: number;
constructor(x: number) {
this.x = x;
}
getX(): number {
return this.x;
}
doit(y: number): number {
return this.x * y;
}
}
function echo(value: any): any {
return value;
}
(样本.ts)
<html>
<head>
<script src="example.js"></script>
<script>
var a1 = new MyClass(10),
a2 = new MyClass(43);
console.log(echo("hey there!"));
console.log(a1.doit(a2.getX()));
</script>
</head>
<body></body>
</html>
但是,使用export
应该没问题,因为它不应该出现在编译的 js 中(只要确保不要使用-m
或--module
在编译器选项中)。
例如,这个:
module MyModule {
export class MyClass {
private x: number;
constructor(x: number) {
this.x = x;
}
getX(): number {
return this.x;
}
doit(y: number): number {
return this.x * y;
}
}
export function echo(value: any): any {
return value;
}
}
编译成这样:
var MyModule;
(function (MyModule) {
var MyClass = (function () {
function MyClass(x) {
this.x = x;
}
MyClass.prototype.getX = function () {
return this.x;
};
MyClass.prototype.doit = function (y) {
return this.x * y;
};
return MyClass;
}());
MyModule.MyClass = MyClass;
function echo(value) {
return value;
}
MyModule.echo = echo;
})(MyModule || (MyModule = {}));
(操场上的代码)
而且你会注意到export
编译的js中没有。
然后你只需:
<html>
<head>
<script src="example.js"></script>
<script>
var a1 = new MyModule.MyClass(10),
a2 = new MyModule.MyClass(43);
console.log(MyModule.echo("hey there!"));
console.log(a1.doit(a2.getX()));
</script>
</head>
<body></body>
</html>