TypeScript Paths

Oct 18, 2018 20:05 · 197 words · 1 minute read TypeScript Angular Webpack

First tech post, yay!

Writing code in Angular using Visual Studio Code is a real pleasure: syntax highlight, autocompletion, git integration, auto import, etc. but from time to time you find some odd routes in your imports that can be improved using the tsconfig.json file.

Let’s imagine you want to import a component that is far in the folder structure, you will end with something like:

@import "../../../../../modules/shared/components/date-time/date-time.component";

If you use an absolute path the result is slightly better:

@import "src/app/modules/shared/components/date-time/date-time.component"

Now, TypeScript provides a solution, inside tsconfig.json file you have a “path” option that allows to declaring “path aliases”, this way you can short them significantly. The route provided inside the path is relative to the baseUrl configuration of the same file.

{
  "compilerOptions": {
  ..
  "baseUrl": "src",
  "paths": [
    "@shared-module/*": [
      "app/modules/shared/*"
    ],
  ]
  }
}

From now on, in your components you can import files from shared modules this way:

@import "@shared-module/components/date-time/date-time.component"

Final note, this feature depends on your build tool, you may need to modify it. In webpack 2, for example, you will need to add the new path to the resolve alias array in the webpack.config.js:

alias: {
  '@shared-module': gpath.resolve(\_\_dirname, `../src/app/modules/shared`),
}
tweet Share