Skip to main content

Absolute Imports and Module Path Aliases

MBC CQRS Serverless framework has in-built support for the "paths" and "baseUrl" options of tsconfig.json file.

These options allow you to alias project directories to absolute paths, making it easier to import modules. For example:

// before
import { Role } from "../../../auth/role.enum";

// after
import { Role } from "@/auth/role.enum";

Absolute Imports

The baseUrl configuration option allows you to import directly from the root of the project.

An example of this configuration:

tsconfig.json
{
"compilerOptions": {
"baseUrl": "."
},
"include": ["src/*", "src/**/*"]
}

Module Aliases

In addition to configuring the baseUrl path, you can use the "paths" option to create module path aliases. The MBC CQRS Serverless convention maps @/* to src/*:

tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@shared/*": ["src/shared/*"]
}
},
"include": ["src/**/*"]
}

This lets you write clean, refactoring-friendly imports:

// without alias
import { OrderService } from "../../../orders/order.service";

// with alias
import { OrderService } from "@/orders/order.service";

Jest Configuration

TypeScript path aliases must also be registered in Jest so tests resolve the same paths. Add a moduleNameMapper to your jest.config.json:

jest.config.json
{
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1",
"^@shared/(.*)$": "<rootDir>/src/shared/$1"
}
}
info

Keep the moduleNameMapper patterns in sync with the paths entries in tsconfig.json. A missing mapper causes Cannot find module errors only in tests, which can be hard to diagnose.