babel-preset-const-enum

raw JSON →
1.0.0 verified Sat Apr 25 auth: no javascript

Babel preset for transforming TypeScript const enums. Version 1.0.0. It runs babel-plugin-const-enum only on .ts/.tsx files to prevent syntax errors on non-TypeScript files. Provides two transform options: removeConst (default) reverts const enum to regular enum, while constObject inlines values into a const object literal for minification. Must be placed after @babel/preset-typescript in the preset order to work correctly. Lightweight, focused solution for using const enums with Babel.

error SyntaxError: Unexpected token, expected ";" (1:14) ... while parsing unexpected token
cause babel-preset-const-enum ran before TypeScript preset, causing parsing failure on const enum syntax.
fix
Reorder presets: put '@babel/preset-typescript' first, then 'const-enum'.
error Error: Cannot find module 'babel-preset-const-enum'
cause Package not installed or not in node_modules.
fix
Install: npm install --save-dev babel-preset-const-enum
error ReferenceError: MyEnum is not defined
cause Using transform: 'removeConst' and the enum is used before declaration (hoisting issue).
fix
Use transform: 'constObject' to create a const object that avoids hoisting issues.
gotcha Preset ordering: babel-preset-const-enum must come AFTER @babel/preset-typescript in the presets array.
fix Put 'const-enum' after '@babel/preset-typescript' in the preset order.
gotcha Transform 'removeConst' only removes const keyword, does not inline values. May not achieve full minification.
fix Use transform: 'constObject' if you want inlined values for minification.
deprecated The default transform 'removeConst' may not be optimal for production; consider using 'constObject' to fully leverage Uglify/Terser.
fix Set transform: 'constObject' explicitly for production builds.
npm install babel-preset-const-enum
yarn add babel-preset-const-enum
pnpm add babel-preset-const-enum

Shows how to configure babel-preset-const-enum with @babel/preset-typescript and constObject transform, then run Babel on a .ts file.

// .babelrc
{
  "presets": [
    "@babel/preset-typescript",
    ["const-enum", { "transform": "constObject" }]
  ]
}

// example.ts
const enum Color {
  Red = 1,
  Green = 2,
  Blue = 3
}
console.log(Color.Red);

// Run: npx babel example.ts --out-file example.js
// Output:
// const Color = {
//   Red: 1,
//   Green: 2,
//   Blue: 3
// };
// console.log(Color.Red);