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.
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
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With