How to Use Typescript Path Alias in Loopback 4

How to Use Typescript Path Alias in Loopback 4

Post Date : 2022-08-05T15:07:40+07:00

Modified Date : 2022-08-05T15:07:40+07:00

Category: cheatsheet

Tags: typescript

The problem

In Node.js (or TS/JS in general) you can import single modules into your code. This might look the following:

import { Example } from "../example/model";
import { Article } from "../article/model";

The problem we have here is that the deeper your project tree is the more ‘../’ are required to access modules in higher layers. Actually, this doesn’t look very beautiful to be honest. Fortunately we can change that.

The solution: path aliases

import { Example } from "@modules/example/model";
import { Article } from "@modules/article/model";

In our case

@modules that maps to ‘./src/modules’

Our tsconfig

"baseUrl": "./src",
"paths": {
    "@modules/*": ["./*"]
}

And run

ts-node -r tsconfig-paths/register src/index.ts

But everything is not pink and you will get this error at run time

node dist/index.js

Error: Cannot find module ‘@modules/example/model’

Why?

Because when you build, it is still keep your alias, so there are 2 ways to allow us to start the application:

  1. Using tsconfig-paths at run time, at start up time, it will map the path alias to your relative paths
node -r tsconfig-paths/register dist/index.js
  1. Replace all relative path in your build with tsc-alias
npm install --save-dev tsc-alias
"build": "lb-tsc --copy-resources && tsc-alias",