DEV Community

Cover image for How to add alias in typescript
Davejs136
Davejs136

Posted on

How to add alias in typescript

When we are working on development projects sometimes we have a long path of imports 😬

import { x } from '../../../../path/to/x';

// code ...
Enter fullscreen mode Exit fullscreen mode

To reduce these long paths, TypeScript provides us with paths in tsconfig.json to add path aliases 😎

{
  "compilerOptions": {
    // skip
    "paths": {
      "@src/*": ["./src/*"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

By setting the paths configuration to the different paths we need, the code above looks cleaner 🙌

import { x } from '@src/path/to/x';

// code ...
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

After this just update the package.json script

{
  "scripts": {
    "dev": "ts-node-dev --respawn --transpile-only -r tsconfig-paths/register index.ts"
  }
}
Enter fullscreen mode Exit fullscreen mode

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! 💻

Latest comments (0)