目次
Astro.jsでshadcn/uiを使ってみたので備忘録。
shadcn/uiは、使いやすくスタイリッシュなUIコンポーネントを提供するReactライブラリです。以下の手順に従って、Astro.jsでshadcn/uiを利用できるようにしましょう。
Astroプロジェクトの作成
まず、Astroプロジェクトを作成します。
以下のコマンドを実行して新しいプロジェクトを作成してください。
npm create astro@latest
プロジェクトの設定
プロジェクト作成時にいくつかの質問がされます。以下のように回答してください。
- Where should we create your new project?
./your-app-name
- How would you like to start your new project? Choose a template
- Do you plan to write TypeScript? Yes
- How strict should TypeScript be? Strict
- Install dependencies? Yes
- Initialize a new git repository? (optional) Yes/No
Reactの追加
次に、Astro CLIを使用してReactをプロジェクトに追加します。
npx astro add react
インストール時に表示されるすべての質問に「Yes」と回答してください。
Tailwind CSSの追加
次に、Tailwind CSSをプロジェクトに追加します。
npx astro add tailwind
プロジェクトのsrc
フォルダ内にstyles/globals.css
というファイルを作成し、以下の内容を追加します。
@tailwind base;
@tailwind components;
@tailwind utilities;
グローバルスタイルのインポート
src/pages/index.astro
ファイルに、先ほど作成したglobals.css
ファイルをインポートします。
---
import '@/styles/globals.css'
---
astro.config.mjs
の更新
Tailwindの基本スタイルが二重に適用されないように、astro.config.mjs
ファイルを更新します。TailwindプラグインのapplyBaseStyles
オプションをfalse
に設定します。
import { defineConfig } from 'astro/config';
import tailwind from '@astrojs/tailwind';
export default defineConfig({
integrations: [
tailwind({
applyBaseStyles: false,
}),
],
});
tsconfig.json
の編集
tsconfig.json
ファイルに以下のコードを追加し、パスを解決できるようにします。
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}
shadcn/uiの初期設定
次に、shadcn/uiをプロジェクトに設定します。CLIを使用して初期設定を行います。
pnpm dlx shadcn@latest init
コンポーネントの追加
shadcn/uiからコンポーネントを追加します。例えば、ボタンコンポーネントを追加するには、以下のコマンドを実行します。
pnpm dlx shadcn@latest add button
このコマンドでボタンコンポーネントがプロジェクトに追加されます。
コンポーネントの使用
追加したボタンコンポーネントを使用するには、以下のようにインポートします。
---
import { Button } from "@/components/ui/button"
---
<html lang="en">
<head>
<title>Astro with shadcn/ui</title>
</head>
<body>
<Button>Hello World</Button>
</body>
</html>
これで、Astro.jsとshadcn/uiを使ったプロジェクトが作成できました。