0
0

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 1 year has passed since last update.

PostCSS で PurgeCSS を使いプロジェクトで使っていない CSS を削除する方法

Posted at

ゴール

下記ディレクトリ構造で src/index.html で使われていない CSS を src/styles/main.css から削除して dist/styles/main.css に書き出す。

ディレクトリ構造

.
├── dist
│   └── styles
│       └── main.css
├── node_modules
├── package-lock.json
├── package.json
├── postcss.config.js
└── src
    ├── index.html
    └── styles
            └── main.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">
    <title>Document</title>
  </head>

  <body class="test1">

  </body>

</html>

src/styles/main.css

.test1 {}

.test2 {}

.test3 {}

.test4 {}

src/index.html で使っている CSS は test1 のみです。
期待する実行結果は dist/styles/main.css の内容が下記のようになることです。

.test1 {}

手順

NPM をイニシャライズする

npm init -y

必要なパッケージをインストールする

npm install postcss postcss-cli @fullhuman/postcss-purgecss --save-dev

PostCSSの設定

postcss.config.js を作成して下記のように設定

// postcss.config.js
module.exports = {
  plugins: [
    // 他の必要なプラグインがあればここに追加
    require('@fullhuman/postcss-purgecss')({
      // PurgeCSSの設定を追加
      content: [
        './src/**/*.html',
        './src/**/*.vue',
        './src/**/*.jsx',
        // 使っているファイルの拡張子を追加
      ],
      // 他のPurgeCSSのオプションを追加
    }),
  ],
};

スクリプトの追加

package.json に NPMScript を追加します。

{
  "scripts": {
    "build:css": "postcss src/styles/main.css -o dist/styles/main.css"
  }
}

ビルドの実行

npm run build:css

dist/styles/main.css には test1 のみ書き出されているはずです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?