LoginSignup
3
3

More than 1 year has passed since last update.

Webpackを使っているプロジェクトにTailwind CSSを導入する

Last updated at Posted at 2021-05-09

元となるプロジェクト構成

プロジェクトによって構成は様々だと思いますが、ここでは Webpack を使ってJSをバンドルする他に、htmlファイル、cssファイルも利用している構成となります。またcssは別ファイルに書き出してます。

構築

一旦、Tailwind CSS導入前のプロジェクトを構築していきます。

パッケージ等をインストール。

npm init -y
npm install webpack webpack-cli webpack-dev-server html-loader html-webpack-plugin css-loader mini-css-extract-plugin -D

webpack.config.js 作成します。

const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = [
    {
        entry: './src/index.js',

        output: {
            path: `${__dirname}/dist`,
            filename: '[name].js'
        },
        mode: "development",
        devServer: {
          contentBase: `${__dirname}/dist`,
          open: true
        },
        module: {
          rules: [
            {
              test: /\.html$/,
              loader: 'html-loader',
            },
            {
              test: /\.css$/,
              use: [
                MiniCssExtractPlugin.loader,
                'css-loader',
              ],
            },
          ],
        },
        plugins: [
          new HtmlWebPackPlugin({
            template: 'src/index.html',
            filename: './index.html',
          }),
          new MiniCssExtractPlugin({
            filename: './css/style.css',
          }),
        ],
    },
];

src/ 以下に下記ファイル用意します。

├ src
│ ├ index.js
│ ├ index.html
│ ├ css
│    └ style.css

src/index.js

import './css/style.css';

src/index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css/style.css">
  <title>sample</title>
</head>
<body>
  <h1>hello world</h1>
</body>
</html>

src/css/style.css

h1 {
  color: red;
}

NODE_ENV=production npx webpack
で、ここまで問題なく動作することを確認しました。

Tailwind CSS導入

本題のTailwind CSSを導入します。

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

npm install tailwindcss@latest postcss@latest autoprefixer@latest -D
npm i postcss-loader -D

post CSSのconfig

postcss.config.js を作成します。

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

Tailwindのconfig

下記コマンドでconfigファイルを生成します。

npx tailwindcss init

tailwind.config.js を下記のように設定します。

module.exports = {
  content: [
    './src/**/*.html',
    './src/**/*.js',
  ],
  darkMode: false,
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

content オプションが肝で、ここに対象ファイルを指定することで、ビルド時にこのファイルで使用されているCSSクラス名以外残すことでCSSファイルの容量を軽くします。( v2ではpurge になります)

CSSファイルでTailwindの読み込み

css/style.css

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

webpack.config.jsの編集

webpack.config.jsに post CSSの処理を追加します。

module: {
          rules: [
            ...
            {
              test: /\.css$/,
              use: [
                MiniCssExtractPlugin.loader,
                'css-loader',
                'postcss-loader', //追加
              ],
            },
          ],
        },

設定はここまで。

なお、本記事執筆時の各パッケージのバージョンは以下のとおりです。

  "devDependencies": {
    "autoprefixer": "^10.2.5",
    "css-loader": "^5.2.4",
    "html-loader": "^2.1.2",
    "html-webpack-plugin": "^5.3.1",
    "mini-css-extract-plugin": "^1.6.0",
    "postcss": "^8.2.14",
    "postcss-loader": "^5.2.0",
    "tailwindcss": "^2.1.2",
    "webpack": "^5.36.2",
    "webpack-cli": "^4.7.0",
    "webpack-dev-server": "^3.11.2"
  }

確認

src/index.html を下記のように変更してみます。

<body>
  <div class="container mx-auto">
    <div class="flex justify-center">
      <div class="w-1/2">
        <div class="p-6 text-center shadow-md bg-white rounded-md">
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae vitae similique laborum odio laboriosam. Iure aliquid minima reprehenderit incidunt corrupti nostrum, placeat provident id minus consequuntur facere, officia nobis ipsam.</p>
          <a href="" class="py-2 px-4 text-white bg-green-500 border-green-600 rounded-md mt-4 inline-block">click me</a>
        </div>
      </div>
    </div>
  </div>
</body>

ビルド。

NODE_ENV=production npx webpack

dist/index.html にアクセスするとこのようにTailwind cssが適用されたUIが表示されます。

スクリーンショット 2021-05-09 14.11.56.png

またビルドされたcssも未使用のクラスは削除され、12.2 KB と非常に軽くなってます。

3
3
2

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
3
3