Extending The Symfony Assetic Google Closure Filter

If you’ve ever used the Symfony framework, then you’ve likely used the Assetic Bundle, which uses the Assetic library to provide asset management tools. The bundle provides a wrapper for the Google Closure which compresses and optimizes javascript.

To dump js wp-content, you would usually run:

php app/console assetic:dump --env=prod

In the background, this runs the Google closure binary that goes through all the scripts declared in your templates. By default, Google closure is set to follow the ECMASscript3 Standard, which is fine for most scripts. However, you will occasionally run into scripts or third party libs that do not follow the standard and Google closure will fail to dump the wp-content due to parse errors / reserved words problems. The quick solution to this is to change the standard that Google closure checks for when compiling to ECMASscript5, but Assetic currently has no configuration option to allow this. There is at least 1 pull request that adds a language option to the assetic config, but at the time of this writing it has yet to be merged. So in order to change the standard, we have to take a slightly longer route.

First, let’s extend the Assetic Google closure filter:

setLanguage(self::LANGUAGE_ECMASCRIPT5);

        parent::filterDump($asset);
    }
}

Second, let’s make this class a service:

Acme/AcmeBundle/Resources/config/services.yml
...
acme.assetic.my_closure:
    class: AcmeAcmeBundleAsseticFilterCompilerJarFilter
    arguments:
        - %assetic.filter.closure.jar%
    tags:
        - { name: 'assetic.filter', alias: 'my_closure' }

And last, use this filter in the templates instead of the default closure filter:

{% javascripts filter="?my_closure" output="js/base.js"
    "../app/Resources/public/js/somelib.js"
    "../app/Resources/public/js/someotherlib.js"
%}{% endjavascripts %}

At this point, when running

php app/console assetic:dump --env=prod

google closure should no longer fail when dumping the js wp-content.

Leave a Comment

Your email address will not be published.

Scroll to Top