32
24

More than 3 years have passed since last update.

[TailwindCSS] Next.js+TypeScript+styled-componentsの環境にTailwindCSSを導入する

Last updated at Posted at 2020-05-02

はじめに

本記事は、既存のプロジェクトにTailwindCSSを導入するところから反映までになります。
Next.js,TypeScript,styled-componentsなどの各導入については別途参照お願いします。

環境

  • Next.js: v9.3.6
  • TypeScript: v3.8.3
  • styled-components: v4.4.1
  • tailwindCSS: v1.4.4

create-next-appで作成したプロジェクトをベースに説明します。

導入

TailwindCSS Install

TailwindCSS公式

$ npm install --save-dev @fullhuman/postcss-purgecss tailwindcss postcss-import

tailwindcss: TailwindCSSのインストールをしています。
@fullhuman/postcss-purgecss: TailwindCSSの使ってないCSSを削除してくれます。
postcss-import: npmからインストールしたCSSのモジュールをインポート可能にしています。

postcss.config.jsファイルの作成

TailwindCSSを使えるようにするためにします。

// postcss.config.js

const purgecss = [
    '@fullhuman/postcss-purgecss',
    {
        content: ['./components/**/*.js', './pages/**/*.js'],
        defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
    },
]
module.exports = {
    plugins: [
        'postcss-import',
        require('tailwindcss')('./tailwindcss-config.js'),
        'autoprefixer',
        ...(process.env.NODE_ENV === 'production' ? [purgecss] : []),
    ],
}

TailwindCSSのimport

pagesフォルダの中にstyles.cssを作成し、Tailwind CSSのbasecomponentsutilitiesをインポートします。

/* style.css */

@tailwind base;
@tailwind components;
@tailwind utilities;

_app.jsにstyles.cssをインポート

下記のように、import文を追加します。

// _app.js

import './styles.css'

styled-componentsと併用可能にする

tailwind.macroというbabelプラグインをインストールします。

$ npm install --save-dev babel-plugin-macros tailwind.macro

インストールした、babelプラグインを.babelrcに

// .babelrc

{
    "presets": [
        "next/babel"
    ],
    "plugins": [
       "styled-components", 
    +  "macros"
    ]
}

これで、tailwind.macroをインポートして
twの中にTailwind CSSのスタイルを入れれば反映できるはずでした。

こんな感じ

import * as React from 'react'
import styled from 'styled-components'
import media from 'styled-media-query'
import tw from 'tailwind.macro'

const HeaderBox = styled.div`
    ${tw`bg-black`};
    ${media.lessThan('medium')`
    `};
`

エラーだらけなので、ひとつひとつ解消していきます。

ハマった点

1.tailwind.macroモジュールに型定義

Could not find a declaration file for module 'tailwind.macro'. 
'node_modules/tailwind.macro/macro.js' implicitly has an 'any' type.
 Try `npm install @types/tailwind.macro` if it exists or add a new declaration (.d.ts) file containing 
 `declare module 'tailwind.macro';`
  • tailwind.macroというmoduleは見つかりません
  • tailwind.macroは暗黙的にany型であるので、型の定義をしてください。

とりあえず言われた通りnpm install @types/tailwind.macroを実行してみます。

npm ERR! 404 Not Found - GET https://registry.npmjs.org/@types%2ftailwind.macro - Not found

@types/tailwind.macroというpacakgeは存在しないようです。

これでは解決できないので
次に書いてある、型定義ファイルにdeclare module 'tailwind.macro';追記してみます。


declare module 'tailwind.macro'

tailwind.macroが無事読み込まれました!
スクリーンショット 2020-05-02 23.32.30.png

エディタでのエラーは消えたので、実行してみます。

./src/components/organisms/MainHeader.tsx
Module not found: Can't resolve 'yumedeshinou-dev/tailwind.js' in '/workspace/yumedeshinou-dev/src/components/organisms'

実行時にModule not foundのエラー
書き方と設定周りが怪しいと感じたので調べました。

2.tailwindの設定

$ npx tailwindcss init

上記コマンドを実行すればtailwind.config.jsは作られます。
とりあえず今回は導入して反映させるのが目的なので、公式からそのまま持ってきました。

// tailwind.config.js

module.exports = {
  important: true,
  theme: {
    fontFamily: {
      display: ['Gilroy', 'sans-serif'],
      body: ['Graphik', 'sans-serif'],
    },
    extend: {
      colors: {
        cyan: '#9cdbff',
      },
      margin: {
        '96': '24rem',
        '128': '32rem',
      },
    }
  },
  variants: {
    opacity: ['responsive', 'hover']
  }
}

まだ実行時エラーは消えません。
babel-plugin-macrosの設定もしていないので、そちらもしてみます。

3.babel-plugin-macrosの設定

// babel-plugin-macros.config.js

module.exports = {
    tailwind: {
        styled: 'styled-components',
        config: './tailwind.config.js',
        format: 'auto',
    },
}

tailwind.config.jsが読み込まれるように設定します。

4.styled-components+TailwindCSS


import * as React from 'react'
import styled from 'styled-components'
import media from 'styled-media-query'
import tw from 'tailwind.macro'

const HeaderBox = styled('div')`
    ${tw`bg-black`};
    ${media.lessThan('medium')`
    `};
`

ブログ名的にヤバイ感じになってしまいましたが、無事反映されました!!!!!!!!
スクリーンショット 2020-05-02 23.58.52.png

まとめ

  • TailwindCSSをインストールする
  • TailwindCSSをstyled-componentsと併用可能にするためにtailwind.macroをインストール
  • tailwind.macroモジュールの型定義をする
  • tailwindの設定をする
  • babel-pluguin-macrosの設定をする

以上で、無事Next.js+TypeScript+styled-componentsの環境に
TailwindCSSを導入することができました!

参考記事

至らない部分などありましたら、編集依頼などで教えていただければ幸いです!
ここまで、読んでいただきありがとうございました!

32
24
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
32
24