🐥

shadcn/uiエラー対応とセットアップ方法

2025/01/09に公開

この記事は、エンジニア初心者である筆者が、自身の学びを記録する目的でまとめた内容です。できる限り調査し正確に執筆していますが、万が一誤りがございましたら、どうかご容赦ください。

今回は、Tailwind CSS と Vite をセットアップした状態で、shadcn/ui をインストールした際に発生したエラーについて解決方法をまとめました。

shadcnをインストールする

npx shadcn@latest init

エラー

✔ Preflight checks.
✔ Verifying framework. Found Vite.
✔ Validating Tailwind CSS.
✖ Validating import alias.

No import alias found in your tsconfig.json file.
Visit https://ui.shadcn.com/docs/installation/vite to learn how to set an import alias.

ということで、

tsconfig.json を編集する

Viteの現在のバージョンでは、TypeScript 構成が3つのファイルに分割されており、そのうち2つを編集する必要がありました。

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

tsconfig.app.jsonファイルを編集する

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

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"),
    },
  },
})

CLIを実行する

npx shadcn@latest init

設定するためにいくつかの質問が表示されるので答えていきます。

Success! Project initialization completed.

Buttonコンポーネントをプロジェクトに追加してみる

npx shadcn@latest add button

componentにbutton.tsxが追加されました。
Appにshadcn/uiのボタンを追加し動作確認をしてみます。

App.tsx
<div className="card">
        <Button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </Button>
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
</div>


↓↓

成功しました。

Discussion