Astro.jsとshadcn/uiを使ったプロジェクトの始め方

公開日:
目次

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? ./アプリの名前
  • How would you like to start your new project? テンプレートを選ぶ(A basic, minimal starter)
  • Install dependencies? 依存関係をインストールするか(Yes)
  • Initialize a new git repository? Gitを始めるか(Yes)

Reactの追加

次に、Astro CLIを使用してReactをプロジェクトに追加します。

npx astro add react

インストール時に表示されるすべての質問に「Yes」と回答してください。

Tailwind CSSの追加

次に、Tailwind CSSをプロジェクトに追加します。

先ほど作成したastroプロジェクトに移動して下記を実行します。

npx astro add tailwind

インストール時に表示されるすべての質問に「Yes」と回答してください。

グローバルスタイルのインポート

src/layouts/Layouts.astroファイルに、先ほど作成したglobals.cssファイルをインポートします。

Layouts.astro
---
import '@/styles/globals.css';
---

astro.config.mjsの更新

Tailwindの基本スタイルが二重に適用されないように、astro.config.mjsファイルを更新します。

TailwindプラグインのapplyBaseStylesオプションをfalseに設定します。

astro.config.mjs
// @ts-check
import { defineConfig } from 'astro/config';
import tailwindcss from '@tailwindcss/vite';
import react from '@astrojs/react';

// https://astro.build/config
export default defineConfig({
  vite: {
    plugins: [
      tailwindcss(
+       {
+         applyBaseStyles: false,
+       }
      ),
    ],
  },
  integrations: [react()]
});

tsconfig.jsonの編集

tsconfig.jsonファイルに以下のコードを追加し、パスを解決できるようにします。

{
  "extends": "astro/tsconfigs/strict",
  "include": [
    ".astro/types.d.ts",
    "**/*"
  ],
  "exclude": [
    "dist"
  ],
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "react",
+   "baseUrl": ".",
+   "paths": {
+     "@/*": [
+       "./src/*"
+     ]
    }
  }
}

shadcn/uiの初期設定

次に、shadcn/uiをプロジェクトに設定します。CLIを使用して初期設定を行います。

npx shadcn@latest init

コンポーネントの追加

shadcn/uiからコンポーネントを追加します。例えば、ボタンコンポーネントを追加するには、以下のコマンドを実行します。

npx 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を使ったプロジェクトが作成できました。

参考