Next.jsでTailwind CSSとEmotionを使う

Next.jsでTailwind CSSとEmotionを使える環境を作ってみます

$ npm init next-app --example with-tailwindcss-emotion [アプリケーション名]

create-next-appを使って、exampleをダウンロードするだけでOKです

Exampleのリポジトリ

github.com

これだけだとあっけないので、Tips的なものを1つ

[ご注意] ここからは↑で作成したexampleを前提に書いてます。他の環境では動作しないかもです

こんなコンポーネントがあったとします

/** @jsx jsx */
import { jsx } from '@emotion/react'
import tw from '@tailwindcssinjs/macro'

const styles = {
  button: tw`
    relative
  `
}

const Button = () => <button css={styles.button}>button</button>
export default Button

JSX Pragmaなるもの(/** @jsx jsx */)とimport { jsx } from '@emotion/react'を毎回かかないといけません。。。

しかも、ESLintにjsxno-unused-varsだと怒られたりもします。。。

そこで、@emotion/babel-preset-css-propですよ

emotion.sh

@emotion/babel-preset-css-propは、Emotion用パーサーのbabelプラグインです

導入手順

  • Installation
    • @emotion/core
      • @emotion/babel-preset-css-propには@emotion/coreが必要なのでインストール
  $ npm install @emotion/core
  
  or 
  
  $ yarn add @emotion/core
  • @emotion/babel-preset-css-prop
  $ npm install @emotion/babel-preset-css-prop
  
  or 
  
  $ yarn add @emotion/babel-preset-css-prop
  • Modify babel config
{
  "presets": [
    "next/babel",
    "@emotion/babel-preset-css-prop" # この行を追加
  ],
  "plugins": [
    "macros",
    "@emotion/babel-plugin"
  ]
}

これで ↓ の2行が不要になります

/** @jsx jsx */
import { jsx } from '@emotion/react'

やったね!

あ、TypeScriptだとcssってpropsの型しらねーって怒られるので、型定義も追加する必要があります

# emotion-env.d.ts (ファイル名はなんでもOK)
/// <reference types="@emotion/core"/>

Happy Tailwind CSS and Emotion ヘ(^o^)ノ