概要
shandcn/ui は、React プロジェクトに簡単に統合できる美しい UI コンポーネントを提供するライブラリです。 この記事では、Vite で作成した React プロジェクトに shandcn/ui ライブラリを導入する方法について解説します。
手順
インストール方法はバージョン更新により変更される場合があります。最新の情報は公式ページを参照してください。
1. プロジェクトを作成する
まず、Vite を使用して React プロジェクトを作成します。以下のコマンドを実行して、プロジェクトを新規に作成します。
$ npm create vite@latest
√ Project name: ... react-shadcnui
√ Select a framework: » React
√ Select a variant: » TypeScript + SWC
上記の手順により、TypeScript と SWC (高速な JavaScript/TypeScript コンパイラ) を利用する設定で React プロジェクトが初期化されます。 次に、プロジェクトディレクトリに移動して依存関係をインストールします。
cd react-shadcnui
npm install
2. Tailwind をインストールする
以下のコマンドを実行して Tailwind CSS と @tailwindcss/vite をインストールします。
npm install tailwindcss @tailwindcss/vite
3. グローバル CSS の設定
次に、src/index.css
ファイルに以下の内容を記述します。
@import "tailwindcss";
これにより、Tailwind CSS のスタイルがプロジェクト全体で有効になります。
4. Typescript のコンパイラの設定
tsconfig.json
および tsconfig.app.json
に以下の設定を追記します。
- モジュールのルートディレクトリをプロジェクトのルートディレクトリに設定する
@/path/to/file
が/src/path/to/file
を指すようにエイリアスを設定する
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}
5. vite.config.ts
を設定する
vite.config.ts
を以下のように設定します。
# Node.js の型定義をインストール
npm install -D @types/node
import path from "path";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react-swc";
import { defineConfig } from "vite";
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
6. shandcn/ui の設定
以下のコマンドで shandcn/ui の設定を行います。
$ npx shadcn@latest init
✔ Preflight checks.
✔ Verifying framework. Found Vite.
✔ Validating Tailwind CSS config. Found v4.
✔ Validating import alias.
√ Which color would you like to use as the base color? » Neutral
✔ Writing components.json.
✔ Checking registry.
✔ Updating src\index.css
Installing dependencies.
It looks like you are using React 19.
Some packages may fail to install due to peer dependency issues in npm (see https://ui.shadcn.com/react-19).
√ How would you like to proceed? » Use --force
✔ Installing dependencies.
✔ Created 1 file:
- src\lib\utils.ts
Success! Project initialization completed.
You may now add components.
shadcn/ui の使い方
1. コンポーネントをインストールする
Introduction – shadcn/ui の Components の欄から使用したいコンポーネントのページを参照すると、各ページにそのコンポーネントをインストールするための方法が記載されています。 例えば、Button コンポーネントの場合、以下のコマンドでインストールできます。
npx shadcn@latest add button
2. コンポーネントを使用する
基本的には、src/components/ui
以下にインストールされるので、@/components/ui/button
からインポートして使用します。
import { Button } from "@/components/ui/button";
function App() {
return (
<>
<Button>クリック</Button>
</>
);
}
export default App;
カスタマイズ
デフォルトの仕様からカスタマイズしたい場合、以下の方法があります。
@/components/ui/button.tsx
を編集する- shadcn/ui のベースカラーが記載された
src/index.css
を編集する className
で指定する
コメント