概要
Astro で構築した Web アプリに Tailwind CSS を導入する方法の備忘録です。
Astro の公式ドキュメント(英語)にも 導入方法の詳細 はありますし、簡単すぎて書くまでもないかもしれませんが、念のために初心者向けの日本語の要約版として記載します。
「Astro で用意されたコマンドを利用する方法」と「手動で導入する方法」の2種類がありますが、今回は 「astro コマンドを利用して導入する方法」 について解説します。
コマンド利用をすると、手動で導入する場合の手順を「Yes」と答えるだけで全部やってくれます。
何か他のライブラリやプラグインとの兼ね合い等で、手動で導入する理由がなければ、基本はコマンド利用で良いと思います。
手順
コンソールを開き、Asrto のプロジェクト配下(package.json
がある場所)で以下を実行します。
npx astro add tailwind
以下、実行結果。対話式で質問に答えていきます。
✔ Resolving packages...
11:47:36
# Q1. 以下のコマンド実行するけど良い?
Astro will run the following command:
If you skip this step, you can always run it yourself later
╭──────────────────────────────────────────────────────────╮
│ npm install @astrojs/tailwind@^5.1.0 tailwindcss@^3.4.1 │
╰──────────────────────────────────────────────────────────╯
? Continue? › (Y/n)
# 👉 デフォルトが "Y" なので、そのままエンターキーで OK
✔ Continue? … yes
✔ Installing dependencies...
11:47:50
# Q2. xxx?
Astro will generate a minimal ./tailwind.config.mjs file.
? Continue? › (Y/n)
# 👉 そのままエンターキーで OK
✔ Continue? … yes
11:54:59
# Q3. xxx?
Astro will make the following changes to your config file:
╭ astro.config.mjs ───────────────────────────────╮
│ import { defineConfig } from 'astro/config'; │
│ import mdx from '@astrojs/mdx'; │
│ import sitemap from '@astrojs/sitemap'; │
│ │
│ import tailwind from "@astrojs/tailwind"; │
│ │
│ // https://astro.build/config │
│ export default defineConfig({ │
│ site: 'https://example.com', │
│ integrations: [mdx(), sitemap(), tailwind()] │
│ }); │
╰─────────────────────────────────────────────────╯
? Continue? › (Y/n)
# 👉 そのままエンターキーで OK
✔ Continue? … yes
11:57:00
success Added the following integration to your project:
- @astrojs/tailwind
以上で導入完了です。簡単ですね 🙌✨
Astro の場合は、他のツールで必要な以下のスタイル定義ファイルの追記は 不要 です。
@tailwind base;
@tailwind components;
@tailwind utilities;
動作確認
Tailwind CSS が実際に利用できるか動作確認しましょう。
書き方や使い方は、Tailwind CSS 側のドキュメント を見た方が良さそうです。
今回はサンプルとして、以下の要素を画面に表示してみます。
<h1 class="p-8 text-center text-blue-400 underline">
Hello world!
</h1>
上記は、「パディング(内側への余白)」「文字は中央揃え」「文字色は青」「下線を引く」のスタイルを適用するクラス指定です。
このスタイルが適用された状態で "Hello world!" と表示されれば成功です。
そして、実際にブラウザで表示してみました。
ちゃんとスタイルが適用されていますね。Tailwind CSS が問題なく使えることが確認できました!
プラグインを追加する場合
Tailwind CSS のプラグインを追加する場合は、自動インストール時に生成された ui/tailwind.config.mjs
ファイルに設定を追加しましょう。
プラグイン追加の詳細は、Tailwind CSS のドキュメント を参考にしてください。