When we are working on development projects sometimes we have a long path of imports 😬
import { x } from '../../../../path/to/x';
// code ...
To reduce these long paths, TypeScript provides us with paths
in tsconfig.json
to add path aliases 😎
{
"compilerOptions": {
// skip
"paths": {
"@src/*": ["./src/*"]
}
}
}
By setting the paths
configuration to the different paths we need, the code above looks cleaner 🙌
import { x } from '@src/path/to/x';
// code ...
This is the main configuration for paths works, typescript will compile this with successful because the compiler can resolve those paths. But when we run the project with node, ts-node, ts-node-dev, etc, it will fail, and that's due to the nodejs module resolution, it just looks in the node_modules
folder and doesn't find the modules which we already specified by paths in tsconfig
.
But no worries! There is a solution 😎, tsconfig-paths fixes that for us, solving the specified paths.
First we need to install the package.
yarn add -D tsconfig-paths
After this just update the package.json
script
{
"scripts": {
"dev": "ts-node-dev --respawn --transpile-only -r tsconfig-paths/register index.ts"
}
}
And that's it! Works ✨! You can add more paths as much as you want! 💪
I hope this post has been helpful!
You can follow me in my github profile 😃
Thank you for reading this post! Happy coding! 💻
Top comments (0)