TypeScript Path Alias Resolver

4.2.0 · active · verified Sun Apr 19

tsconfig-paths is a utility that provides runtime support for TypeScript's path mapping feature, allowing Node.js to resolve modules based on the `paths` configuration in `tsconfig.json`. This addresses the common issue where TypeScript compiles code successfully using path aliases (e.g., `@lib/utils`), but Node.js fails at runtime because it doesn't understand these mappings. The package, currently at version 4.2.0, functions by hooking into Node.js's module resolution system, typically via a `--require` flag (e.g., `node -r tsconfig-paths/register`) or through a programmatic API. While TypeScript handles `paths` during compilation, tsconfig-paths ensures these aliases work in development environments with `ts-node` or directly with compiled JavaScript, making it a critical tool for maintaining clean import paths and structured projects without additional build steps or manual path adjustments for runtime execution. Its release cadence is generally tied to bug fixes and compatibility updates, not a strict schedule.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates both CLI usage for Node.js and ts-node, and programmatic API registration for finer control over path resolution, including `baseUrl` and `paths` from `tsconfig.json`.

const tsConfig = require('./tsconfig.json');
const { register } = require('tsconfig-paths');

// Example tsconfig.json content:
// {
//   "compilerOptions": {
//     "baseUrl": ".",
//     "paths": {
//       "@utils/*": ["src/utils/*"],
//       "@config": ["src/config/index.ts"]
//     }
//   }
// }

// 1. Using the CLI with Node.js:
// To run a JavaScript file compiled from TypeScript with path aliases:
// node -r tsconfig-paths/register main.js

// 2. Using the CLI with ts-node:
// To run a TypeScript file directly with path aliases:
// ts-node -r tsconfig-paths/register main.ts

// 3. Programmatic registration for more control:
// This is useful if your tsconfig.json is not in the CWD or you need custom settings.

const baseUrl = process.env.TS_NODE_BASEURL ?? tsConfig.compilerOptions.baseUrl ?? './';
const cleanup = register({
  baseUrl,
  paths: tsConfig.compilerOptions.paths
});

console.log('tsconfig-paths registered successfully.');

// Your application logic that uses path aliases would go here.
// For example, if you had '@utils/logger' mapped to 'src/utils/logger.ts'
// import { log } from '@utils/logger';
// log('Application started');

// When path registration is no longer needed (e.g., in a long-running process that might reconfigure)
// cleanup();

view raw JSON →