Exclude any js file from uglifier optimization during assets:precompile
If you need to exclude a file from optimization by UglifyJS when you run rake assets:precompile
, you can use this custom class. (Modify it for your own needs)
Place this class into any suitable folder (e.g. lib/ext
).
class ConditionalUglifier < Uglifier
def really_compile(source, generate_map)
# Skip any optimization (e.g. for shims)
if source =~ /^\/\/= skip/
source.gsub!(/\/\/= ?skip(\n)*;(\n)*\z/, "")
else
super
end
end
end
Require it in production.rb
(if it's needed) and specify ConditionalUglifier
as your js_compressor.
require 'ext/conditional_uglifier'
# Compress JavaScripts and CSS.
config.assets.js_compressor = ConditionalUglifier.new
Add //= skip
to the first line of any js file that you want to exclude from the optimization.
An example of shim.js:
//= skip
//= require shims/classList.min
//= require shims/raf.min
//= require shims/weakmap.min
Written by Andrew Volozhanin
Related protips
3 Responses
Hi Andrew, I've been trying to implement this with Rails 4.2.7.1
and can't get it to work. I've added the config.assets.jscompressor = ConditionalUglifier.new to my production.rb.
But it doesn't seem to pass in any arguments for the reallycompress method to run :( .
If you could give me a hand I'd really appreciate it!
All my best, Didi.
I think would be better to override the "compile" method instead of the private "really_compile", because the private one changed, and may keep changing since the interface is private.
TLDR: replace def really_compile(source, generated_map)
by def compile(source)
.
Ref: https://github.com/lautis/uglifier/commit/aba46d4fb36db6c507306b54b48c39fb09fbc6da
EDIT: the desired method is compress
instead of compile
as the Rails guides suggests: http://guides.rubyonrails.org/asset_pipeline.html#using-your-own-compressor