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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay