1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

shadcn/ui をインストールする方法(React・JavaScript・Vite)

Posted at

1. 背景

Reactを利用してフロントエンドの開発をすることを決め、開発効率を上げるライブラリーについて調べていたところ、Tailwindcssをベースに作られたUIコンポーネント shadcn/ui(シャドシーエヌ・ユーアイ)に出会いました。shadcn/ui の公式ドキュメントに従いインストールを進めようと試みましたが、ドキュメントにはTypeScriptのプロジェクトが前提で記されていまいした。私と同様にReactで shadcn/ui を利用したいという方に向けて、JavaScriptの環境下でのインストール方法について調べて分かった方法を以下に記します。
※ 以下の手順は、Vite+React のプロジェクトが既に出来上がっていることを前提にしております。

2. 導入手順

2.1. Tailwind CSS をインスール

ターミナルを立ち上げ、以下のコマンドを実行して Tailwind CSS をインストールします。

bash
yarn add tailwindcss @tailwindcss/vite

2.2. index.css を編集

index.cssの内容を全て削除し、以下に置き換えます。

index.css
@import "tailwindcss";

2.3. jsconfig.json を作成

プロジェクトフォルダの直下にjsconfig.json作成して、以下の様に記述します。

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

2.4. vite.config.js を編集

vite.config.js を編集する前に、以下のコマンドを実行します。

bash
yarn add -D @types/node

vite.config.js を以下に置き換えます。

vite.config.js
import path from "path"
import tailwindcss from "@tailwindcss/vite"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"

// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), tailwindcss()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
})

2.5. CLIの実行

以下のコマンドを実行して、shadcnプロジェクトをセットアップします。実行するとベースカラーを尋ねられるので、適切なものを選択します。
※ 特にこだわりのない人はNeutural を選択

bash
npx shadcn@latest init

2.6. コンポーネントの追加

使用するUIコンポーネントを追加します。以後、必要なコンポネントがあれば shadcn/ui のドキュメントからコマンドを参照して追加します。
※ ここでは、Buttonのコンポーネントを追加します。

bash
npx shadcn@latest add button
src/App.tsx
import { Button } from "@/components/ui/button"
 
function App() {
  return (
    <div className="flex flex-col items-center justify-center min-h-svh">
      <Button>Click me</Button>
    </div>
  )
}
 
export default App

上記のようにAppファイルを書き換えると、以下の様に追加したボタンが表示されます。

image.png

3. 参考文献

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?