I've been struggling to setup path alias in my Node project using TypeScript. This is my package.json
{
...
"main": "index.js",
"type": "module",
"scripts": {
"start": "nodemon",
"build": "tsc"
},
...
"dependencies": {
...
"node-cache": "^5.1.2",
"nodemon": "^3.0.1",
"passport": "^0.6.0",
...
},
"devDependencies": {
...
}
}
...
here is only to shorten.
Here's my nodemon.json
:
{
"watch": ["src"],
"ext": "ts",
"exec": "tsc && node dist/index.js"
}
And finally my tsconfig.json
, where I define a path alias under paths
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"rootDir": "./src",
"moduleResolution": "Node",
"baseUrl": "./",
"paths": {
"@util/*": ["./src/util/*"],
},
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true
}
}
So if I run the following code using npm start
import logger from '@util/logger';
it compiles correctly using the tsc
command but when it runs the .js
file I get the error
Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@util/logger' imported from /path/to/my/project/dist/index.js
.
If I replace '@util/logger'
with './util/logger.js'
it works just fine, but even if I remove the .js
it throws me the erorr, only with Cannot find module
instead of Cannot find package
.
Not sure what am I missing, I even tried this:
// index.ts
import { fileURLToPath } from 'url'; // dirname workaround
import path from 'path'; // dirname workaround
import moduleAlias from 'module-alias';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
moduleAlias.addAliases({
'@util': path.join(__dirname, 'util'),
});
import logger from '@util/logger';
but no luck, still the same error.