导出的枚举不会用 tsickle/closure 编译

exported enums won't compile with tsickle/closure

我正在尝试使用新的 tsickle/closure 链编译一个 angular 项目。但是,它似乎必须在所有枚举上都出现以下错误:

src/path/to/YourEnumType.ts:1: ERROR - Exports must be a statement at the top-level of a module

我的代码是这样的:

export enum YourEnumType {
    None = 0,
    OneThing = 1,
    OtherThing = 2
}

我该如何处理这个问题?

Typescript 编译器从导出的枚举中生成:

var YourEnumType;
(function (YourEnumType) {
    YourEnumType[YourEnumType["None"] = 0] = "None";
    YourEnumType[YourEnumType["OneThing"] = 1] = "OneThing";
    YourEnumType[YourEnumType["OtherThing"] = 2] = "OtherThing";
})(YourEnumType = exports.YourEnumType || (exports.YourEnumType = {}));

正如我们所见,是的,这个生成的 Javascript 使用函数内部的 exports

深入研究打字稿编译器,尝试使用其生成的输出格式等,我发现没有办法解决这个问题。尽管如此,如果按照我们在 this 答案中看到的那样进行编译,此 Typescript 代码会好得多:

var YourEnumType = Object.freeze({"None":1, "OneThing":2, "OtherThing":3, ...});

不幸的是,打字稿不会这样做。

类似地挖掘 google 闭包编译器 show,如果不修改 google 闭包源代码,就无法解决这个问题。

因此,考虑到这个,以及整个打字稿世界中枚举的其他主要问题,我认为唯一的出路是避免使用打字稿枚举。

如果您将 export 拉到单独的一行,那么它就可以工作。即:

enum YourEnumType {
    None = 0,
    OneThing = 1,
    OtherThing = 2
}
export {YourEnumType};

似乎是 tsickle 中的一个错误。

更新:此外,由于您使用了缩小器,因此您应该考虑使用 const 枚举,它发出的代码更少,并且在与闭包一起使用时具有更少的极端情况:

const enum YourEnumType {
    None = 0,
    OneThing = 1,
    OtherThing = 2
}
export {YourEnumType};