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

Jsmin Php Laravel Package

mrclay/jsmin-php

PHP port of Douglas Crockford’s JSMin for minifying JavaScript. Removes comments and unnecessary whitespace to shrink files while preserving behavior. Lightweight and simple to integrate into build scripts or server-side workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mrclay/jsmin-php
    

    Add to composer.json if not using Composer directly.

  2. Basic Usage:

    use Mrclay\JsMin\JsMin;
    
    $jsCode = 'function foo() { return "bar"; }';
    $minified = JsMin::minify($jsCode);
    

    Outputs: function foo(){return"bar";}

  3. First Use Case:

    • Minify JavaScript assets before saving to disk or sending to the browser.
    • Use in a Laravel service provider or middleware to pre-process JS files in public/js/.

Implementation Patterns

Common Workflows

  1. Asset Optimization Pipeline:

    // In a Laravel service provider (e.g., AppServiceProvider)
    public function boot()
    {
        $jsFiles = glob(public_path('js/*.js'));
        foreach ($jsFiles as $file) {
            $content = file_get_contents($file);
            $minified = JsMin::minify($content);
            file_put_contents($file, $minified);
        }
    }
    
    • Run during php artisan optimize or a custom Artisan command.
  2. On-the-Fly Minification (Middleware):

    // app/Http/Middleware/MinifyJs.php
    public function handle($request, Closure $next)
    {
        if ($request->is('js/*')) {
            $content = file_get_contents($request->path());
            $minified = JsMin::minify($content);
            return response($minified, 200, ['Content-Type' => 'application/javascript']);
        }
        return $next($request);
    }
    

    Register in app/Http/Kernel.php under $middleware.

  3. Integration with Laravel Mix:

    • Use the postCss or postProcess hooks to minify JS after compilation:
      // webpack.mix.js
      mix.js('resources/js/app.js', 'public/js')
          .postProcess((stats) => {
              const fs = require('fs');
              const JsMin = require('mrclay/jsmin-php').JsMin;
              fs.readFile(stats.compilation.assets['js/app.js'], 'utf8', (err, data) => {
                  if (!err) {
                      const minified = JsMin.minify(data);
                      fs.writeFileSync(stats.compilation.assets['js/app.js'], minified);
                  }
              });
          });
      
  4. Blade Directives:

    // Create a custom Blade directive in AppServiceProvider
    Blade::directive('minify', function ($expression) {
        return "<?php echo Mrclay\JsMin\JsMin::minify({$expression}); ?>";
    });
    

    Usage in Blade:

    <script>
        @minify($jsVariable)
    </script>
    

Gotchas and Tips

Pitfalls

  1. Source Maps:

    • Minification breaks source maps. If using source maps (e.g., with Laravel Mix), disable minification or generate source maps post-minification using tools like source-map.
  2. Edge Cases in JS:

    • The minifier may not handle all JS syntax (e.g., template literals, ES6+ features) perfectly. Test with your project’s JS codebase.
    • Avoid minifying JS that relies on whitespace (e.g., indentation-sensitive libraries like Prettier or custom parsers).
  3. Performance:

    • Minifying large JS files on-the-fly (e.g., in middleware) can slow down responses. Pre-minify during build/deployment instead.
  4. Caching:

    • Cache minified JS files to avoid reprocessing. Use Laravel’s cache or filesystem caching:
      $cacheKey = 'js_minified_' . md5($jsCode);
      $minified = Cache::remember($cacheKey, now()->addHours(1), function() use ($jsCode) {
          return JsMin::minify($jsCode);
      });
      

Debugging

  1. Verify Output:

    • Compare minified output with tools like JSMin Online to ensure consistency.
    • Use JsMin::minify($jsCode, true) (if supported) to enable verbose logging or debug mode.
  2. Error Handling:

    • Wrap minification in a try-catch to handle malformed JS gracefully:
      try {
          $minified = JsMin::minify($jsCode);
      } catch (\Exception $e) {
          Log::error("JS Minification failed: " . $e->getMessage());
          $minified = $jsCode; // Fallback to original
      }
      

Tips

  1. Exclude Files:

    • Skip minification for specific files (e.g., third-party libraries) by checking filenames or content:
      if (strpos($jsCode, '// NO_MINIFY') !== false) {
          return $jsCode; // Skip minification
      }
      
  2. Combine with Other Tools:

    • Chain with Laravel’s file_get_contents and file_put_contents for disk operations, or use with Symfony\Component\Filesystem\Filesystem for robust file handling.
  3. Custom Rules:

    • Extend the minifier by subclassing Mrclay\JsMin\JsMin and overriding methods like minify() or process().
  4. Testing:

    • Write PHPUnit tests to ensure minification behaves as expected:
      public function testMinification()
      {
          $input = 'var x = 10;';
          $expected = 'var x=10;';
          $this->assertEquals($expected, JsMin::minify($input));
      }
      
  5. Configuration:

    • The package has minimal config, but you can create a config file (config/jsmin.php) to store defaults (e.g., cache duration, excluded files):
      return [
          'cache_duration' => 60 * 24, // 24 hours
          'excluded_files' => ['vendor.js', 'no-minify.js'],
      ];
      
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