Source maps in Ruby on Rails through sprockets

2020-05-17 04:35发布

问题:

I'd like to add source map support on a rails 3.2 application I am working on. As far as I know, generating source maps is not supported by Sprockets and from its github page it looks like the feature is planned for 4.0. I am working with Sprockets 2.2 and I think monkey patching is the only way to go. The module Processing under the main Sprockets module gives access to the js_compressor function which can be patched to generate source map for a single file. But, I don't know how to add this when the JS files combine. I am using Uglifier 2.4 as the compressor.

The project has a mixture of CoffeeScript, JS and EJS files. So, I think this is how sprockets would be compiling them together. First, it would convert Coffeescript and EJS to JS, then use the js_compressor to compress individual files and later concatenate them in groups. Now, as the source map for multiple files combined to the same file is a single file. So, I will need to change the compilation process somewhat and make the js_compressor run over the files, once the concatenation is finished. So, can anyone help out with this? Even explaining the sprockets compilation process and the modules used and functions involved would be of great help. I don't care about making source map files for the CoffeeScript code at present. Even mapping to their converted JS files would do.

Also, would like to add if there is some gem which can help with this it would be most welcome.

回答1:

Rails 4 does not have source maps either.

As far as I know, and as of today, this will only be part of rails 5.

A really nice approach to solve this right now is implemented in discourse by @SamSaffron and explained here: https://github.com/discourse/discourse/blob/master/lib/tasks/assets.rake

The gist, add a "before" task to the sprockets precompile process, and hack into the compilation process to generate the sourcemapped files and directives.

The nice thing in this approach is that you don't lose stuff from files that are both js and erb (*.js.erb) which is something quite common in rails.

I think that patching the whole sprockets pipeline is a bit of an abuse and risky.