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

Assets Bundle Laravel Package

becklyn/assets-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require becklyn/assets-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Becklyn\AssetsBundle\BecklynAssetsBundle::class => ['all' => true],
    ];
    
  2. Enable Routes (Dev Only) Add to config/routes/dev/assets.yaml:

    becklyn_assets:
        resource: "@BecklynAssetsBundle/Resources/config/routes.yaml"
        prefix: /
    
  3. First Use Case Place assets in assets/ (e.g., assets/js/app.js). Reference them in Twig:

    <script src="{{ asset('js/app.js') }}"></script>
    

    The bundle auto-generates hashed filenames (e.g., app.abc123.js) in public/assets/.


Implementation Patterns

Workflows

  1. Asset Organization

    • Store source files in assets/ (e.g., assets/css/main.scss, assets/js/vendor.js).
    • Use subdirectories for logical grouping (e.g., assets/admin/, assets/vendor/).
  2. Twig Integration

    • Basic Usage: {{ asset('path/to/file.ext') }} → Outputs hashed URL.
    • Versioned Assets: {{ asset('path/to/file.ext', { version: '1.2.3' }) }} → Forces regeneration if version changes.
    • Embedded Assets: Use {{ asset('bundles/YourBundle/asset.ext') }} for bundle assets.
  3. Build Automation

    • Integrate with Laravel Mix/Webpack Encore for preprocessing (e.g., SCSS → CSS).
    • Example webpack.mix.js:
      mix.js('assets/js/app.js', 'assets/js')
         .sass('assets/scss/app.scss', 'assets/css');
      
  4. Environment-Specific Config Override defaults in config/packages/becklyn_assets.yaml:

    becklyn_assets:
        output_dir: '%kernel.project_dir%/public/build/assets' # Custom output
        debug: '%kernel.debug%' # Disable hashing in dev
        compressors:
            - 'zopfli' # Enable compression
    
  5. Symfony Controller Integration Generate URLs programmatically:

    $url = $this->get('becklyn_assets.helper')->getUrl('js/app.js');
    

Integration Tips

  • With Symfony UX Stimulus: Reference Stimulus controllers via hashed paths:
    {{ stimulus_controller('hello_controller', { asset: asset('js/controllers/hello_controller.js') }) }}
    
  • With Vite: Use vite:assets to preprocess files, then reference via asset().
  • Cache Invalidation: Clear assets on deploy:
    php bin/console cache:clear --env=prod --no-warmup
    

Gotchas and Tips

Pitfalls

  1. Public Directory Management

    • Never manually edit public/assets/. The bundle clears this directory on cache:clear.
    • Solution: Use output_dir config to point to a custom location if needed.
  2. Debug Mode Quirks

    • In debug: true, assets are served without hashing (e.g., app.js instead of app.abc123.js).
    • Tip: Set debug: false in prod environments for long-term caching.
  3. Compression Dependencies

    • zopfli/gzip must be installed for compression to work. Test with:
      zopfli --version
      
    • Fallback: Use yui or closure compressors if zopfli fails.
  4. File Watching

    • The bundle does not watch files for changes. Use a tool like nodemon or Laravel Mix’s --watch flag during development.
  5. Bundle Assets

    • For assets inside bundles (e.g., src/YourBundle/Resources/public/), use:
      {{ asset('bundles/YourBundle/path/to/file.ext') }}
      
    • Gotcha: Bundle assets must be copied to assets/ manually or via a build step.
  6. URL Generation Edge Cases

    • Relative Paths: Ensure paths in asset() are relative to the assets/ root. ❌ {{ asset('../js/app.js') }} (fails) ✅ {{ asset('js/app.js') }} (works)
    • Query Strings: Avoid appending query strings (e.g., ?v=1.0)—use the version option instead.

Debugging

  1. Asset Not Regenerated?

    • Clear cache and assets:
      php bin/console cache:clear
      php bin/console assets:clear
      
    • Check var/cache/dev/assets.json for generated hashes.
  2. 404 Errors

    • Verify public/assets/ permissions (chmod -R 755 public/assets).
    • Ensure output_dir in config matches the actual directory.
  3. Compression Failures

    • Check var/log/dev.log for compressor errors. Reinstall dependencies:
      composer require --dev zopfli/zopfli-php
      

Extension Points

  1. Custom Processors Extend asset processing by implementing Becklyn\AssetsBundle\Processor\ProcessorInterface:

    class MyProcessor implements ProcessorInterface {
        public function process(string $content, string $path): string {
            return str_replace('foo', 'bar', $content);
        }
    }
    

    Register in config/packages/becklyn_assets.yaml:

    becklyn_assets:
        processors:
            - My\Bundle\Processor\MyProcessor
    
  2. Custom Output Directories Override output_dir per environment:

    # config/packages/becklyn_assets_prod.yaml
    becklyn_assets:
        output_dir: '%kernel.project_dir%/public/build/assets'
    
  3. Twig Extensions Add custom asset functions:

    // src/Twig/AppExtension.php
    class AppExtension extends \Twig\Extension\AbstractExtension {
        public function getFunctions() {
            return [
                new \Twig\TwigFunction('custom_asset', [$this->get('becklyn_assets.helper'), 'getUrl']),
            ];
        }
    }
    

    Use in Twig:

    {{ custom_asset('js/app.js') }}
    
  4. Event Listeners Hook into asset generation events:

    // src/EventListener/AssetsListener.php
    class AssetsListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                AssetsEvents::PRE_PROCESS => 'onPreProcess',
            ];
        }
    
        public function onPreProcess(AssetsEvent $event) {
            $event->setContent(strtoupper($event->getContent()));
        }
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky