Use TypeScript path aliases in Node.js

June 16, 2024

First you need to set the basic path aliases config in tsconfig.json.

{
  "compilerOptions": {
    // ...Existing configuration
    "baseUrl": "./src",
    "paths": {
      "@/*": ["*"]
    }
  }
}

This allow you to use aliases (@) in your code.

// If our project structure looks like this:
// project-root/
// │
// ├── src/
// │   ├── lib/
// │   │   └── utils.tsx
// │   │
// │   ├── index.ts
// │
// ├── tsconfig.json
// ├── ...
import { getDate } from '@/lib/utils'

const date = getDate()

Now, when you build your application, you need to install tsc-alias package, and edit the build command in package.json.

{
  // ...Existing configuration
  "scripts": {
    "build": "tsc && tsc-alias"
  }
}

This will replace alias paths with relative paths after typescript compilation.