0%

typescript-paths

Introduction

paths is a TypeScript configuration option that allows you to map a module name to a path. This is useful when you have a complex project structure and you want to avoid long relative paths.

Config

Add the following configuration to your tsconfig.json file.

1
2
3
4
5
6
7
8
9
10
{
"compilerOptions": {
"baseUrl": ".", // This must be specified.
"paths": {
"@app/*": ["src/app/*"],
"@shared/*": ["src/shared/*"],
"@utils/*": ["src/app/service/others/utils/*"],
}
}
}

baseUrl

The baseUrl option specifies the base directory to resolve non-relative module names. This must be specified when using absolute path. In above example, baseUrl is set to .(this is the same directory with tsconfig.json) which means the base directory is the root directory of the project. take “@app/*” as an example, when you import a module like import {AppComponent} from '@app/app.component', TypeScript will look for the module in the src/app directory.

if you don’t specify baseUrl, You must use relative paths to import modules. For example:

1
2
3
4
5
6
7
8
9
{
"compilerOptions": {
"paths": {
"@app/*": ["./src/app/*"],
"@shared/*": ["./src/shared/*"],
"@utils/*": ["./src/app/service/others/utils/*"],
}
}
}

Usage

Suppose you have a file stringUtils.ts in the src/app/service/others/utils directory. You can import it like this:

1
import {stringUtils} from '@utils/stringUtils';

You don’t need to write the long relative path. TypeScript will automatically resolve the path based on the configuration in tsconfig.json.

Nx mono repo

When using Nx mono repo to create multiple app/libs, be careful when you use paths in tsconfig.json. You need to add the paths configuration to the tsconfig.base.json file in the root directory of the Nx workspace. and every tsconfig.json in each app/lib should extend tsconfig.base.json.

1
2
3
4
5
6
7
8
9
// tsconfig.json in app or lib
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": []
},
"include": ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"]
}
1
2
3
4
5
6
7
8
9
10
11
// tsconfig.base.json
{
"compilerOptions": {
"baseUrl": ".", // This must be specified.
"paths": {
"@app/*": ["apps/*"],
"@shared/*": ["libs/shared/*"],
"@utils/*": ["libs/shared/utils/*"],
}
}
}

Note that tsconfig.json in app/lib has higher priority than tsconfig.base.json. If you have same configuration in both files, the configuration in tsconfig.json will override the configuration in tsconfig.base.json. this will cause some path not found sometimes.

So,

  • Only add paths configuration to tsconfig.base.json file in the root directory of Nx workspace.
  • Do not add paths configuration to any other tsconfig.json file in the app/lib.

References

https://www.typescriptlang.org/tsconfig/#paths