在 Name 不变的情况下正确地重新导出 Typescript 中的局部变量

Re-export local Variables in Typescript properly with the Name unchanged

为了为我的 clientside module bundle problem 找到一个不太难看的解决方案,我发现我可以告诉 Typescript 从本地范围导出变量作为模块的一部分。但是有些事情很奇怪,我想在下面的小例子中向您展示。

假设我在同一目录中有以下三个文件。

Red.ts

class Red {}

Blue.ts

class Blue {}

colors.ts

/// <reference path="Blue"/>
/// <reference path="Red"/>

export var Red = Red;
export var Blue = Blue;

在构建客户端模块时,我使用 AMD 作为模块格式,从 Typescript 获得以下 Javascript 输出。

输出

var Blue = (function () {
    function Blue() {
    }
    return Blue;
}());
var Red = (function () {
    function Red() {
    }
    return Red;
}());
define("colors", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.Red = exports.Red; // this just assigns undefined
    exports.Blue = exports.Blue; // his just assigns undefined
});

我尝试使用:

export var Red;
export var Blue;

但在那种情况下,Typescript 根本不会为这些语句生成任何代码。

我实际上希望它生成以下导出语句:

exports.Red = Red;
exports.Blue = Blue;

我知道我可以临时重命名变量,例如:

var Red_ = Red;
var Blue_ = Blue;
export Red = Red_;
export Blue = Blue_;

或者也可以使用地图和其他东西在循环中执行此操作,但是执行此操作的正确方法是什么?

问题

因此,为了让问题更简单,请从以下选项中选择一个或多个问题:

  1. 有没有一种好方法可以告诉 Typescript 在不更改名称的情况下正确地重新导出这些变量?
  2. 是否有更好的做法来实现我想要的,从而使我的问题消失?
  3. 这是打字稿错误吗? (在那种情况下,我会提交错误报告。)

更重要的约束条件

我无法自行导出 classes(Red.ts 中的 export class Red ...Blue.ts),然后像 Aluan Haddad 描述的那样在 colors.ts 中重新导出它们 ,因为我这样做不希望任何 class 获得定义语句以保持干净的全局环境。

目的是能够要求结果 (colors.js) 并让一个对象授予对整体某些部分的访问权限。 作为编译 Typescript 后的第二步,我将整个脚本包含在一个函数中,以便所有全局变量都成为局部变量,并且只有 define 语句会定义整个脚本功能的接口。

问题是您混合了全局代码和模块代码。 "reference path" 构造用于使用在其他文件中声明的全局变量。 虽然这在您的案例中似乎是个意外,但通常尽量避免混合使用全局代码和模块代码。

试试下面的方法

red.ts

export class Red {}

blue.ts

export class Blue {}

colors.ts

export {Red} from './red';
export {Blue} from './blue';

详细地说,文件不是模块,除非它们包含 top-level importexport 语句。由于您的 redblue 文件没有导入或导出任何内容,它们只是定义了全局变量。