Update (as of March 2023)
The previous answers were helpful for development but I was still facing issues in production when I would run my build file.
The way I solved it once and for all is by using the tsc-alias package in build and the tsconfig-paths in development.
Setup instructions:
- Install
tsc-alias & tsconfig-paths as a dev dependency with:
npm i -D tsc-alias tsconfig-paths
- Use
tsconfig-paths in your dev or start script like so:
{
"scripts": {
"dev": "ts-node-dev -r tsconfig-paths/register src/index.ts", // here I am using ts-node-dev
"start": "ts-node -r tsconfig-paths/register src/index.ts" // works with node too, see tsconfig-paths doc
},
"devDependencies": {
"tsconfig-paths": "^4.1.2",
"typescript": "^4.9.5"
}
}
- Append
tsc-alias in the build script.
In your package.json:
{
"scripts": {
"build": "tsc -p tsconfig.json && tsc-alias -p tsconfig.json"
},
"devDependencies": {
"tsc-alias": "^1.8.3",
"typescript": "^4.9.5"
}
}
And that's it. You are done. You can now use both path alias AND absolute imports and build your app without running into module not found issues.
Here's my tsconfig.json for reference:
{
"compilerOptions": {
"module": "commonjs",
"baseUrl": "src", // notice my base url is set to ./src folder
"resolveJsonModule": true,
"outDir": "./build",
"paths": {
"@middlewares": ["_globals/middlewares"], // referring to ./src/_globals/middlewares folder
"@exceptions": ["_globals/exceptions"],
"@utils": ["_globals/utils"]
}
},
"include": [ "src/**/*" ], // if you need absolute path or path alias outside src then include the directory accordingly
"exclude": ["src/test.ts"] // import won't work in this file/directory
}
Usage
You can now use both absolute import and path alias:
import { sth } from "_globals/sth"; // using absolute imports
import { sth } from "@utils"; // using path alias
Your build file should also run without any module not found errors.