TypeScript Path Mapping Transformer
typescript-transform-paths is a TypeScript compiler plugin that transforms module resolution paths defined in `tsconfig.json`'s `paths` or `rootDirs` options into correct relative paths within the compiled JavaScript and declaration files. It addresses a common pain point where TypeScript's path aliases are not natively resolved by Node.js or bundlers without additional configuration. The current stable version is 3.5.6, with a significant v4.0.0-beta release that transitions to ESM-only. The package sees regular maintenance releases and active development, with a beta channel for upcoming major changes. Its key differentiators include comprehensive support for both `.js` and `.d.ts` file transformations, integration with various build tools like `ts-patch`, `ts-node`, `node -r`, and NX, and the ability to define exclusion patterns for granular control.
Common errors
-
TypeError: (0 , typescript_transform_paths_1.default) is not a function
cause Attempting to `import` or `require` the plugin directly in application code, or an incorrect setup with `ts-patch` or `ts-node`.fixThis package is a compiler plugin, not a runtime library for direct import. Ensure it's correctly configured in `tsconfig.json` `plugins` for compilation (with `ts-patch`) or used via its `register` script for runtime (`node -r` or `ts-node` config). -
Error: Expected version to be parsed
cause This error occurs in specific scenarios where the installed TypeScript version string contains a '0' in an unexpected position, causing issues with internal version parsing logic.fixThis was fixed in v3.5.5. Update `typescript-transform-paths` to version 3.5.5 or newer to resolve this parsing issue. -
Module not found: Error: Can't resolve '@utils/sum' in '...' (or similar path alias error after build)
cause The TypeScript `paths` configuration was not transformed during compilation, or the runtime environment is not resolving the aliased paths.fixVerify that `typescript-transform-paths` is correctly configured in your `tsconfig.json` plugins for both `.js` and `.d.ts` files. If compiling with `tsc`, ensure `ts-patch install` and `ts-patch tsc` are used. If at runtime, make sure `typescript-transform-paths/register` is active (e.g., `node -r` or `ts-node` config).
Warnings
- breaking Version 4.0.0-beta introduces an ESM-only distribution. Projects targeting CommonJS modules will need to stick to version 3.x or migrate their build system to ESM.
- gotcha To ensure path transformations apply to both compiled JavaScript (`.js`) files and their corresponding TypeScript declaration (`.d.ts`) files, you must include two separate plugin entries in your `tsconfig.json`.
- gotcha When using `typescript-transform-paths` with `ts-node`, it's important to configure `ts-node` to `require` the transformation module. Simply having the plugin in `tsconfig.json` does not automatically enable it for `ts-node`'s runtime compilation.
- gotcha The plugin needs to be applied by a TypeScript transformer runner. Installing the package alone is not enough; you must integrate it with a tool like `ts-patch` for `tsc` compilation or use its `register` script for runtime.
- gotcha Older TypeScript versions (e.g., prior to 3.6.5, though the peer dep is now >=3.6.5) or specific patch versions might lead to compatibility issues, as observed with `minimatch` dependency changes and TypeScript 5.6 compatibility fixes.
Install
-
npm install typescript-transform-paths -
yarn add typescript-transform-paths -
pnpm add typescript-transform-paths
Imports
- transformer
import * as transform from 'typescript-transform-paths'
{ "transform": "typescript-transform-paths" } - afterDeclarations transformer
{ "transform": "typescript-transform-paths/afterDeclarations" }{ "transform": "typescript-transform-paths", "afterDeclarations": true } - register
require('typescript-transform-paths/register')node -r typescript-transform-paths/register your-app.js
- nx-transformer
{ "name": "typescript-transform-paths/nx-transformer" }
Quickstart
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
// Minimal ts-patch setup for demonstration
const tsconfigPath = path.resolve('./tsconfig.json');
const tsconfigContent = fs.readFileSync(tsconfigPath, 'utf8');
const tsconfig = ts.parseConfigFileTextToJson(tsconfigPath, tsconfigContent).config;
// Simulate the ts-patch application of the transformer
// In a real setup, ts-patch handles this with its CLI tool.
const program = ts.createProgram({
rootNames: [path.resolve('./src/index.ts')],
options: {
...tsconfig.compilerOptions,
noEmit: false, // Ensure output for demonstration
outDir: './dist-quickstart' // Output to a specific directory
},
});
const emitResult = program.emit(undefined, undefined, undefined, undefined, [
{
before: (ctx) => (sourceFile) => {
// This represents the 'typescript-transform-paths' plugin
// In real scenarios, this is loaded dynamically by ts-patch
const ttPaths = require('typescript-transform-paths');
const transformer = ttPaths.default(program, tsconfig.compilerOptions, {}, ts, path, fs)(ctx);
return transformer(sourceFile);
},
afterDeclarations: (ctx) => (sourceFile) => {
const ttPaths = require('typescript-transform-paths');
const transformer = ttPaths.default(program, tsconfig.compilerOptions, { afterDeclarations: true }, ts, path, fs)(ctx);
return transformer(sourceFile);
}
}
]);
if (emitResult.emitSkipped) {
console.log('Compilation failed or skipped.');
} else {
console.log('Compilation successful. Check ./dist-quickstart for output.');
}
/*
To run this:
1. Create tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@utils/*": ["./src/utils/*"]
},
"outDir": "./dist",
"declaration": true,
"target": "es2018",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"plugins": [
{ "transform": "typescript-transform-paths" },
{ "transform": "typescript-transform-paths", "afterDeclarations": true }
]
},
"include": ["src/**/*.ts"]
}
2. Create src/utils/sum.ts:
export function sum(a: number, b: number): number { return a + b; }
3. Create src/index.ts:
import { sum } from "@utils/sum";
console.log(sum(1, 2));
4. Install deps: npm i -D typescript typescript-transform-paths
5. Run with `npx ts-node your-script.ts` (this script simulates the plugin, not directly using ts-patch CLI)
(For actual usage, you'd run `npx ts-patch tsc` after `ts-patch install`)
*/