File tree 2 files changed +43
-1
lines changed
2 files changed +43
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1376 TILs and counting..._
13
+ _ 1377 TILs and counting..._
14
14
15
15
---
16
16
@@ -1278,6 +1278,7 @@ _1376 TILs and counting..._
1278
1278
- [ Interfaces With The Same Name Are Merged] ( typescript/interfaces-with-the-same-name-are-merged.md )
1279
1279
- [ Narrow The Type Of An Array To Its Values] ( typescript/narrow-the-type-of-an-array-to-its-values.md )
1280
1280
- [ 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 )
1281
1282
- [ Type Narrowing With Const VS Let Strings] ( typescript/type-narrowing-with-const-vs-let-strings.md )
1282
1283
- [ Type Narrowing With Similarly Shaped Objects] ( typescript/type-narrowing-with-similarly-shaped-objects.md )
1283
1284
- [ Type Promise Results With The Awaited Type] ( typescript/type-promise-results-with-the-awaited-type.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments