tsc编译const enum
tsc对于const enum
枚举类型的编译采取的是直接用枚举的常量值进行替换。例如tsc编译如下代码
const enum ETest {
Test = 0,
Test1 = 1
}
let t: ETest = ETest.Test;
结果为
let t = 0 /* ETest.Test */;
从编译结果可以发现const enum声明的枚举消失了,而用到枚举的地方,直接被替换为了常量值
优缺点
这种编译结果,有很明显的优点,那就是大大节省代码的体积,但是也有它的缺点,那就是无法遍历枚举,也无法通过常量值,取枚举的字符串,不过这些缺点用的不是太多。
尽管这种编译结果,与typescript标准是不一致的,但是光是减小代码体积这一优点就值得一用。
EsBuild对const enum的支持
对于才用EsBuild作为编译器的项目来说,早期的EsBuild并不支持const enum的常量替换,不过从去年开始EsBuild做出了一些改变,不过在使用上有一些限制,引用作者原话
Tree shaking for cross-module inlined enum values has been implemented. This feature should now work the way I intend for it to work. Specifically:
- There is no difference between enum and const enum in esbuild
- Accessing an enum value directly means it will be inlined (as long as the value is a number or a string)
- Referencing the enum itself will cause the code for the enum object map to be included in the output
- Cross-module inlining only works when bundling
- You have to use ESM import/export syntax for cross-module inlining to work
作者这段话讲了如何使用
- enum和const enum没有任何不同
- 能直接访问enum的值,也就意味着可以内联(只要值是数或者字符串)
- enum引用自身会导致enum仍然输出
- 跨模块内联只工作在bundle时(即–bundle参数)
- 要使跨模块内联,必须使用ESM import/export(即ES6的import/export)语法
今天试用了一下,已经可以完成const enum的内联替换,当然如果是.d.ts的声明文件尚需做一些更改,才能使用这一功能。
EsBuild是一个非常优秀的编译软件,推荐大家使用!!
引用链接:https://github.com/evanw/esbuild/issues/128