8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PurgeCSS で使われていない CSS を削除しよう

Last updated at Posted at 2021-04-26

この記事は使われていない CSS を削除するデモです。

PurgeCSS を PostCSS のプラグインとして npm scripts で 使います。

環境

$ node -v
v12.14.1

プロジェクトの作成とプロジェクトルートディレクトリへの移動

$ mkdir test-purgecss && cd test-purgecss

npm パッケージを新規でセットアップする

今回はオプション -y で質問を省略しています。

$ npm init -y

インストール

purgecss、postcss と postcss-cliをインストールします。

$ npm i -D @fullhuman/postcss-purgecss postcss postcss-cli

postcss の設定ファイルを作成します

$ touch postcss.config.js

postcss の設定ファイルの中身

postcss.config.js
const purgecss = require('@fullhuman/postcss-purgecss')

module.exports = {
  plugins: [
    purgecss({
      content: ['./**/*.html']
    })
  ]
}

package.json にコマンドを記述します。

package.json
{
  "scripts": {
    "postcss": "postcss src/**/*.css --dir css"
  }
}

作業ファイルの作成

ここまででセットアップは完了しました。
作業ファイル index.html と src/style.css を作成します。

$ mkdir src && touch index.html src/style.css

HTMLファイルの中身

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body class="a">
  
</body>
</html>

<body> 要素に class="a" を記述します。

CSSファイルの中身

src/style.css
.a {
  color: aqua;
}
.b {
  color: blue;
}
.c {
  color: cyan;
}

purgecss の実行

$ npm run postcss

結果

css/style.css
.a {
  color: aqua;
}

ディレクトリ構成

.
├── css
│   └── style.css
├── index.html
├── node_modules
├── package-lock.json
├── package.json
├── postcss.config.js
└── src
    └── style.css

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?