DEV Community

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

Posted on • Edited on

12 1

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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay