LoginSignup
1
2

More than 3 years have passed since last update.

【2021年4月最新版】爆速でGatsbyでTailwindcssを使う方法

Last updated at Posted at 2021-04-16

今回の記事は最近巷で有名なGatsby.jsでTailwindcssを使用する手順をご紹介します。

ほぼ公式のドキュメント通りに進めていくのですが、いくつか変更点があるのでそれらを説明しながらやっていきます。

一応公式ドキュメントを載せておきますね。

https://www.gatsbyjs.com/docs/how-to/styling/tailwind-css/

はじめに

GatsbyでTailwindcssを使用する場合、ReactもそうなのですがclassName="text-center"のようにクラス名に指定してもTailwindcssを適用することはできません。

そこで登場するのがtwin.macroです。

これを使って例えばtw="text-center"と指定するとTailwindcssを適用することが可能です。

設定も全然難しくないので肩の力を抜いてご覧ください!

それでは早速説明を見ていきましょう!

必要パッケージのインストール

まずは必要なパッケージをインストールします。

npm install tailwindcss autoprefixer postcss gatsby-plugin-postcss sass gatsby-plugin-sass
npm install -D twin.macro @emotion/react @emotion/styled gatsby-plugin-emotion

プラグインの設定

次はプログインの設定を行っていきます。

gatsby-config.jsに以下のコードをコピペしてください。

gatsby-config.js
module.exports = {
  /* Your site config here */
  plugins: [
    'gatsby-plugin-material-ui',
    'gatsby-plugin-postcss',
    'gatsby-plugin-emotion',
    {
      resolve: `gatsby-plugin-sass`,
      options: {
        postCssPlugins: [
          require("tailwindcss"),
          require("./tailwind.config.js")
        ],
      },
    },

  ],
}

postcss.config.jsにてtailwindcssを追加(postcss.config.jsを作成していない方は手動で作成してください)。

postcss.config.js
module.exports = () => ({
  plugins: [require("tailwindcss")],
})

tailwindの設定

下記のコマンドでtailwind.config.jsを作成。

npx tailwindcss init

そしてgatsby-config.jsと同じ階層でgatsby-browser.jstailwind.cssを作成してください。

そしたら、tailwind.cssにて以下をインポート。

tailwind.css
@tailwind base;
@tailwind components;
@tailwind utilities;

tailwind.cssの読み込み。

gatsby-browser.js
import "./tailwind.css";

これで準備は整いました。

あとはローカルサーバーを立ち上げ、以下を例にTailwindcssを適用させてみて下さい!

import React from "react"
import 'twin.macro'  // これをインポートしないとtwが使えない
import { Header } from "../components"

export default function Home() {
  return (
    <div>
      <h1 tw="text-black">Hello</h1>
    </div>  
  )
}

追記

pakage.jsonに以下のマクロを登録すると、classNameでTailwindcssを適用することができました。

{
  // 省略
  "babelMacros": {
    "twin": {
      "config": "./tailwind.config.js",
      "preset": "emotion",
      "hasSuggestions": true,
      "debug": false
    }
  },
}

このようにしてGatsby.jsでTailwindcssを適用することができました!

そこまで難しくは無かったような気がする。

他にもたくさん記事を上げているので是非ご覧下さい!

Thank you for reading

参考記事

GatsbyにTailwind CSSを導入する最短手順(CSS-in-JS)

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