{"id":36940259,"url":"https://github.com/jet2jet/ts-const-value-transformer","last_synced_at":"2026-02-15T02:10:14.575Z","repository":{"id":326834952,"uuid":"1105987486","full_name":"jet2jet/ts-const-value-transformer","owner":"jet2jet","description":"Transforms constant variables with actual literals in TypeScript project","archived":false,"fork":false,"pushed_at":"2026-01-12T11:52:58.000Z","size":625,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-01-12T19:27:14.984Z","etag":null,"topics":["optimizer","transformer","typescript","typescript-transformer","webpack-loader"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jet2jet.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-28T12:59:28.000Z","updated_at":"2026-01-12T11:50:52.000Z","dependencies_parsed_at":"2026-01-05T15:04:30.556Z","dependency_job_id":null,"html_url":"https://github.com/jet2jet/ts-const-value-transformer","commit_stats":null,"previous_names":["jet2jet/ts-const-value-transformer"],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/jet2jet/ts-const-value-transformer","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jet2jet%2Fts-const-value-transformer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jet2jet%2Fts-const-value-transformer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jet2jet%2Fts-const-value-transformer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jet2jet%2Fts-const-value-transformer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jet2jet","download_url":"https://codeload.github.com/jet2jet/ts-const-value-transformer/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jet2jet%2Fts-const-value-transformer/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28382375,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-13T10:34:27.190Z","status":"ssl_error","status_checked_at":"2026-01-13T10:34:26.289Z","response_time":56,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["optimizer","transformer","typescript","typescript-transformer","webpack-loader"],"created_at":"2026-01-13T10:38:47.151Z","updated_at":"2026-02-11T10:08:35.097Z","avatar_url":"https://github.com/jet2jet.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ts-const-value-transformer\n\nTransforms constant variables with actual literals in TypeScript project.\nProvides 'transformer' for TypeScript building ecosystems, 'loader' for webpack, and transform and print APIs.\n\n- [Motivation](#motivation)\n- [Usage](#usage)\n  - [Using transformer](#using-transformer)\n  - [Using webpack loader](#using-webpack-loader)\n  - [Transform options](#transform-options)\n  - [APIs](#apis)\n- [Additional notes](#additional-notes)\n- [License](#license)\n\n## Motivation\n\nUsually, constant variables will be replaced with actual values by [terser](https://terser.org/), [swc](https://swc.rs/) or etc. ([swc example](https://play.swc.rs/?version=1.15.3\u0026code=H4sIAAAAAAAAA9PXVygvyixJVcgvUihILAYykvNTUhUyUotSebl4uZLz84pLFBIVbBWqebkUFBKtFAx1QIwkKwUjMCPZSsGYl6vWGqI0PydVLyc%2FXSNRL1FHIVEvCUQkawIlAet2OZpnAAAA\u0026config=H4sIAAAAAAAAA32US3LbMAyG9zmFR%2Bts20UPkF3PwKFJUKbDh4YAHWsyvnshSrLdGNJOwocfIAEQ32%2BHQ3dG0%2F05fPMn%2Fwy6IJT7P1twTKSvbOnARI2m%2BIG695WecUJOB4Rmus2kI116oKbCX4t7F3JGWN0XW%2FTJu%2FE5oclxKID4ZGMrx6sREuH%2F%2BoWV%2FDUBKvXZfsw5gE47RGlUPhH0UKTAJoegBwR10UWIMp1UF49ZSjHBSmDVUPIg8mQ9%2BZw45yu1oK0y2YKAfAFD%2FgKSjHOxLCFfT7hPwxaOte9bk3%2Bo4aJD1STkhGtrCZ9WiHrKHkm5mqQSznCjBjNcivtT6Z0qQLWkV905%2B7TRk08ArkDQiElHkOI2D8fztKV2u0qfHI8sjQLn%2BZZumaDnoirvnVDZqTJQyEvdLGCrgamyRjrOgjfKh96CAud4VoTQ%2BOXJnKSkNA6QnQC4v9pJUzUDdX%2BFG3x6EDv4g29J8oAtHlHTaZviGI857CSIQKdsdxy4FZS3ceEtcR22eU0WeDTAii4VG3hdAvwAKKvQluXLbPDz4IiqD%2Fn4WBOLw%2B2%2BhKNO%2FeO9z3v4bXHoYra1wWXDT%2F2d9%2FLv7uG0buH1BJ3Hv6uw5bz9A1EN%2Bh8sBgAA)), but if the variables are exported, the variables are not replaced ([swc example](https://play.swc.rs/?version=1.15.3\u0026code=H4sIAAAAAAAAAyXKwQqAIBCE4bvgO8yxQIzqZvQwmy0VRBsqFETvXtZl%2BGD%2BqsIRlsSQgJ3iCy8jY%2BbAWmnlZYsJhB6XVgA51CZjcGg%2BeIdWq7v7U1nZrjIVZMmA7JDHl%2B%2FJ5y4h4aJcPrXX%2FP90AAAA\u0026config=H4sIAAAAAAAAA32US3LbMAyG9zmFR%2Bts20UPkF3PwKFJUKbDh4YAHWsyvnshSrLdGNJOwocfIAEQ32%2BHQ3dG0%2F05fPMn%2Fwy6IJT7P1twTKSvbOnARI2m%2BIG695WecUJOB4Rmus2kI116oKbCX4t7F3JGWN0XW%2FTJu%2FE5oclxKID4ZGMrx6sREuH%2F%2BoWV%2FDUBKvXZfsw5gE47RGlUPhH0UKTAJoegBwR10UWIMp1UF49ZSjHBSmDVUPIg8mQ9%2BZw45yu1oK0y2YKAfAFD%2FgKSjHOxLCFfT7hPwxaOte9bk3%2Bo4aJD1STkhGtrCZ9WiHrKHkm5mqQSznCjBjNcivtT6Z0qQLWkV905%2B7TRk08ArkDQiElHkOI2D8fztKV2u0qfHI8sjQLn%2BZZumaDnoirvnVDZqTJQyEvdLGCrgamyRjrOgjfKh96CAud4VoTQ%2BOXJnKSkNA6QnQC4v9pJUzUDdX%2BFG3x6EDv4g29J8oAtHlHTaZviGI857CSIQKdsdxy4FZS3ceEtcR22eU0WeDTAii4VG3hdAvwAKKvQluXLbPDz4IiqD%2Fn4WBOLw%2B2%2BhKNO%2FeO9z3v4bXHoYra1wWXDT%2F2d9%2FLv7uG0buH1BJ3Hv6uw5bz9A1EN%2Bh8sBgAA)). But if the variables are strictly typed, the variables should be replaced probably safely.  \nThis package aims to replace those variables/property references/enum values with actual values, to reduce code side (and, perhaps, to increase execution speed).\n\n## Usage\n\nFirst, install with:\n\n```sh\nnpm install --save-dev ts-const-value-transformer\n```\n\n### Using transformer\n\nTransformer is a feature for TypeScript build system to convert parsed source code (AST) to another AST.\nTypeScript compiler `tsc` does not accept transformers, but some TypeScript-related ecosystems such as\n[ts-loader](https://www.npmjs.com/package/ts-loader) and [ts-patch](https://www.npmjs.com/package/ts-patch) accept transformers to intercept builds.\n\nTo use with ts-loader, write webpack configuration as follows:\n\n```js\nimport { createTransformer } from 'ts-const-value-transformer';\n// or: const { createTransformer } = require('ts-const-value-transformer');\n// (you can use 'require' for ES modules starting from Node.js v20.19.0; see https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require)\n\nconst yourWebpackConfiguration = {\n  module: {\n    rules: [\n      {\n        test: /\\.ts$/,\n        use: [\n          {\n            loader: 'ts-loader',\n            options: {\n              getCustomTransformers: (program) =\u003e ({\n                before: [\n                  createTransformer(program, {\n                    options: {\n                      /* ts-const-value-transformer options (see below) */\n                    },\n                  }),\n                ],\n              }),\n              // ...other configurations\n            },\n          },\n        ],\n      },\n    ],\n  },\n  // ...other configurations\n};\n```\n\nor:\n\n```js\nconst yourWebpackConfiguration = {\n  module: {\n    rules: [\n      {\n        test: /\\.ts$/,\n        use: [\n          {\n            loader: 'ts-loader',\n            options: {\n              // If you specify only one transformer, you can use 'ts-const-value-transformer/getCustomTransformers' module\n              getCustomTransformers:\n                'ts-const-value-transformer/getCustomTransformers',\n              // ...other configurations\n            },\n          },\n        ],\n      },\n    ],\n  },\n  // ...other configurations\n};\n```\n\nTo use with ts-patch, write tsconfig.json as follows:\n\n```jsonc\n  \"compilerOptions\": {\n    // ...\n    \"plugins\": [\n      { \"transform\": \"ts-const-value-transformer\", \"options\": { /* ts-const-value-transformer options (see below) */ } }\n    ]\n  }\n```\n\n### Using webpack loader\n\nYou can use webpack loader for transformation. If you use loaders to transpile TS files other than ts-loader, `ts-const-value-transformer/loader` is a choice.  \nNote that this may increase the build time because of parsing processes.\n\n\u003e If you are using ts-loader, you should use the transformer described above for performance reason.\n\n```js\nconst yourWebpackConfiguration = {\n  module: {\n    rules: [\n      {\n        test: /\\.ts$/,\n        use: [\n          {\n            loader: 'babel-loader',\n            options: {\n              presets: ['@babel/preset-typescript'],\n            },\n          },\n          {\n            loader: 'ts-const-value-transformer/loader',\n            options; {\n              project: 'tsconfig.json', // your tsconfig.json\n              // typescript: 'typescript', // if you are using another 'typescript' package, you can specify the module name here\n              // ... other options from `TransformOptions` fields\n              // hoistProperty: false,\n              // ...\n            }\n          },\n        ],\n      },\n    ],\n  },\n  // ...other configurations\n};\n```\n\n### Transform options\n\n```ts\nexport interface TransformOptions {\n  /** `typescript` namespace object */\n  ts?: typeof ts;\n  /** Hoist property expressions (`x.prop`) which the value is constant. Default is true, but if the property getter has side effects (not recommended), set false explicitly. */\n  hoistProperty?: boolean | undefined;\n  /** Hoist TypeScript's `enum` values (which are constant). Default is true, but if you want to preserve references, set false explicitly. Note that TypeScript compiler erases `const enum` references unless `preserveConstEnums` is true. */\n  hoistEnumValues?: boolean | undefined;\n  /** Hoist values defined in the external libraries. Default is true, but if the external libraries are not bundled, set false explicitly to keep references. */\n  hoistExternalValues?: boolean | undefined;\n  /** Hoist function calls which the return value is constant. Default is false because function calls may have side effects. */\n  unsafeHoistFunctionCall?: boolean | undefined;\n  /** Hoist function calls, with `@__PURE__` (or `#__PURE__`) comment annotation (must be a multi-line comment), which the return value is constant. Default is false, but if the function really has no side effects, you can safely specify true. If true, `unsafeHoistFunctionCall` option is ignored for `@__PURE__` functions */\n  hoistPureFunctionCall?: boolean | undefined;\n  /** Hoist expressions with `as XXX`. Default is false because the base (non-`as`) value may be non-constant. */\n  unsafeHoistAsExpresion?: boolean | undefined;\n  /** Hoist properties/variables that can write (i.e. `let` / `var` variables or properies without `readonly`). Default is false because although the value is literal type at some point, the value may change to another literal type. */\n  unsafeHoistWritableValues?: boolean | undefined;\n  /** Uses `undefined` symbol for `undefined` type values. Default is false and replaces to `void 0`. */\n  useUndefinedSymbolForUndefinedValue?: boolean | undefined;\n  /** Hoist `undefined` symbol to `void 0` (or `undefined` if useUndefinedSymbolForUndefinedValue is true). Default is true. */\n  hoistUndefinedSymbol?: boolean | undefined;\n  /** Hoist template literals with constant (not including variables). Default is false because it is not necessary for ES2015 or later; Script minifiers would optimize for those values. For ES5 (which will be deprecated in the future), TypeScript converts template literals to such as `''.concat(...)`, which is not treated as constant values. */\n  hoistConstTemplateLiteral?: boolean | undefined;\n  /**\n   * External names (tested with `.includes()` for string, with `.test()` for RegExp) for `hoistExternalValues` settings (If `hoistExternalValues` is not specified, this setting will be used).\n   * - Path separators for input file name are always normalized to '/' internally.\n   * - Default is `['/node_modules/']`.\n   */\n  externalNames?: ReadonlyArray\u003cstring | RegExp\u003e | undefined;\n  /**\n   * Specifies for file name list or function to skip transformation. This option is used by webpack loader, the transformed called from ts-loader, and createPortalTransformer only.\n   * - For list, if the token is `string`, the transformation will be skipped if `fileName.indexOf(token) \u003e= 0` is true.\n   *   If the token is `RegExp`, the transformation will be skipped if `fileName.indexOf(token) \u003e= 0` is true.\n   * - For function, the transformation will be skipped if `fn(fileName)` is true.\n   */\n  ignoreFiles?:\n    | ReadonlyArray\u003cstring | RegExp\u003e\n    | ((fileName: string) =\u003e boolean);\n}\n```\n\nNote that you must pass `options` field to `createTransformer` function or `\"plugins\"` specifier (see above examples).\n\n### APIs\n\n```ts\nimport {\n  createTransformer,\n  printSource,\n  printSourceWithMap,\n  transformSource,\n  version,\n  type TransformOptions,\n  createPortalTransformer,\n  createPortalTransformerSync,\n  type CreatePortalTransformerOptions,\n  type PortalTransformer,\n} from 'ts-const-value-transformer';\n```\n\n#### createTransformer: (program: ts.Program, config?: { options?: TransformOptions }, extras?: { ts?: typeof ts }) =\u003e ts.TransformerFactory\u003cts.SourceFile\u003e\n\nUsed with TypeScript API or ts-loader.\n\nCall example:\n\n```js\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { createTransformer } from 'ts-const-value-transformer';\n\nconst PROJECT_DIR = path.resolve('.');\n\n// Load tsconfig.json file\nconst configFile = ts.readJsonConfigFile(\n  path.resolve(PROJECT_DIR, 'tsconfig.json'),\n  ts.sys.readFile\n);\nconst config = ts.parseJsonSourceFileConfigFileContent(\n  configFile,\n  ts.sys,\n  PROJECT_DIR\n);\n\n// Initialize the program\nconst program = ts.createProgram({\n  options: config.options,\n  rootNames: config.fileNames,\n});\n\n// Load the source file to transform\nconst fileName = path.resolve(PROJECT_DIR, 'index.mts');\nconst sourceFile = program.getSourceFile(fileName)!;\n\n// Do transform\nconst transformer = createTransformer(program);\nconst result = ts.transform(\n  sourceFile,\n  [transformer],\n  program.getCompilerOptions()\n);\nconst transformedSource = result.transformed[0]!;\n// You can emit the transformed code by using `printSource` (see below):\n//   console.log(printSource(transformedSource));\n```\n\n#### printSource: (sourceFile: ts.SourceFile) =\u003e string\n\nPrints (generates) source code from `SourceFile`. The source file must be one generated by `transformSource` or existing in the TS project (available with `getSourceFile()` in `ts.Program`).\n\n#### printSourceWithMap: (sourceFile: ts.SourceFile, originalSourceName: string, startOfSourceMap?: RawSourceMap) =\u003e [string, RawSourceMap]\n\nPrints (generates) source code from `SourceFile`, along with raw source-map data. The source file must be one generated by `transformSource` or existing in the TS project (available with `getSourceFile()` in `ts.Program`).\n\n- `originalSourceName` would be the file name of `sourceFile`, but you can specify another name.\n- `startOfSourceMap` is a base source map (if original source file is a generated-content) if available.\n\n#### transformAndPrintSource: (sourceFile: ts.SourceFile, program: ts.Program, context: ts.TransformationContext | undefined, options?: TransformOptions) =\u003e string\n\nTransforms the source file with TypeScript project and prints a new source code. This acts like combination of `transformSource` and `printSource`, but performs in one loop, so if transformed AST is not necessary, this function is suitable.\n\n#### transformAndPrintSourceWithMap: (sourceFile: ts.SourceFile, program: ts.Program, context: ts.TransformationContext | undefined, originalSourceName: string, options?: TransformOptions, startOfSourceMap?: RawSourceMap) =\u003e [string, RawSourceMap]\n\nTransforms the source file with TypeScript project and prints a new source code. This acts like combination of `transformSource` and `printSourceWithMap`, but performs in one loop, so if transformed AST is not necessary, this function is suitable.\n\n- `originalSourceName` would be the file name of `sourceFile`, but you can specify another name.\n- `startOfSourceMap` is a base source map (if original source file is a generated-content) if available.\n\n#### transformSource: (sourceFile: ts.SourceFile, program: ts.Program, context: ts.TransformationContext, options?: TransformOptions) =\u003e ts.SourceFile\n\nTransforms the source file with TypeScript project. You don't need to call this function directly; use `createTransformer` or `createPortalTransformer` instead.\n\nNote that `ignoreFiles` of `options` will be ignored for this function.\n\n#### version: string\n\nThe version string of this package.\n\n#### type TransformOptions\n\nSee [Transform options](#transform-options).\n\n#### createPortalTransformer: (options?: CreatePortalTransformerOptions) =\u003e Promise\u003cPortalTransformer\u003e\n\nCreates 'portal transformer', which can be used the transformer easily from the code which does not use TypeScript Compiler API.  \nThe return object has `transform` method with signature: `(content: string, fileName: string, sourceMap?: string | RawSourceMap | null, options?: TransformOptions) =\u003e [newSource: string, newSourceMap: RawSourceMap | undefined]`. You can call to transform TypeScript source code. (Note that this API does not transpile to JavaScript; the output code is still TypeScript code.)\n\n`CreatePortalTransformerOptions` has a following signature. Also, `TransformOptions` fields, including `ignoreFiles`, can be used.\n\n```ts\ninterface CreatePortalTransformerOptions extends TransformOptions {\n  /** Path to tsconfig.json. If omitted, `tsconfig.json` will be used. */\n  project?: string;\n  /** Package path to `typescript` or `typescript` namespace object. */\n  typescript?: string | typeof tsNamespace;\n  /** The current directory for file search. Also affects to `project` option. */\n  cwd?: string;\n  /**\n   * Speficies the count. When the transformation count reaches this value, `program` instance will be recreated (and count will be reset).\n   * This is useful if the project is big and out-of-memory occurs during transformation, but the process may be slower.\n   * If 0 or `undefined`, recreation will not be performed.\n   */\n  recreateProgramOnTransformCount?: number;\n  /** Specifies to cache base (original) source code for check if the input is changed. Default is false. */\n  cacheBaseSource?: boolean;\n  /** Specifies to cache result source code. Default is true (false for webpack loader). If the latter process has cache system, specifies false to reduce memory usage. */\n  cacheResult?: boolean;\n}\n```\n\nIf `Promise` cannot be used for some reason, use `createPortalTransformerSync` instead.\n\n## Notice\n\nStarting from v0.4.0, `unsafeHoistWritableValues` option is introduced. Since TypeScript sometimes narrows non-constant values to literal types such as:\n\n```ts\nconst resultObject = { success: false };\nsomeFunc1(resultObject);\nconsole.log(resultObject.success); // resultObject.success will be `boolean` type\nresultObject.success = false;\nsomeFunc1(resultObject);\nconsole.log(resultObject.success); // resultObject.success will be `false` type, not `boolean`\n```\n\n... so if `unsafeHoistWritableValues` is true, the second reference of `resultObject.success` above will be replaced to `false`, which may not be correct.\n\n## Additional notes\n\nI think there should be more optimization methods by using strictly-typed information, like other programming languages.\n\n## License\n\n[MIT License](./LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjet2jet%2Fts-const-value-transformer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjet2jet%2Fts-const-value-transformer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjet2jet%2Fts-const-value-transformer/lists"}