Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tsc - doesn't compile alias paths

I have typescript and uses the aliases. Here is part of tsconfig.json

"compilerOptions": {
  "baseUrl": "./src",
   ...
},

By setting the base url, I can change

import User from "src/models/User.model.ts"

to

import User from "models/User.model.ts"

The problem is that tsc compiles src folder to dist folder, so User import path should be changed to the relative path something like this:

"../models/User.model.js"

But it doesn't change, so I get the following error:

"models/User.model.js" not found

I searched for the answer, but no luck.

like image 390
ahadortiz Avatar asked Dec 04 '19 15:12

ahadortiz


2 Answers

TSC compiler alone can't resolve the alias paths. So in order to make it work you will be required to install additional dev package

npm install --save-dev tsc-alias

tsc-alias is for replacing alias paths with relative paths after typescript compilation of tsc compiler because the compiler alone can't resolve the alias paths

After that you need to modify your build command in your package.json file to

"build": "tsc && tsc-alias",

Running npm run build should work after that and the code should be compiled correctly to javascript

If you want to enable also hot reloading you will be required to install one more dev package

npm install --save-dev concurrently

concurrently is for runing multiple commands concurrently

After that you will need to add 1 new script inside your package.json file

"build:watch": "concurrently --kill-others \"tsc -w\" \"tsc-alias -w\"",

Running npm run build:watch should work after that and the code should be compiled correctly to javascript with hot reload functionality

Please Note: I am using this versions of the packages

"tsc-alias": "^1.5.0",
"typescript": "^4.5.5",
"concurrently": "^7.0.0",

Older or newer versions might introduce some issues with compiling the code

like image 146
TatkoBarba Avatar answered Nov 15 '22 21:11

TatkoBarba


There's a long discussion in typescript issues about this, and I can't seem find better solution than this.

Development

npm i -save-dev tsconfig-paths/register

tsconfig.json

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

package.json

"scripts": {
  dev: "ts-node -r tsconfig-paths/register src/index.ts"
}

Build

npm i -save-d ttypescript @zerollup/ts-transform-paths

tsconfig.json

{
 "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@src/*": ["src/*"],
    },
    "plugins": [
      {
          "transform": "@zerollup/ts-transform-paths",
      }
    ]
  }
}

package.json

"scripts": {
  build: "ttsc -P ./tsconfig.json"
}
like image 38
Jethro91 Avatar answered Nov 15 '22 22:11

Jethro91