Skip to content

typescript: path aliases #124

Open
Open

Description

@papsavas

Problem

Many imports are relative which leads to the following code:

import { useMyHook } from "../../../hooks/myHook"

Solution

Path aliases allow you to specify certain path areas for cleaner imports

//tsconfig.json

{
  "compilerOptions:"{
   "paths": {
      "@hooks/*": ["./src/hooks/*"], 
   }
  }
}
import { useMyHook } from "@hooks/myHook"

Note

  • @ is arbitrary. Some projects use ~

Note

you can also alias as follows

{
  "compilerOptions:"{
   "paths": {
      "@/*": ["./src/*"], 
   }
  }
}
import { useMyHook } from "@/hooks/myHook"

Important

if a combination of both aliasing root and sub-paths is decided, make sure to put inner paths above their outer in tsconfig.ts to receive shorter path priority when auto-importing

Activity

  1. papsavas commented on May 4, 2024

    @papsavas
    ContributorAuthor

    i would suggest such feature is accompanied by the deletion of hooks/index.ts since it's one more file to maintain when adding new hooks. Instead each hook will be imported as:

    import { useDepartments } from "@hooks/useDepartments"
  2. added
    p.MediumPriority: Medium
    frontendThis issue is related to frontend
    qualityThis issue is related to quality
    on May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    frontendThis issue is related to frontendp.MediumPriority: MediumqualityThis issue is related to quality

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions