felixdorn/klass

Extract dynamic classes in your Blade components

dev-master 2021-05-23 21:00 UTC

This package is auto-updated.

Last update: 2024-10-24 04:13:13 UTC


README

Klass extracts your dynamic classes in your Blade components to a file that PurgeCSS can process.

Tests Formats Version Total Downloads License

Installation

Requires PHP 8.0.0+

You can install the package via composer:

composer require felixdorn/klass

Usage

// app/View/Components/Button.php
class Button extends Component {
    public string $color;
    
    public function __construct(string $color = 'blue') {
        $this->color = $color;
    }
    
    public function render() {
        return view('components.button');
    } 
}
<!-- resources/views/components/button.blade.php -->
<button class="bg-{{ $color }}-500" {{ $attributes }}>
    {{ $slot }}
</button>
<!-- resources/views/welcome.blade.php -->
<x-button color="red"/>
<x-button/>
php artisan klass:extract
// storage/framework/extracted-classes.txt
bg-red-500 bg-blue-500

You can now add that file to PurgeCSS, or a similar tool to include those classes in your final CSS build.

Configuration

You can publish the config file with:

php artisan vendor:publish --provider="Felix\\Klass\\KlassServiceProvider" --tag="klass-config"

This is the contents of the published config file:

return [
    'components_paths' => [
        resource_path('views/components'),
        base_path('vendor'),
    ],

    'views_paths' => [
        resource_path('views'),
    ],

    'output' => base_path('storage/framework/extracted-classes.txt'),
];

Tailwind & JIT compilation

Klass works well with the old Tailwind workflow aka use a build with a ton of classes in development and then remove all of the unused classes in production. However, recently, Tailwind got a JIT compiler to have a production-like css in development.

Klass could work quite easily with the JIT compiler. At compile time, php artisan klass:extract should be called but I have yet to figure out how to do that in a smart way.

Livewire

Blade components used in a Livewire component are analyzed. However, we do not support Livewire components in itself. I have no plans to support it before traditional Blade components edge cases are resolved. I'd merge a PR adding support for it, if you feel like contributing.

Testing

composer test

Klass was created by Félix Dorn, 16 year old maker under the MIT license.