You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+99-9Lines changed: 99 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,16 +1,18 @@
1
1
# ts-transformer-optimize-const-enum
2
2
3
-
A typescript transpiler that transform exported const enum into object literal! This is just like the one from [@babel/preset-typescript or @babel/plugin-transform-typescript with optimizeConstEnums: true](https://babeljs.io/docs/en/babel-preset-typescript#optimizeconstenums) but it works for typescript compiler.
3
+
A typescript transpiler that transform exported const enum into object literal.
4
+
5
+
This is just like the one from [@babel/preset-typescript with optimizeConstEnums: true](https://babeljs.io/docs/en/babel-preset-typescript#optimizeconstenums) but it works for typescript compiler.
4
6
5
7
This will transform exported const enum from
6
8
7
9
```ts
8
10
exportconstenumMyEnum {
9
11
A,
10
12
B,
11
-
C
13
+
C,
12
14
D=10,
13
-
D=C*200
15
+
E=C*200
14
16
}
15
17
```
16
18
@@ -23,21 +25,110 @@ export const MyEnum {
23
25
C: 2,
24
26
D: 10,
25
27
E: 400
26
-
}
28
+
}asconst
27
29
```
28
30
29
-
while stripping const in declaration file, to make your code compatible with `--isolatedModules`
31
+
and it also strips `const` in declaration file, to make your code compatible with [`--isolatedModules`](https://www.typescriptlang.org/tsconfig#isolatedModules)
30
32
31
33
```ts
32
-
declareenumMyEnum { ... }
34
+
// my-enum.d.ts
35
+
declareenumMyEnum { A: 0, ... }
33
36
```
34
37
35
38
## Why?
36
-
WIP
39
+
40
+
Const enum can only works in the same file. It works by inlining the exact value into code.
41
+
With [isolateModules](https://www.typescriptlang.org/tsconfig#isolatedModules), you can't use the exported const enum. The solution is to enable [preserveConstEnums](https://www.typescriptlang.org/tsconfig#preserveConstEnums) option to convert const enum to regular enum.
42
+
43
+
However, the regular enum compiles to
44
+
45
+
```js
46
+
exportvar MyEnum;
47
+
(function(MyEnum) {
48
+
MyEnum[MyEnum['A'] =0] ='A';
49
+
MyEnum[MyEnum['B'] =1] ='B';
50
+
MyEnum[MyEnum['C'] =2] ='C';
51
+
MyEnum[MyEnum['D'] =10] ='D';
52
+
MyEnum[MyEnum['E'] =400] ='E';
53
+
})(MyEnum || (MyEnum = {}));
54
+
```
55
+
56
+
which is ugly and waste a lot of bytes. Not only can't you take advantage of enum inlining, but it also wastes a lot of bytes. That's why this transform existed.
37
57
38
58
# Usage
39
59
40
-
WIP
60
+
## ttypescript
61
+
62
+
If you use vanilla TypeScript compiler, you can use this with [ttypescript](https://github.com/cevek/ttypescript) and compile with `ttsc` instead of `tsc`
0 commit comments