Unfortunately (and I don't know why) the Typescript compiler currently does not support the paths transformation very well.
Here is my solution:
I used the solution with this project.
Install devDependencies
- ttypescript -> npm install ttypescript --save-dev -> TTypescript (Transformer TypeScript) solves the problem by patching on the fly the compile module to use transformers from tsconfig.json.
- typescript-transform-paths -> npm install typescript-transform-paths --save-dev -> Transforms absolute imports to relative from paths in your tsconfig.json.
- tsconfig-paths -> npm install tsconfig-paths --save-dev -> Use this to load modules whose location is specified in the paths section of tsconfig.json. Both loading at run-time and via API are supported.
- ts-node-dev -> npm install ts-node-dev --save-dev -> It restarts target node process when any of required files changes (as standard node-dev) but shares Typescript compilation process between restarts
tsconfig.json
Update the tsconfig.json file with the following options:
{
"compilerOptions": {
/* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
"paths": {
"@app/*": [
"./src/*"
]
},
/* Advanced Options */
"plugins": [
{
"transform": "typescript-transform-paths"
}
],
}
}
Build
For the compilation phase use ttsc instead of tsc with the configuration file. See the snippet below:
npx ttsc --p ./tsconfig.json
Development mode with autoreload
When you are in dev mode use the following script (put it in the scripts options in package.json) to automatically reload the project with the correct paths. The src/app.ts is the "entry point" of your application located under the src folder.
npx ts-node-dev --prefer-ts true --no-notify -r tsconfig-paths/register --watch src --transpileOnly src/app.ts
PS: Using ts-node-dev increase the speed significantly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…