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 | { |
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 | { |
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 | // tsconfig.json in app or lib |
1 | // tsconfig.base.json |
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
addpaths
configuration totsconfig.base.json
file in the root directory of Nx workspace.Do not
addpaths
configuration to any othertsconfig.json
file in the app/lib.