Search code examples
typescriptvite

How do I use Typescript path aliases in Vite?


How do I set up and use typescript path aliases like @/shared/types in a Vite project? I'm getting this error: Failed to resolve import "@/shared/types"

Here's a part of my tsconfig.json:

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

Solution

  • You need to configure both vite.config.ts and tsconfig.json files. Your tsconfig.json looks correct, but inside the vite.config.ts file you need to import the path module and map the path aliases to absolute paths using something like path.resolve(). And make sure to remove any asterisk characters (*)!

    For example, if your tsconfig.json looks like this:

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

    Then this is how you should configure vite.config.ts:

    import { defineConfig } from "vite";
    import react from "@vitejs/plugin-react-swc";
    import path from "path";
    
    export default defineConfig({
      resolve: {
        alias: {
          "@": path.resolve(__dirname, "../"),
          "@server": path.resolve(__dirname, "../server/src"),
        },
      },
      plugins: [react()],
    });
    

    You may need to import react from '@vitejs/plugin-react', depending on which options you chose when creating your app.