Search code examples
ruby-on-railsasset-pipelineuglifyjs

How to do JS pre-processing with Uglifier and assets pipeline?


What I'm trying to do (and I'm not sure is possible) is to use UglifierJS to pre-process the JS files using its AST 'mangle' options object. There's an option {defines: {DEVMODE: true}} that you can pass to UglifyJS: https://github.com/mishoo/UglifyJS#use-as-a-code-pre-processor

The Uglify GEM that works with Rails basically uses the same, "defines" is not supposed to be part of the GEM implementation, but I hard-coded it to change a couple of lines of the gem so it will included as one more option.

In any case, the point is how can I use the pre-processing approach in development, so the assets pipeline delivers JS files in this way?


Solution

  • I added support for defines to Uglifier. It's not released yet, but you can use by depending on latest version on git.

    Gemfile:

    gem 'uglifier', :git => 'https://github.com/lautis/uglifier.git'
    

    Instantiate Uglifier with used defines, e.g.

    Uglifier.new(:define => {"DEVMODE" => true})
    

    Alternatively, when using asset pipeline you could use erb preprocessor together with your JS code. Name your file something.js.erb and write code like

    <% if Rails.env.development? %>
      console.log(debug)
    <% end %>