bonami-cz/assetic
Assetic is a PHP asset management framework for combining, filtering, and dumping assets like JS and CSS. Supports asset collections, file/glob inputs, metadata (target path, mtime), and a wide range of filters for compilation and minification.
Installation
composer require bonami-cz/assetic
Ensure bonami-cz/assetic is listed in composer.json under require.
Basic Setup
Add the service provider to config/app.php:
'providers' => [
// ...
Bonami\Assetic\AsseticServiceProvider::class,
],
First Use Case: Compiling Assets
Define a simple asset configuration in config/assetic.php:
'assets' => [
'app' => [
'inputs' => [
public_path('css/app.css'),
public_path('js/app.js'),
],
'output' => public_path('build/app.css'),
'filters' => ['cssrewrite', 'uglifyjs'],
],
],
Trigger compilation via Artisan:
php artisan assetic:dump app
Development vs. Production Use environment-based configurations:
if (app()->environment('production')) {
$assetic->setDebug(false);
}
Dynamic Asset Loading Load assets dynamically in Blade:
@assetic('app', ['output' => 'build/app.css'])
Integration with Laravel Mix Use Assetic for PHP-based asset processing while leveraging Mix for JS/CSS bundling:
$mix->assetic(['app'], public_path('mix-manifest.json'));
Custom Filters: Extend Assetic’s filters by creating a custom filter class:
namespace App\Filters;
use Assetic\Filter\FilterInterface;
class CustomFilter implements FilterInterface { ... }
Register it in config/assetic.php:
'filters' => [
'custom' => App\Filters\CustomFilter::class,
],
Asset Versioning Automatically append version hashes to output files:
$assetic->setUseCache(true);
$assetic->setCacheDir(storage_path('app/assetic'));
Caching Issues Clear Assetic cache when updating filters or inputs:
php artisan assetic:clear
File Permissions
Ensure storage_path('app/assetic') is writable:
chmod -R 775 storage/app/assetic
Filter Conflicts
Avoid duplicate filters (e.g., cssrewrite + cssrewrite). Validate filters in config/assetic.php.
Verbose Output Enable debug mode for detailed logs:
php artisan assetic:dump --debug
Dry Runs Test configurations without writing files:
php artisan assetic:dump --dry-run
Custom Dump Command
Extend the AsseticDumpCommand for project-specific logic:
namespace App\Console\Commands;
use Bonami\Assetic\Console\AsseticDumpCommand;
class CustomAsseticDumpCommand extends AsseticDumpCommand {
protected $name = 'assetic:custom-dump';
// Override logic here
}
Event Listeners
Listen to assetic.dump events for post-processing:
Event::listen('assetic.dump', function ($event) {
// Post-process output (e.g., minify further)
});
Asset Manifests Generate JSON manifests for SPAs:
$manifest = $assetic->getManifest();
file_put_contents(public_path('mix-manifest.json'), json_encode($manifest));
How can I help you explore Laravel packages today?