The aliases (shortened paths) need to be set in both the root tsconfig.base.json and vite.config.ts files.
- vite.config.ts will be used at compile time to tell the vite compiler where your files are located. Its critical that both are set up correctly.
- tsconfig is required so typescript knows where the file can be found for intellisense and automatic imports.
The way tsconfig.json files extend one another can cause confusion when setting up path aliases in monorepo projects. Therefore its critical we add out aliases to the tsconfig.base.json file in the root of the mono-repo, not in the tsconfig.json file found in individual apps.
The "extends" property of a tsconfig.json file is poorly named. The properties of the file being extended (often tsconfig.base.json) are overridden not extended.
To add custom path aliases the following pattern can be used.
1. Add the path alias to the tsconfig.base.json file in the root of the monorepo.
{
"compilerOptions": {
"paths": {
"@<project-name>/<import-alias>": [
"apps/<app-name>/<path-to-dir>"
]
}
}
}
-
@<project-name>/<import-alias>
is the shortened, readable import path you will use in your files. eg:import {FileName} from '@<project-name>/<import-alias>'
-
apps/<app-name>/<path-to-dir>
is the directory that you wish to alias (relative to the tsconfig.base.json file location)
the @ symbol is not required, but it is the standard pattern to prepend the aliases when using nx.
2. Add a path alias to the vite.config.ts file inside the app(s) you will be using the alias.
import * as path from 'node:path';
export default defineConfig({
resolve: {
alias: {
'@<project-name>/<import-alias>': `${path.resolve(__dirname, './<path-to-dir>')}`
},
}
});
-
@<project-name>/<import-alias>
is the same alias as used in the tsconfig file and should match exactly. -
<path-to-dir>
is the directory which you wish to alias. NB: this is relative to the location of the vite.config.ts file so the path will be different from the one used in tsconfig.base.json. usually./src/path/to/directory
.
This setup should allow you to user shortened aliases, which act as absolute imports in your Vite-React Typescript projects.
Goodbye import {filename} from '../../../../relative/import/that/breaks/all/the/time'
Top comments (0)