Skip to content

content(typescript): use path mappings to simplify imports #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions content/typescript/use_path_mappings_to_simplify_imports.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
title: use path mappings to simplify imports
author:
name: Bo Vandersteene
url: https://medium.com/@bo.vandersteene
---

# Problem
An application, can have a lot of components, modules, ... . Everywhere we want to use a dependency, we need to import it.

If we take a look at our imports in a file, then you discover imports, that have long names and/or a lot of imports with the same functionality
```ts
import { AuthenticationModule } '../.../../../../authentication/src/lib/authentication.module';
import { AuhtenticationAction } '../.../../../../authentication/src/lib/store/authentication.actions';
import { AuhtenticationState } '../.../../../../authentication/src/lib/store/authentication.state';
```
And finally if we want to refactor our authentication lib, we need to adjust all our imports.


# Solution

In TypeScript, we want to take advantage of module resolution. This is the process the compiler uses to figure out what an import refers to.

Create a public_api.ts file that expose all options

```ts
export * from './lib/authentication.module';
export * from './lib/store/authentication.actions';
export * from './lib/store/authentication.state';
```
This file should be linked in the tsconfig.json file
```ts
{
...
"paths": {
"@my/authentication": ["projects/authentication/src/public_api.ts"],
}
}
}

```
use the import
```ts
import { AuthenticationModule } from '@my/authentication'
```

The import is now more readable.

Another advantage of this usage: when we refactor our authentication module, there is only the need to adjust our public_api.ts file