2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NuxtプロジェクトにTailwindCSSをセットアップする方法

Posted at

NuxtにTailwindCSSを導入する一連の作業を残しておきます.

環境

  • Node: 23.5.0
  • npm: 10.9.2

Nuxtプロジェクトの作成

Nuxtのプロジェクトをリファレンスの通りに作成します.

shell
npx nuxi@latest init my-project

下記の確認プロセスのあとNuxtプロジェクトが作成されます.

  1. パッケージマネージャの選択
  2. Gitリポジトリの初期化

状況に合わせて選択します.

この時点で以下のように実行するとNuxtの開発用サーバが立ち上がります.

shell
cd my-project
npm run dev -- -o

デフォルトは http://localhost:3000 でアクセスできます.

Tailwind CSS の導入

Nuxtのモジュールとして公開されているNuxt Tailwindを利用してみます.
リファレンスの通り作業します.

shell
npx nuxi@latest module add tailwindcss

nuxi module add を利用すると nuxt.config.ts に勝手にモジュールが追加されるので楽ですね.

nuxt.config.ts
export default defineNuxtConfig({
  :
  modules: ['@nuxtjs/tailwindcss']
  :
})

tailwind.config.js と asset/css/tailwind.css が無くて怒られるため準備します.
tailwindcss モジュールを使って tailwind.config.js を生成します.

shell

npm install -D tailwindcss
npx tailwindcss init

次に,assets/css/tailwind.cssを作成し,Tailwind CSS のユーティリティクラスをインポートします.
ディレクトリが存在しない場合は作成してください.Nuxt Tailwindのデフォルト設定でフォルダ階層とファイル名が指定されているので特別な理由がない限りは守ります.

~/asset/css/tailwind.scss
+ @tailwind base;
+ @tailwind components;
+ @tailwind utilities;

ファイルの位置を変更したい場合は次節で後述するnuxt.config.tsに設定を変更することができます.

Nuxtプロジェクトの設定変更

Nuxt Tailwindではnuxt.config.tsにtailwindcss要素を追加して設定するようです.
tailwind.cssのファイル名や置き場所を変更する場合はtailwindcss.cssPathを設定するといいようです.
TailwindCSSのクラスが認識されるようにtailwindcss.config.content要素を追加します.

~/nuxt.config.ts
  // https://nuxt.com/docs/api/configuration/nuxt-config
  export default defineNuxtConfig({
    compatibilityDate: "2024-11-01",
    devtools: { enabled: true },
    modules: ["@nuxtjs/tailwindcss"],
+   tailwindcss: {
+     cssPath: ["~/assets/css/tailwind.css", { injectPosition: "first" }], // Default
+     config: {
+       content: [
+         "~/components/**/*.{js,vue,ts}",
+         "~/layouts/**/*.vue",
+         "~/pages/**/*.vue",
+         "~/plugins/**/*.{js,ts}",
+         "~/app.vue",
+         "~/error.vue",
+       ],
+     },
+     viewer: true,
+   },
  });

tailwindcss.viewer は何ぞと思い true にしてみましたが,http://localhost:3000/_tailwind にデザインのカタログのようなものが一覧で確認できるようです.

導入作業は以上です!

動作確認

簡単に動作確認をしてみます.
app.vue を簡単に下記の通りに変更してみました.

app.vue
<template>
  <div class="font-black text-center text-3xl">Nuxt Tailwind</div>
</template>

クラスを指定するだけでデザインが変更されていたら導入完了!

Nuxt Tailwind

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?