Skip to content

Commit a83ce7c

Browse files
committed
Add Set Path Alias For Cleaner Imports as a TypeScript TIL
1 parent a61a22f commit a83ce7c

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1376 TILs and counting..._
13+
_1377 TILs and counting..._
1414

1515
---
1616

@@ -1278,6 +1278,7 @@ _1376 TILs and counting..._
12781278
- [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md)
12791279
- [Narrow The Type Of An Array To Its Values](typescript/narrow-the-type-of-an-array-to-its-values.md)
12801280
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
1281+
- [Set Path Alias For Cleaner Imports](typescript/set-path-alias-for-cleaner-imports.md)
12811282
- [Type Narrowing With Const VS Let Strings](typescript/type-narrowing-with-const-vs-let-strings.md)
12821283
- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md)
12831284
- [Type Promise Results With The Awaited Type](typescript/type-promise-results-with-the-awaited-type.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Set Path Alias For Cleaner Imports
2+
3+
In the `tsconfig.json` file of a TypeScript project, there are a bunch of
4+
compiler options that you can specify. One of those compiler options is
5+
`paths`. This is an object that can map path aliases to directories in your
6+
project.
7+
8+
In projects where nested files are importing modules from other parts of the
9+
file tree, you can end up with cluttered imports like this:
10+
11+
```typescript
12+
import { prisma } from '../../server/db.server'
13+
import { List } from '../../components/list'
14+
```
15+
16+
By setting a path alias in your `tsconfig.json` file, like so, you can tidy
17+
these up:
18+
19+
```json
20+
{
21+
"compilerOptions": {
22+
"paths": {
23+
"~/*": ["./app/*"]
24+
}
25+
}
26+
}
27+
```
28+
29+
Now I can write any import such that it anchors to the `app` directory with
30+
`~`.
31+
32+
```typescript
33+
import { prisma } from '~/server/db.server'
34+
import { List } from '~/components/list'
35+
```
36+
37+
I prefer a single path alias if I can get away with it, but you can [add
38+
several](https://learn.saleor.io/setup/typescript-path-aliases/) to suit your
39+
project if you'd like.
40+
41+
[source](https://www.typescriptlang.org/tsconfig#paths)

0 commit comments

Comments
 (0)