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

Javascript Bundle Laravel Package

ecommit/javascript-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ecommit/javascript-bundle
    

    Add to config/bundles.php:

    Ecommit\JavascriptBundle\EcommitJavascriptBundle::class => ['all' => true],
    
  2. Basic Configuration: Publish the default config:

    php artisan vendor:publish --tag=ecommit-javascript-bundle-config
    

    Edit config/ecommit_javascript.php to define your asset paths (e.g., js, css, vendor).

  3. First Use Case: Register a JavaScript file in a controller or service:

    use Ecommit\JavascriptBundle\Asset\JavascriptAsset;
    
    public function index()
    {
        $asset = new JavascriptAsset('path/to/your-script.js');
        return view('your.view')->with('javascript', $asset);
    }
    

    Render in Blade:

    @foreach($javascript as $asset)
        {{ $asset->render() }}
    @endforeach
    

Implementation Patterns

Asset Registration Workflows

  1. Dynamic Asset Loading: Use the JavascriptAsset class to dynamically register scripts based on user roles, features, or conditions:

    if (auth()->check()) {
        $asset = new JavascriptAsset('js/admin-dashboard.js');
        view()->share('javascript', $asset);
    }
    
  2. Grouping Assets: Bundle related scripts (e.g., for a specific page or module) using an array:

    $assets = [
        new JavascriptAsset('js/vendor/jquery.js'),
        new JavascriptAsset('js/custom/module.js'),
    ];
    return view('module.view')->with('javascript', $assets);
    
  3. Versioning: Append a version query string to assets for cache busting:

    $asset = new JavascriptAsset('js/app.js', ['version' => '1.0.1']);
    
  4. Integration with Laravel Mix/Vite: Use the bundle to render assets compiled by Laravel Mix or Vite:

    $asset = new JavascriptAsset(mix('js/app.js'));
    

Common Use Cases

  • Admin Panels: Load admin-specific scripts conditionally.
  • Feature Flags: Toggle scripts based on feature toggles.
  • A/B Testing: Dynamically inject scripts for test variants.
  • Third-Party Libraries: Register vendor scripts with dependencies.

Gotchas and Tips

Pitfalls

  1. Asset Path Resolution:

    • The bundle assumes assets are in public/ by default. Customize asset_path in config if using a different root.
    • Fix: Override the getPath() method in JavascriptAsset for custom paths:
      $asset = new class('js/custom.js') extends JavascriptAsset {
          protected function getPath() {
              return storage_path('app/js/custom.js');
          }
      };
      
  2. Duplicate Scripts:

    • Without deduplication, scripts may be rendered multiple times if registered in multiple places.
    • Fix: Use a JavascriptAssetManager (if available) or manually track loaded scripts in a session:
      if (!session()->has('scripts.loaded')) {
          $asset = new JavascriptAsset('js/app.js');
          session()->put('scripts.loaded', true);
      }
      
  3. Missing Dependencies:

    • The bundle does not enforce dependency ordering. Critical scripts may fail if loaded out of order.
    • Fix: Manually order assets or use a build tool (e.g., Laravel Mix) to bundle dependencies.
  4. Configuration Overrides:

    • Changes to config/ecommit_javascript.php require clearing cached configs:
      php artisan config:clear
      

Debugging Tips

  • Check Rendered Output: Temporarily modify the render() method to add debug markers:
    public function render() {
        return '<!-- DEBUG: '.$this->path.' -->'.parent::render();
    }
    
  • Log Asset Registration: Add logging in a service provider:
    public function boot() {
        \Log::debug('Registered JS assets:', view()->getShared('javascript'));
    }
    

Extension Points

  1. Custom Asset Types: Extend Ecommit\JavascriptBundle\Asset\AbstractAsset to support CSS, Webpack chunks, or other assets:

    class WebpackAsset extends AbstractAsset {
        protected $type = 'webpack';
        public function render() {
            return '<script src="' . $this->getUrl() . '"></script>';
        }
    }
    
  2. Asset Processing: Override the getUrl() method to transform paths (e.g., add hashes, CDN prefixes):

    $asset = new class('js/app.js') extends JavascriptAsset {
        protected function getUrl() {
            return 'https://cdn.example.com/' . parent::getUrl();
        }
    };
    
  3. Event Listeners: Listen for asset registration events (if the bundle emits them) to modify behavior globally:

    Event::listen('ecommit.javascript.registered', function ($asset) {
        if (strpos($asset->path, 'analytics') !== false) {
            $asset->attributes['async'] = true;
        }
    });
    

Configuration Quirks

  • Default Attributes: The bundle may add default attributes (e.g., defer, async). Override in the constructor:
    $asset = new JavascriptAsset('js/app.js', ['defer' => false]);
    
  • Asset Paths: Use absolute paths (e.g., asset('js/app.js')) or relative paths. Relative paths are resolved from public/.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle