reactjstypescriptviteconfig

Path aliases without @ in a Vite project


We moved our project to Vite from CRA. While using CRA we used path aliases set in tsconfig:

 "baseUrl": "src",
    "paths": {
      "@*": ["src/*"]
    },

And imports went like this: import Loader from 'components/shared/Loader/Loader'; With the file being at src/components/shared/Loader/Loader.tsx

After moving to Vite I installed vite-tsconfig-paths and used it in vite config by adding tsconfigPaths() to plugins array in the config but the compiler can't resolve the paths.

The only way I managed to solve this is by adding every possible path into an array and iterate over it while adding the paths into alias objects

const paths = [
  "components",
  "Providers",
  "hooks",
  "auth",
  "localConstants",
  "assets",
  "utils",
  "helpers",
  "reducers",
];

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: paths.map((path) => ({
      find: path,
      replacement: fileURLToPath(new URL(`src/${path}`, import.meta.url)),
    })),
  },
});

But obviously this is cumbersome. How can I achieve previous behaviour without having to use @ in my imports?


Solution

  • When we migrated from CRA we used vite-tsconfig-paths. Just install it with

    npm i vite-tsconfig-paths
    

    and add it to vite.config.ts|js

    import tsconfigPaths from "vite-tsconfig-paths";
    
    export default defineConfig(() => {
      return {
        ...,
        plugins: [
          ...,
          tsconfigPaths(),
        ],
      };
    });
    

    and your tsconfig.json:

    {
      "compilerOptions": {
        ...,
        "baseUrl": "src",
        "paths": {
          "*": ["*"]
        }
      }
    }