weblabormx/php-remove-unused-css

PHP Remove Unused CSS is a tool to remove unused CSS from your website using PHP

v1.0.1 2024-05-04 09:00 UTC

This package is auto-updated.

Last update: 2024-11-04 10:10:28 UTC


README

PHP Remove Unused CSS is a tool to remove unused CSS from your website using PHP. Developed by Momentum 81 - https://momentum81.com.

- IMPORTANT! MAKE SURE YOU READ THE GUIDE FIRST OR YOU MAY INADVERTENTLY OVERWRITE YOUR CSS

The main idea is to first compile your CSS into as few files as possible, then you would remove the extra classes using this package, then use this (or another) package to minify the CSS.

Often this is done with JS however that can raise issues if you want to work this into a pure PHP development flow.

Installation

Installation via composer:

composer require momentum81/php-remove-unused-css

Example

$removeUnusedCss = new \Momentum81\PhpRemoveUnusedCss\RemoveUnusedCssBasic();

$removeUnusedCss->whitelist('.fab', '.far', '.fal')
    ->styleSheets(public_path('**/*.css'))
    ->htmlFiles(resource_path('**/*.blade.php'))
    ->setFilenameSuffix('.refactored.min')
    ->minify()
    ->refactor()
    ->saveFiles();

Classes

The are two main ways of using the package:

  • Basic
  • Complete (In Development, not yet available)

Basic Class

The basic class is created using RemoveUnusedCssBasic. This is essentially a 'dumb' system that won't traverse the DOM in any way and will just include a selector if it's lowest level appears in the CSS.

That said, this can still provide some significant savings in file size, especially when you're using a package like Bootstrap.

$removeUnusedCss = new \Momentum81\PhpRemoveUnusedCss\RemoveUnusedCssBasic();

The basic class only weakly matches, lets look at the following HTML:

<div>
    <span class="hello">Hello World</span>
</div>

The following CSS Classes would match and be kept, despite the .hello class being used in the HTML not being inside a parent element using the class .test:

.test .hello {}
.test .hello::after {}

Complete Class

In Development. This method attempts to be smarter and where possible traverse the DOM as much as it can (When using a templating system this is infinitely more difficult if your views are not cached, so the system can only do so well here).

Available Methods