vitealiasnx-monorepo

What does Nx plugin nxViteTsPaths() do exactly? Especially in addition to vite's tsconfigPaths() plugin


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?


Solution

  • The key difference lies in monorepo awareness.

    vite-tsconfig-paths (i.e., tsconfigPaths() from vite-tsconfig-paths)

    nxViteTsPaths() (from @nx/vite/plugins/nx-tsconfig-paths)

    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.