I have a NX/vite based monorepo and want to use path alias to avoid long relative imports.
I configured my tsconfig.json for each packages and then installed the vite plugin tsconfigPaths() for reading paths from tsconfig.json.
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"@components/*": ["components/*"],
"@constants/*": ["constants/*"],
"@pages/*": ["pages/*"]
}
},
...
}
Screenshot on the configuraton of nxViteTsPaths and tsconfigPaths plugins
On Nx's official document for configuring vite https://nx.dev/recipes/vite/configure-vite, they required to use nxViteTsPaths() plugin, but I failed to find enough doc or source code from https://nx.dev/plugin-registry.
Could anyone share insights on what additional functionality this nxViteTsPaths() does?
The key difference lies in monorepo awareness.
vite-tsconfig-paths (i.e., tsconfigPaths() from vite-tsconfig-paths)
Reads path aliases from the nearest tsconfig.json.
Works fine for simple or single-project setups.
May not resolve paths across multiple libraries in an Nx monorepo.
Doesn’t understand Nx’s project graph or workspaces layout.
nxViteTsPaths() (from @nx/vite/plugins/nx-tsconfig-paths)
Specifically designed for Nx monorepos.
Fully integrates with Nx’s project graph.
Resolves aliases declared in your root tsconfig.base.json and project-specific tsconfigs.
Can resolve aliases for any library or app in the workspace, not just local ones.
How to use it
Make sure you’ve installed @nx/vite, and then in your vite.config.ts:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths';
export default defineConfig({
plugins: [
nxViteTsPaths(),
react(),
],
});
Make sure your tsconfig.base.json contains the path aliases:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@shared-ui/*": ["libs/shared-ui/src/*"]
}
}
}
You shouldn’t need both plugins. If you’re using Nx, just stick with nxViteTsPaths()—it covers all the ground vite-tsconfig-paths does, and more, with better support for Nx-specific setups.