Appearance
概要
Vite で構築した React プロジェクトに Shadcn を追加する手順を紹介します。
- Tailwind CSS を追加する
- tsconfig.json と tsconfig.app.json の設定を変更する
- vite.config.ts の設定を変更する
- Shadcn を追加する
- Shadcn のコンポーネントを追加してみる
Vite で React プロジェクトを構築している前提になりますので、Vite で React プロジェクトを構築していない場合は、以下の記事を参考にしてください。
Tailwind CSS を追加する
以下のコマンドを実行して、Tailwind CSS をインストールします。
bash
npm install -D tailwindcss postcss autoprefixer
以下のコマンドを実行して、Tailwind CSS の設定ファイルを作成します。
bash
npx tailwindcss init -p
tailwind.config.js
ファイルを開いて、以下のように設定します。
js
/** @type {import('tailwindcss').Config} */
export default {
darkMode: ["class"],
content: ["./src/**/*.tsx"],
theme: {
extend: {},
},
src/index.css
ファイルに追記します。
css
@tailwind base;
@tailwind components;
@tailwind utilities;
tsconfig.json と tsconfig.app.json の設定を変更する
以下のように tsconfig.json
と tsconfig.app.json
の設定を変更します。
json
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
json
{
"compilerOptions": {
// ...
"baseUrl": "./src",
"paths": {
"@/*": ["*"]
}
},
"include": ["src"]
}
vite.config.ts の設定を変更する
以下のコマンドを実行して、@types/node
をインストールします。
次の手順で vite.config.ts
の設定を変更します。
bash
npm i -D @types/node
以下のように vite.config.ts
の設定を変更します。
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"),
},
},
});
Shadcn を追加する
以下のコマンドを実行して、Shadcn をプロジェクトに追加します。
bash
npx shadcn@latest init
質問に答えて、Shadcn を追加します。
bash
Which style would you like to use? › New York
Which color would you like to use as base color? › Zinc
Do you want to use CSS variables for colors? › no / yes
問題なく追加できれば、components.json が生成され、src/components と src/lib ディレクトリにコンポーネントが追加されます。
Shadcn のコンポーネントを追加してみる
以下のコマンドを実行して、Shadcn のコンポーネントを追加します。
bash
npx shadcn@latest add button
コンポーネントにButton
を追加してみます。
tsx
import { Button } from "@/components";
export default function App() {
return (
<div>
<Button>Click me</Button>
</div>
);
}
以上で、Vite で構築した React プロジェクトに Shadcn を追加する手順を紹介しました。
まとめ
Vite で構築した React プロジェクトに Shadcn を追加する手順を紹介しました。 React プロジェクトに Shadcn を追加する際に参考になると幸いです。