Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Frontend Bundle Laravel Package

c4/frontend-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require c4/frontend-bundle
    

    Publish the default configuration (if needed):

    php artisan vendor:publish --provider="C4\FrontendBundle\FrontendBundle" --tag="config"
    
  2. Basic Configuration Update config/frontend.php to define your frontend assets (CSS/JS) and their sources (e.g., local, CDN, or versioned files):

    'assets' => [
        'css' => [
            'app' => [
                'path' => 'assets/css/app.css',
                'version' => '1.0.0',
            ],
        ],
        'js' => [
            'app' => [
                'path' => 'assets/js/app.js',
                'version' => '1.0.0',
            ],
        ],
    ],
    
  3. First Use Case: Rendering Assets Use the Frontend facade to generate HTML tags for assets:

    use C4\FrontendBundle\Facades\Frontend;
    
    // In a Blade template or controller
    echo Frontend::css('app'); // <link href="/assets/css/app.css?v=1.0.0" rel="stylesheet">
    echo Frontend::js('app');  // <script src="/assets/js/app.js?v=1.0.0"></script>
    
  4. Blade Directives (Optional) Add Blade directives for convenience (define in app/Providers/AppServiceProvider):

    Blade::directive('css', function ($asset) {
        return "<?php echo \\C4\\FrontendBundle\\Facades\\Frontend::css('$asset'); ?>";
    });
    Blade::directive('js', function ($asset) {
        return "<?php echo \\C4\\FrontendBundle\\Facades\\Frontend::js('$asset'); ?>";
    });
    

    Now use in Blade:

    @css('app')
    @js('app')
    

Implementation Patterns

1. Asset Organization

  • Grouping Assets: Define logical groups (e.g., admin, dashboard) in the config:
    'assets' => [
        'css' => [
            'admin' => ['path' => 'admin/css/style.css'],
            'dashboard' => ['path' => 'dashboard/css/main.css'],
        ],
    ],
    
    Render them conditionally:
    if (auth()->user()->isAdmin()) {
        echo Frontend::css('admin');
    }
    

2. Versioning and Caching

  • Automatic Versioning: Append a version hash to filenames for cache busting:
    'assets' => [
        'js' => [
            'vendor' => [
                'path' => 'vendor.js',
                'version' => env('APP_VERSION', '1.0.0'), // Dynamic versioning
            ],
        ],
    ],
    
  • Manual Overrides: Disable versioning for specific assets:
    'assets' => [
        'js' => [
            'analytics' => [
                'path' => 'analytics.js',
                'version' => false, // No versioning
            ],
        ],
    ],
    

3. CDN and External Sources

  • Remote Assets: Use the url key to point to external sources:
    'assets' => [
        'css' => [
            'bootstrap' => [
                'url' => 'https://cdn.example.com/bootstrap.css',
                'version' => '5.3.0',
            ],
        ],
    ],
    
  • Fallback to Local: Combine local and remote paths with conditional logic:
    echo Frontend::css('bootstrap', [
        'cdn_fallback' => asset('vendor/bootstrap.css'),
    ]);
    

4. Dynamic Asset Loading

  • Context-Based Loading: Use middleware or service providers to inject assets dynamically:
    // In a middleware
    public function handle($request, Closure $next) {
        if ($request->routeIs('admin.*')) {
            app('frontend')->addAsset('css', 'admin');
        }
        return $next($request);
    }
    

5. Integration with Laravel Mix/Vite

  • Build Output: Configure the bundle to serve assets compiled by Laravel Mix/Vite:
    'assets' => [
        'css' => [
            'app' => [
                'path' => mix('css/app.css'), // Mix output
            ],
        ],
    ],
    
  • Public Path: Ensure publicPath in webpack.mix.js matches the bundle’s expected path.

6. Theming Support

  • Theme-Specific Assets: Use environment-based configurations:
    'assets' => [
        'css' => [
            'theme' => [
                'path' => config('app.theme') . '/style.css',
            ],
        ],
    ],
    

Gotchas and Tips

Pitfalls

  1. Missing Configuration

    • Issue: Assets not loading due to undefined keys in config/frontend.php.
    • Fix: Verify all asset names in the config match those used in Frontend::css()/Frontend::js() calls.
  2. Versioning Conflicts

    • Issue: Hardcoded versions in the config may break cache busting if not updated.
    • Fix: Use dynamic versions (e.g., env('APP_VERSION')) or let the bundle auto-generate hashes:
      'version' => 'auto', // Uses filemtime for versioning
      
  3. Blade Directive Scope

    • Issue: Blade directives may not work if the AppServiceProvider is not registered.
    • Fix: Ensure the provider is in config/app.php under providers.
  4. Asset Path Resolution

    • Issue: Local assets fail to load if the publicPath is misconfigured.
    • Fix: Use asset() helper or set the base path in the config:
      'base_path' => public_path('assets'),
      
  5. Overwriting Defaults

    • Issue: Custom configurations are ignored after package updates.
    • Fix: Publish and extend the config instead of replacing it:
      php artisan vendor:publish --tag="config" --force
      

Debugging Tips

  1. Check Generated HTML Use Frontend::debug() to inspect the rendered asset tags:

    dd(Frontend::css('app')); // Debug the output
    
  2. Log Asset Resolution Enable debug mode in the config to log asset paths:

    'debug' => env('APP_DEBUG', false),
    
  3. Clear Cached Config If changes to config/frontend.php don’t take effect:

    php artisan config:clear
    

Extension Points

  1. Custom Asset Types Extend the bundle to support additional asset types (e.g., fonts, SVGs):

    // In a service provider
    Frontend::extend('font', function ($asset, array $options) {
        return '<link href="' . asset($asset['path']) . '" rel="preload" as="font">';
    });
    
  2. Asset Filters Add middleware-like filters for asset tags:

    Frontend::filter('css', function ($tag) {
        return str_replace('rel="stylesheet"', 'rel="preload"', $tag);
    });
    
  3. Dynamic Asset Sources Override the asset resolver for dynamic sources (e.g., database-driven assets):

    Frontend::resolver(function ($type, $name) {
        return DB::table('frontend_assets')->where('name', $name)->first()->path;
    });
    
  4. Event Listeners Listen for asset compilation events (e.g., post-build hooks for Vite/Mix):

    // In EventServiceProvider
    FrontendBundle::assetCompiled(function ($asset) {
        // Log or process compiled assets
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware