Babel preset for TypeScript `const` enums
npm install babel-preset-const-enum> Babel preset for TypeScript const enums
Using npm:
``sh`
npm install --save-dev babel-preset-const-enum
or using yarn:
`sh`
yarn add babel-preset-const-enum --dev
This preset runs
babel-plugin-const-enum
only on files with extensions .ts or .tsx. This prevents SyntaxErrors frombabel-plugin-const-enum
happening when mistakenly running on non-TypeScript.js
files such as flow, which uses a extension.
A babel preset is required because plugins don't have access to the file
extension of the file the plugin may run on.
You are most likely using
@babel/preset-typescript
as along with this preset. Make sure that babel-preset-const-enum comes after@babel/preset-typescript in the preset array so thatbabel-preset-const-enum runs first.const enum
This preset needs to run first to transform the s into code that@babel/preset-typescript allows.
.babelrc
`json`
{
"presets": ["@babel/typescript", "const-enum"]
}
boolean, defaults to false.
Indicates that every file extension should be parsed.
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`
{
"presets": ["const-enum"]
}
Or Explicitly:
.babelrc
`json`
{
"presets": [
[
"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``
{
"presets": [
[
"const-enum",
{
"transform": "constObject"
}
]
]
}