Search code examples
javascriptruby-on-railsruby-on-rails-3source-maps

Rails 3.2 Dev environment sourceMaps support for JavaScript


I am working on a Rails App using Asset pipeline. The development.rb has the following:

  config.assets.compress = false
  config.assets.compile = true
  config.assets.debug = true

In Dev environment, the assets are not bundled up and each is served up by Rails individually. At this point, the number of assets that are getting served individually are more than 50. Hence, full page reloads are extremely slow.

I would like to concatenate them atleast in a few assets for faster loading time on dev environment but doing that, I loose the ability to debug/see them individually in Chrome dev tools. Example: http://d.pr/i/ZFge

There are two ways to solve this in my knowledge, after you do:

  config.assets.debug = false

and start serving them as concatenated assets.

  1. Old Hacky Way: @sourceUrl trick.
  2. New Way: sourceMaps.

Is there a guide on how I can enable them on a rails app ? I dont use CoffeeScript so https://github.com/markbates/coffee-rails-source-maps is not helpful. Most Google Searches lead to that.

I am looking for a solution for native JS.


Solution

  • I haven't seen an existing solution for this problem. But building one will be quite straight forward.

    The following assumes gem uglifier is the js compressor in use.

    Version 2 of uglifier has a mechanism to create sourcemap. It has the following syntax

    uglified, source_map = Uglifier.new.compile_with_map(source)
    

    Rails asset pipeline allows to specify custom JS Compressor (with a compress method) using the following syntax

    config.assets.js_compressor = Transformer.new
    

    read about that here

    A simple Transformer class would look like the following

    class Transformer
      def compress(string)
        if Rails.env.development?
          output, sourcemap = Uglifier.new.compile_with_map(string)
    
          # write the sourcemap to a file somewhere under public
    
          sourcemap_comment = "//@ sourceMappingURL=#{sourcemap_path}}\n"
    
          return output + sourcemap_comment
        else
          Uglifier.compile(string)
        end
      end
    end
    

    Note: This is not full solution just explaining the concepts. You can build on this and add ways to make it more robust.