DEV Community

Cover image for How to set up aliases for module imports in TypeScript (Angular)
Dino Dujmovic
Dino Dujmovic

Posted on • Updated on

How to set up aliases for module imports in TypeScript (Angular)

Aliases can be helpful to simplify imports and make the code more readable and maintainable, especially in larger projects with many nested directories.

So, instead of importing files using relative file paths (using the sequence of characters "../../../") that could be looking something like this (or worse):

import { environment } from "../../environment";
import { TTime } from "../../../core/models/types/TTime";
import { GetMovies } from "../../../store/movies/movies.action";
import { MoviesModule } from "../../pages/movies/movies.module"
Enter fullscreen mode Exit fullscreen mode

We can have something more beautiful and consistent like:

import { environment } from "@environment/environment";
import { TTime } from "@core/models/types/TTime";
import { GetMovies } from "@store/movies/movies.action";
import { MoviesModule } from "@pages/movies/movies.module"
Enter fullscreen mode Exit fullscreen mode

We can achieve this by adding paths property to our tsconfig.json (usually placed in root folder of our TS projects).

tsconfig.json (Angular project example):

{
    "compilerOptions": {
        "paths": {
            "@environment/*": [
                "./src/environments/*"
            ],
            "@pages/*": [
                "./src/app/pages/*"
            ],
            "@store/*": [
                "./src/app/store/*"
            ],
            "@core/*": [
                "./src/app/core/*"
            ],
            "@shared/*": [
                "./src/app/shared/*"
            ]
        },
} 
Enter fullscreen mode Exit fullscreen mode

The aliases are defined using the paths option, which maps each alias to one or more file paths.


VSCode possible problem

If config doesn't work as expected in VSCode add

"typescript.preferences.importModuleSpecifier": "non-relative"

to your VSCode settings.json.

Top comments (0)