Minification with Both Uglifier and esbuild

Curated ago by @jeremysmithco

Description

If you are working on legacy Rails projects with old ES5 code, but have also switched to jsbundling-rails, esbuild for new ES6 code, you may have struggled to find a good approach to minifying all your assets. Uglifier only works with ES5 and may cause issues in Harmony mode.

Inspiration for this approach came from Optionally skip compression for specific files and Custom sprockets compressor as proxy skips minified assets.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class LegacyCompressor
  def self.default_js_compressor
    @default_js_compressor ||= Sprockets::UglifierCompressor.instance
  end

  def self.call(input)
    if input[:filename] =~ /legacy\.js/
      default_js_compressor.call(input)
    else
      input[:data]
    end
  end
end

Sprockets.register_compressor "application/javascript", :legacy_compressor, LegacyCompressor