Search code examples
javascriptnode.jstypescripttypestsc

why typescript compiler writes path aliases as it is


I'm working on a node-js project with typescript and using typescript path aliases here is my ts config:


{
  "compilerOptions": {
    "target": "ES2022",
    "experimentalDecorators": true,
    "module": "CommonJS", 
    "moduleResolution":"node",
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./*"]
    }
  }
}


Project Structure:-


- routes
  index.ts

- middlewares
  middleware.ts


Problem

path aliases is working fine and VS code is also not throwing any error. But when I'm building code to js, tsc compiler is writing path aliases as it is. Please explain to me why this happening or how can I fix it.

Additional information

Index.ts

import { middleware } from "@/middlewares/middleware";
console.log ("path: routes\index.tsx", middleware);

index.js -- build by tsc

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const middleware_1 = require("@/middlewares/middleware");
console.log("path: routes\index.tsx", middleware_1.middleware);

tsc --traceResolution -- output

======== Resolving module '@/middlewares/middleware' from 'D:/Git Repo/random-restful/templates/routes/index.ts'. ========
Explicitly specified module resolution kind: 'NodeJs'.
'baseUrl' option is set to 'D:/Git Repo/random-restful/templates', using this value to resolve non-relative module name '@/middlewares/middleware'.     
'paths' option is specified, looking for a pattern to match module name '@/middlewares/middleware'.
Module name '@/middlewares/middleware', matched pattern '@/*'.
Trying substitution './*', candidate module location: './middlewares/middleware'.
Loading module as file / folder, candidate module location 'D:/Git Repo/random-restful/templates/middlewares/middleware', target file type 'TypeScript'.
File 'D:/Git Repo/random-restful/templates/middlewares/middleware.ts' exist - use it as a name resolution result.
======== Module name '@/middlewares/middleware' was successfully resolved to 'D:/Git Repo/random-restful/templates/middlewares/middleware.ts'. ========

VS SS


~ Thanks in Advance


Solution

  • tsc doesn't change paths itself. Paths aliases are just helping to integrate typescript with external tools (I.e. webpack) that provide actual aliases. So if you want to use aliased paths you need some tool use some tool. Idk what to use for nodejs thought.