const enums and isolatedModules
What you'll learn: Why const enums can break in modern build setups and when to avoid them.
The Problem with Cross-File Inlining
Remember that const enums get inlined at compile time — TypeScript replaces every reference to a const enum member with its raw value. This works great when TypeScript sees all your code at once.
But many modern build tools (like Babel, esbuild, and SWC) use a mode called isolatedModules. In this mode, each file is compiled independently, without looking at other files. Think of it like assembling furniture with instructions for one piece at a time, never seeing the full blueprint.
Why This Breaks const enums
When you import a const enum from another file:
// colors.ts
export const enum Colors {
Red = "#ff0000"
}
// button.ts
import { Colors } from './colors';
const color = Colors.Red; // needs inlining
With isolatedModules: true, the compiler processing button.ts cannot see the definition of Colors in colors.ts. It doesn't know what value to inline. The build fails.
The Solution
Either:
- Avoid
const enumsentirely in projects using Babel/esbuild - Use regular enums instead (they compile to objects, so no cross-file inlining needed)
- Keep
const enumsonly within single files (no exports)
Most modern TypeScript projects set isolatedModules: true for compatibility with fast transpilers, making const enums unreliable for exported code.
Key Takeaway: const enums require the compiler to see all files together; with isolatedModules enabled (common in modern bundlers), exported const enums fail to compile — stick to regular enums or string literal unions instead.