open-source-uom / myuom

The myUoM app is a project of the Open Software Team of Applied Informatics, University of Macedonia (https://opensource.uom.gr). It was designed to facilitate students' daily interactions with the university.
https://my.uom.gr
MIT License
26 stars 17 forks source link

typescript: path aliases #124

Open papsavas opened 6 months ago

papsavas commented 6 months ago
  • after #101

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

papsavas commented 6 months ago

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"