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! πŸ’»

Oldest comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!