LoginSignup
11
4

More than 3 years have passed since last update.

PurgeCSS のシンプルな使い方

Last updated at Posted at 2021-01-21

PurgeCSS はプロジェクトで使っていない CSS を削除してくれる便利ツールです。

本来は PostCSS や Gulp などのプラグインとして使うのでしょうが、コマンドラインで都度動かすこともできます。

とりあえず使っていないCSSを削除したいときや、簡単に試してみたい時にはこんな方法でいいかもしれません。

環境

  • node v10.14.1
  • purgecss v4.0.0

デモンストレーション

ディレクトリ構造

index.html
style.css

下記、style.css と index.html を見ていただければわかるのですが、
index.html で使っている css は .mt-50 のみです。

style.css

.mt-10 {
  margin-top: 10px;
}
.mt-20 {
  margin-top: 20px;
}
.mt-30 {
  margin-top: 30px;
}
.mt-40 {
  margin-top: 40px;
}
.mt-50 {
  margin-top: 50px;
}
.mt-60 {
  margin-top: 60px;
}
.mt-70 {
  margin-top: 70px;
}
.mt-80 {
  margin-top: 80px;
}
.mt-90 {
  margin-top: 90px;
}

index.html

<!DOCTYPE html>
<html lang="ja">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <p class="mt-50">test</p>
  </body>

</html>

デモではわかりやすく30行程度の CSS ファイルですが、
ユーティリティ系のスタイルをたくさん準備しておくと実際の作業では 数千〜数万行になることもあるのではないでしょうか。

おそらく全てのスタイルは使いません。

そこで PurgeCSS です。

インストール

npm i -g purgecss

実行

purgecss --css style.css --content index.html --output style.purged.css

オプションの --css は元のCSSファイル、--content は参照先のファイル、--output は書き出しファイルです。
ファイル名、ファイルパスは作業環境に合わせてください。

書き出された CSS ファイル

.mt-50 {
  margin-top: 50px;
}
11
4
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
11
4