I'm setting up a React app with Vite and TypeScript, and after installing Shadcn UI using npx shadcn-ui@latest init
, I noticed that the components
folder was created in the root directory instead of inside src
. This setup also configures the @/components
alias.
Given that the components
folder is outside of src
, how should I adjust my Vite configuration to resolve the @/components
alias properly? Additionally, what changes should I make to ensure my imports work correctly with this setup?
Vite Configuration (vite.config.ts
):
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@/components': path.resolve(__dirname, './components'),
'@/lib/utils': path.resolve(__dirname, './lib/utils'),
},
},
});
Shadcn UI Configuration:
`{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "gray",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils"
}
`}
To resolve the issue, I took the following steps:
Here is the updated 'components.json':
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "gray",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "src/components",
"utils": "src/lib/utils"
}
}
Reinitialize Shadcn UI: I ran the following command to reinitialize Shadcn UI:
npx shadcn-ui@latest init
Manually Updated Imports: I updated the import statements in my components to use the correct path. Specifically, I changed:
import { cn } from "@/lib/utils";
After performing these steps, I was able to resolve the issue. While this approach worked for me, I'm unsure if it is the recommended or most effective solution. Any further insights or suggestions would be appreciated.