htmlreactjsuser-interfacetailwind-cssvite

How do I solve the error "Failed to resolve import "src/lib/utils" from ... Does the file exist?"


I am a beginner in react and am trying to follow this tutorial (https://www.youtube.com/watch?v=_W3R2VwRyF4) on youtube. I am trying to test out the button component I am building, but I keep getting an error message:

"[plugin:vite:import-analysis] Failed to resolve import "src/lib/utils" from "src/components/ui/button.tsx". Does the file exist?"

For reference, I am using vite + react + tailwind.

I have attached a screen shot with the rest of the error message.

This is the code button.tsx:

import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "src/lib/utils"

This is the code in utils.ts:

import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

I am importing the button component from @/components/ui/button to SignupForm.tsx with this command:

import { Button } from "@/components/ui/button"

I deleted "@", but when I remove it from the path "@/components/ui/button", I get the error: "Cannot find module 'components/ui/button' or its corresponding type declarations."

I am assuming that it is a syntax OR a path error I am overlooking. Does anyone have any thoughts? Thank you.


Solution

  • @/ here is a path alias, make sure to configure TypeScript and Vite to resolve the pathes:

    If you'r using TypeScript update tsconfig.json to add:

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

    And vite.config.ts:

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

    You'll also need to install @types/node to type path:

    npm i -D @types/node
    

    Then whenever you import something from @/path/to/whatever the compiler will resolve it to ./src/path/to/whatever.

    I deleted "@", but when I remove it from the path "@/components/ui/button", I get the error: "Cannot find module 'components/ui/button' or its corresponding type declarations."

    Make sure to revert this change, or to run again:

    npx shadcn-ui init
    npx shadcn-ui add button