Search code examples
phpwordpressbrowserifyuglifyjs

How do I conditionally include the minified or unminified assets in a PHP-Driven template?


I'm working with a Wordpress setup, and have a template which loads my Gulp-generated JavaScript file (using browserify/babelify to compile).

I am uglifying the browserify/babelified result, and I also use browser-sync.

When I use the website through the Browser-Sync webserver, I would like to load the bundle.js (uncompressed) version of the javascript in my template, when I use the website outside the BrowserSync version / in production, I'd like the bundle.min.js (minified) script to be loaded instead.


Solution

  • I don't know the precise mechanics of how browser-sync works, but what I usually did was decide which version of my assets to serve depending on a server environment variable or the state of WP_DEBUG.

    E.g., more or less:

      $minified = ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ? '' : '.min';
    
      wp_enqueue_script( 'my-js', "filename" . $minified . '.js', false );
    

    Again, I'm not sure about browser-sync, but if I'm not mistaken it justs reloads the proper browser tab, resending the same request when you modify/recompile your assets. So that would not be enough info to distinguish that request.

    But if you do something like the above, you'll serve uncompressed assets on your development machine, and later on deployment serve the minified ones without having to change anything else.