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

linkorb/jsmin-php

PHP port of Douglas Crockford’s JSMin for minifying JavaScript. Provides a simple API to strip comments and whitespace, shrinking scripts for faster delivery. Lightweight, dependency-free and easy to integrate into Laravel or any PHP build/deploy workflow.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require linkorb/jsmin-php
    

    Add to composer.json if not auto-discovered:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "JsMin\\": "vendor/linkorb/jsmin-php/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Minify a JavaScript string in a Blade template or controller:

    use JsMin\JSMin;
    
    $minified = JSMin::minify($yourJsString);
    
  3. Quick Example:

    $js = 'function foo() { return "bar"; }';
    echo JSMin::minify($js); // Outputs: function foo(){return"bar";}
    

Where to Look First


Implementation Patterns

Common Workflows

  1. Blade Directives: Create a custom Blade directive for minification:

    // app/Providers/BladeServiceProvider.php
    Blade::directive('minify', function ($expression) {
        return "<?php echo JsMin\\JSMin::minify({$expression}); ?>";
    });
    

    Usage in Blade:

    <script>
        @minify($jsString)
    </script>
    
  2. Middleware for Asset Optimization: Minify JS in a middleware before sending responses:

    public function handle($request, Closure $next) {
        $response = $next($request);
        if ($response->headers->get('Content-Type') === 'application/javascript') {
            $content = $response->getContent();
            $response->setContent(JsMin::minify($content));
        }
        return $response;
    }
    
  3. Service Integration: Wrap JSMin in a service class for reusability:

    class JsMinifier {
        public static function minify(string $js): string {
            return JSMin::minify($js);
        }
    }
    

Integration Tips

  • Caching: Cache minified JS to avoid reprocessing:
    $cacheKey = 'js_minified_' . md5($js);
    $minified = Cache::remember($cacheKey, 3600, function() use ($js) {
        return JSMin::minify($js);
    });
    
  • Asset Pipelines: Use with Laravel Mix/Vite for build-time minification (avoid runtime minification in production).
  • Error Handling: Validate input before minification:
    if (!is_string($js)) {
        throw new \InvalidArgumentException('Input must be a string.');
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Runtime minification adds CPU load. Prefer build-time minification (e.g., Laravel Mix) in production.
    • Avoid minifying JS in loops or high-traffic endpoints.
  2. Edge Cases:

    • Comments/Whitespace: JSMin removes all whitespace and comments, including:
      // License header
      function foo() { /* comment */ return "bar"; }
      
      → Becomes: function foo(){return"bar";} (license/comments lost).
    • Source Maps: Minification breaks source maps. Use tools like uglify-js with --source-map for debugging.
  3. Non-Standard JS:

    • May fail on:
      • ES6+ syntax (e.g., arrow functions, template literals) unless the package supports it (test first).
      • Custom syntax (e.g., JSX, TypeScript).
  4. Output Mismatches:

    • Minified output may differ from other tools (e.g., uglify-js). Test thoroughly in your stack.

Debugging

  • Verify Input: Log the input string before minification to spot hidden characters (e.g., BOM, UTF-8 artifacts).
  • Compare Outputs: Use an online minifier (e.g., JSMin) to validate results.
  • Error Handling: Wrap calls in try-catch:
    try {
        $minified = JSMin::minify($js);
    } catch (\Exception $e) {
        Log::error("JSMin failed: " . $e->getMessage());
        return $js; // Fallback to unminified
    }
    

Extension Points

  1. Custom Rules: Modify the minifier’s logic in src/JSMin.php (e.g., preserve specific comments):

    // Override the minify method or extend the class
    class CustomJSMin extends JSMin {
        protected function shouldRemoveComment($comment) {
            return !str_contains($comment, 'PRESERVE');
        }
    }
    
  2. Pre/Post-Processing: Chain with other tools (e.g., uglify-js via PHP bindings):

    $minified = JSMin::minify($js);
    $uglified = UglifyJS::minify($minified);
    
  3. Configuration: The package lacks config options, but you can inject settings via dependency injection:

    JSMin::setOption('preserveComments', true); // Hypothetical; check source
    

Tips

  • Benchmark: Compare runtime vs. build-time minification for your use case.
  • Fallback: Provide unminified JS as a fallback for debugging:
    $minified = JSMin::minify($js);
    $jsToUse = app()->environment('production') ? $minified : $js;
    
  • Testing: Test with:
    • Minified JS (should remain unchanged).
    • JS with edge cases (e.g., //, /* */, /\n/).
    • Large files (memory limits).
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony