Problem
I want to use path aliasing in NodeJS + TS. To do that, I need to:
- declare
baseUrl
andpaths
intsconfig.json
to denote I want to use path alias (avoidimport { sth } from "./../../../sth.ts"
- use
tsconfig-paths
to "load modules whose location is specified in thepaths
" (aka my path alias would be mapped to physical files) - use
ts-node
to runtsconfig-paths
with:ts-node -r tsconfig-paths/register ./src/server.ts
The whole process could now be solved with this, based on this answer:
nodemon -e js --exec ts-node -r tsconfig-paths/register ./src/server.ts
My problem is that, nodemon
executes the TS files, not the emitted JS files.
Questions:
- How can I use these tools to point
nodemon
to run emitted JS files (insidedist/
folder) instead of TS files andnodemon
still understands my path alias ? - I also tried
nodemon dist/server.js --exec ts-node -r tsconfig-paths/register ./src/server.ts
but it doesn't work, but why the previous script work ? - Bonus question: in nowsaday, should I run backend Node server from emitted JS files ? or should I just run straight from TS files ?
Environment
- NodeJS: v16.16.0
nodemon
: v2.0.20tsconfig-paths
: v4.1.0ts-node
: v10.9.1
Similar questions
- Typescript paths not working in an Express project
- How to watch and reload ts-node when TypeScript files change
Code
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": ["dom", "es2015", "es5", "es6", "es2020"],
"sourceMap": true,
"moduleResolution": "node",
"baseUrl": "./",
"outDir": "./dist",
"rootDir": "./src",
"paths": {
"~/*": ["src/*"]
},
"strict": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false
}
}