Search code examples
reactjstypescriptviteshadcnui

Import aliasing won't work in Vite (React, Typescript) boilerplate


I installed shadcn/ui into my vite boilerplate following the docs. But the compiler didn't seem to recognize the aliasing. Note: typescript has more than one config file, namely: tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Initially, the "compilerOptions" option key wasn't defined in the original tsconfig but in the other 2 files instead. So I duplicated it to include the alias config in the original file.

// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "files": [],
  "references": [
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.node.json"
    }
  ]
}

// vite.config.ts
import path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});

enter image description here


Solution

  • The problem was apparently in the tsconfig files. The paths option had to be set on both tsconfig.app.json file and plain tsconfig.json so that the ts compiler resolves the path correcly and for the shadcnui to install the components in the right directory based on the configurations of the plain tsconfig.

    //tsconfig.json
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["./src/*"]
        }
      },
      "files": [],
      "references": [
        {
          "path": "./tsconfig.app.json"
        },
        {
          "path": "./tsconfig.node.json"
        }
      ]
    }
    
    // tsconfig.app.json
        {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["./src/*"]
        }
      },
      "include": ["src"]
    }