HOW TO: simplify Angular TypeScript imports by using absolute paths

Recently I’ve been working on a large Angular project with deeply nested folders and all the import paths were referenced relatively and they looked like this:

import { HelloWorldComponent } from '../../../../shared/components/hello-world/hello-world.component';

This imports are too long, hard to maintain and very annoying in large projects. Just imagine how much work is needed to update each path when moving a file that is referenced in 50+ locations (find and replace is not a solution here 🙂 ).

The good news is that TypeScript can be configured to use custom namespaces to point to specific paths by changing two compiler options inside tsconfig.json file:

  • baseUrl – base directory to resolve non-relative module names.
  • paths – list of mapping entries for module names to locations relative to the baseUrl

Here is the default content for tsconfig.json with two paths configured:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@scb/*": ["src/app/*"],
      "@scb-shared/*": ["src/shared/*"],
    }
    ...
  }
}

With this setting, the long import given as an example, will turn into:

import { HelloWorldComponent } from '@scb-shared/components/hello-world/hello-world.component';

I’ve ended up changing all the imports to absolute imports in the project I was writing about, it was a tedious work but it saved me a lot of pain for the rest of the time spent on that project. It’s great to be able to move files around and not to bother about updating paths everywhere.

Let me know if you like this productivity tip 🙂 .

2 Comments

  1. Robert Pergl said:

    Hi, this is great, thanks! However I cannot make it work with webpack + ts-loader, it complains “module not found” for every module imported like that. Any tip?

    July 16, 2020
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *