Assets: Compressors


Compressors

Assets compression (aka minification) is a process to shrink the file size of a file in order to reduce the time that a browser needs to download it. Usually, it’s applied to javascripts and stylesheets.

In order to set one of the following engines, we need to open apps/web/application.rb and write:

# apps/web/application.rb
module Web
  class Application < Hanami::Application
    configure do
      assets do
        javascript_compressor :builtin
        stylesheet_compressor :builtin

        # ...
      end
    end
  end
end

If we want to skip compression, just comment one or both the lines above.

JavaScript

We support the following engines:

In order to use :yui, :uglifier and :closure compressors, you need to add the corresponding gem to Gemfile.

Stylesheet

We support the following engines:

  • :builtin - It isn’t efficient like the other algorithms, but it’s a good starting point because it’s written in pure Ruby and it doesn’t require external dependencies.
  • :yui - It’s based on Yahoo! YUI Compressor. It requires yui-compressor gem and Java 1.4+
  • :sass - It’s based on Sass. It requires sass gem

In order to use :yui, and :sass compressors, you need to add the corresponding gem to Gemfile.

Custom Compressors

We can use our own compressor for both JS and CSS. It MUST respond to #compress(filename) and return a String with the minification output.

class MyCustomJavascriptCompressor
  def compress(filename)
    # ...
  end
end

Then we can use it with our configuration:

# apps/web/application.rb
module Web
  class Application < Hanami::Application
    configure do
      assets do
        javascript_compressor MyCustomJavascriptCompressor.new
        stylesheet_compressor :builtin

        # ...
      end
    end
  end
end