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 Packer Laravel Package

meenie/javascript-packer

PHP library for packing and minifying JavaScript using Dean Edwards’ Packer algorithm. Compresses JS to reduce size and improve load times, with simple PHP API for integrating into builds or runtime processing in Laravel and other projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require meenie/javascript-packer
    

    Require the autoloader in your project (Laravel handles this automatically if using composer.json).

  2. First Use Case Pack a single JavaScript file:

    use Meenie\JavaScriptPacker\Packer;
    
    $packer = new Packer();
    $packedCode = $packer->pack('path/to/your/script.js');
    file_put_contents('path/to/packed/script.min.js', $packedCode);
    
  3. Laravel Integration For Laravel, publish the config (if available) and bind the packer to the container in AppServiceProvider:

    $this->app->singleton(Packer::class, function ($app) {
        return new Packer($app['config']['javascript-packer']);
    });
    

Implementation Patterns

Workflows

  1. Asset Optimization Pipeline Use the packer in a Laravel Asset pipeline (e.g., app/Providers/AppServiceProvider):

    public function boot()
    {
        $this->app->afterResolving('view', function () {
            $packer = app(Packer::class);
            $packed = $packer->pack(public_path('js/app.js'));
            file_put_contents(public_path('js/app.min.js'), $packed);
        });
    }
    
  2. Dynamic Packing in Controllers Pack and serve JS on-demand (e.g., for user-specific scripts):

    public function getCustomScript()
    {
        $packer = app(Packer::class);
        $packed = $packer->pack(storage_path('scripts/custom.js'));
        return response($packed, 200)->header('Content-Type', 'application/javascript');
    }
    
  3. Combining Multiple Files Pack an array of files into one:

    $packer = new Packer();
    $packed = $packer->packMultiple([
        'file1.js',
        'file2.js',
        'vendor/script.js'
    ]);
    

Integration Tips

  • Cache Busting: Append a hash to packed filenames to leverage browser caching:
    $filename = 'js/app.min.js?v=' . md5($packed);
    file_put_contents(public_path($filename), $packed);
    
  • Laravel Mix: Use the packer as a custom webpack loader or post-processor for JS files.
  • Queue Jobs: Offload packing to a queue (e.g., pack:js job) for large projects:
    PackScriptJob::dispatch('path/to/script.js')->onQueue('packing');
    

Gotchas and Tips

Pitfalls

  1. Encoding Issues Ensure input files are UTF-8 encoded. The packer may corrupt non-UTF-8 files (e.g., legacy scripts with ISO-8859-1). Fix: Normalize files before packing:

    $content = file_get_contents($file);
    $content = mb_convert_encoding($content, 'UTF-8', 'auto');
    
  2. Line Breaks in Output The packer strips whitespace by default. To preserve formatting (e.g., for source maps), use:

    $packer = new Packer(['preserve_formatting' => true]);
    
  3. Variable Name Collisions The packer shortens variable names (e.g., var x = 1;var a=1;). This can break:

    • Closures relying on specific variable scopes.
    • Libraries expecting exact variable names (e.g., window.jQuery). Fix: Exclude files/libraries from packing or use the exclude_vars option:
    $packer = new Packer(['exclude_vars' => ['jQuery', 'window']]);
    
  4. Memory Limits Packing large files (>10MB) may hit PHP’s memory_limit. Increase it temporarily:

    ini_set('memory_limit', '256M');
    $packer->pack('large-file.js');
    

Debugging

  • Verbose Output: Enable debug mode to log packing steps:
    $packer = new Packer(['debug' => true]);
    
  • Check for Syntax Errors: Packed JS may fail silently. Validate output with:
    node -e "require('vm').createScript(require('fs').readFileSync('packed.js'));"
    

Extension Points

  1. Custom Packer Classes Extend the Packer class to add pre/post-processing:

    class CustomPacker extends Packer {
        protected function beforePack($code) {
            return str_replace('// DEBUG', '', $code); // Remove debug comments
        }
    }
    
  2. Hooks for External Tools Integrate with tools like UglifyJS or Terser by wrapping the packer:

    $packer = new Packer();
    $packed = $packer->pack($file);
    $minified = shell_exec("uglifyjs -c -m {$packed}");
    
  3. Configuration Overrides Override default settings per environment (e.g., config/javascript-packer.php):

    'production' => [
        'compression_level' => 9,
        'exclude_vars' => ['React', 'Vue'],
    ],
    
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