Eject enums from your TypeScript codebases.
npm install eject-enumEject enums from your TypeScript codebase.
eject-enum is a code rewriting tool for TypeScript codebases that
rewrites each TypeScript enum in your codebase to
the safer alternative.
Before rewriting:
``ts`
/**
* Signals of traffic light.
*/
export enum TrafficLight {
/* Stop. /
Red,
/* Stop unless you can't do so safely. /
Yellow,
/* Go. /
Green,
}
After rewriting:
`ts
/**
* Signals of traffic light.
*/
export const TrafficLight = {
/* Stop. /
Red: 0,
/* Stop unless you can't do so safely. /
Yellow: 1,
/* Go. /
Green: 2,
} as const;
export type TrafficLight = (typeof TrafficLight)[keyof typeof TrafficLight];
`
> [!Note]
>
> **It is recommended to run code formatting tools after rewriting by
> eject-enum**, as it doesn't consider any code formatting configurations of
> your project when rewriting.
You can execute eject-enum as a CLI tool:
`bashnpm
npx eject-enum [options...]
CLI Options:
`bash
If no targets are specified, it tries to use
tsconfig.json
in the current directory as the default target.
npx eject-enumRewrite all files in projects specified by tsconfigs.
npx eject-enum path/to/tsconfig.json path/to/tsconfig2.jsonRewrite all Typescript files under the
src and test directories,
except files under the
src/foo directory.
npx eject-enum "src//.ts" "test//.ts" --exclude "src/foo/*/.ts"
`$3
You can use eject-enum as a library from your scripts as well.
`bash
npm install --save-dev eject-enum
``ts
import { ejectEnum, EjectEnumTarget } from "eject-enum";// Rewrite all files in projects specified by paths to tsconfigs.
ejectEnum(
EjectEnumTarget.projects([
"path/to/tsconfig.json",
"path/to/tsconfig2.json",
]),
);
// Rewrite all Typescript files under the
src and test directories
// except files under the src/foo directory.
ejectEnum(
EjectEnumTarget.srcPaths({
include: ["src//.ts", "test//.ts"],
exclude: ["src/foo/*/.ts"],
}),
);
`Features
- [x] Rewrite enums in the top-level as well as nested in functions, namespaces
and body of control flows (
if, while, switch`).eject-enum have some limitations about code rewriting. They originate from
limitations of the TS Compiler API/ts-morph.
- Can't rewrite enums that have computed enum members.
- e.g. referring variables, members of other enums (even constant members)
- Can't preserve original trailing comments of enum members.