How do I transpile aliased paths in TypeScript to JavaScript?
Asked Answered
U

1

6

I have a TypeScript project that I am trying to transpile into executable JavaScript which makes use of path aliases. This is required for the NPM package I am working on.

For example here with importing a method from my lib directory without referencing it via relative paths:

import { hexify } from '@lib/utils/conversion';

Usually I would use tsconfig-paths to register the path-aliases when running the app from the entry point with a command like ts-node-dev --files -r tsconfig-paths/register ./src/index.ts or in production mode with node -r ts-node/register/transpile-only -r tsconfig-paths/register ./dist/index.js. But in this instance I would like to successfully transpile it to JavaScript so that the compiler automatically translates the path aliases to the correct relative paths therefore not needing to use ts-node and tsconfig-paths to successfully run the JavaScript code.

My tsconfig.json file looks like this for some additional context:

{
  "ts-node": {
    "files": true
  },
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "rootDir": "src",
    "outDir": "dist",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": false,
    "resolveJsonModule": true,
    "baseUrl": "./",
    "paths": {
      "@src/*": ["src/*"],
      "@middleware/*": ["src/middleware/*"],
      "@services/*": ["src/services/*"],
      "@routes/*": ["src/routes/*"],
      "@controllers/*": ["src/controllers/*"],
      "@exchanges/*": ["src/api/exchanges/*"],
      "@utils/*": ["src/utils/*"],
      "@api/*": ["src/api/*"],
      "@lib/*": ["src/lib/*"],
      "@app": ["src/app/index.ts"],
      "@singleton/*": ["src/singleton/*"],
      "@constants/*": ["src/constants/*"]
    }
  },
  "exclude": ["junk"]
}

However when building this project, my NPM package cannot make sense of my path aliases, is there something I can do about this to make my NPM package work or should I just change all my TypeScript imports using aliases to instead use relative paths like this example below:

import { hexify } from '../lib/utils/conversion.ts'
Unloosen answered 29/7, 2022 at 10:2 Comment(0)
H
0

Currently, there's no way to do this as part of a tsc build.

There are a number of modules out there that will do the task for you, such as ts-alias. Indeed, a search on npm for "typescript path alias" gives 66 such modules: https://www.npmjs.com/search?q=typescript%20path%20alias

Hardunn answered 29/11, 2022 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.