Transform TypeScript `const` enums
npm install babel-plugin-const-enum> Transform TypeScript const enums
Using npm:
``sh`
npm install --save-dev babel-plugin-const-enum
or using yarn:
`sh`
yarn add babel-plugin-const-enum --dev
You are most likely using
@babel/preset-typescript
or
@babel/plugin-transform-typescript
along with this plugin.
If you are using @babel/preset-typescript, then nothing special needs to be
done since
plugins run before presets.
If you are using @babel/plugin-transform-typescript, then make sure thatbabel-plugin-const-enum comes before@babel/plugin-transform-typescript in the plugin array so thatbabel-plugin-const-enum runs first.const enum
This plugin needs to run first to transform the s into code that@babel/plugin-transform-typescript allows.
.babelrc
`json`
{
"plugins": ["const-enum", "@babel/transform-typescript"]
}
Removes the const keyword to use regular enum.const
Can be used in a slower dev build to allow , while prod still uses tsc.
See babel#6476.
`ts
// Before:
const enum MyEnum {
A = 1,
B = A,
C,
D = C,
E = 1,
F,
G = A * E,
H = A B C,
I = A << 20
}
// After:
enum MyEnum {
A = 1,
B = A,
C,
D = C,
E = 1,
F,
G = A * E,
H = A B C,
I = A << 20
}
`
.babelrc`json`
{
"plugins": [
"const-enum"
]
}
Or Explicitly:
.babelrc`json`
{
"plugins": [
[
"const-enum",
{
"transform": "removeConst"
}
]
]
}
Transforms into a const object literal.enum
Can be further compressed using Uglify/Terser to inline access.
See babel#8741.
`ts
// Before:
const enum MyEnum {
A = 1,
B = A,
C,
D = C,
E = 1,
F,
G = A * E,
H = A B C,
I = A << 20
}
// After:
const MyEnum = {
A: 1,
B: 1,
C: 2,
D: 2,
E: 1,
F: 2,
G: 1,
H: 1,
I: 1048576
};
`
.babelrc`json`
{
"plugins": [
[
"const-enum",
{
"transform": "constObject"
}
]
]
}
You may be getting a SyntaxError because you are running this plugin onreact-native
non-TypeScript source. You might have run into this problem in ,
see:
babel-plugin-const-enum#2
babel-plugin-const-enum#3
This seems to be caused by react-native transpilingflow code in node_modules.babel-preset-const-enum
To fix this issue, please usebabel-plugin-const-enum` on TypeScript files.
to only run
If you wish to fix the issue manually, check out the
solution in babel-plugin-const-enum#2.