Class: SprocketsTerserWithSourceMaps::Compressor

Inherits:
Terser::Compressor
  • Object
show all
Defined in:
lib/sprockets_terser_with_source_maps/compressor.rb

Overview

Custom compressor to generate sourcemaps

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Compressor

Returns a new instance of Compressor.



12
13
14
15
16
17
# File 'lib/sprockets_terser_with_source_maps/compressor.rb', line 12

def initialize(options = {})
  @logger = Logger.new($stdout)
  @logger.level = Logger::INFO
  @options = options.merge(Rails.application.config.assets.terser.to_h)
  super(@options)
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



10
11
12
# File 'lib/sprockets_terser_with_source_maps/compressor.rb', line 10

def logger
  @logger
end

Instance Method Details

#call(input) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/sprockets_terser_with_source_maps/compressor.rb', line 19

def call(input)
  input_options = { source_map: { filename: input[:filename] } }

  data = input.fetch(:data)
  name = input.fetch(:name)

  compressed_js, map = @terser.compile_with_map(data, input_options)

  sourcemap = JSON.parse(map)

  if Rails.application.config.assets.sourcemaps_embed_source
    sourcemap['sourcesContent'] = [data]
  else
    # Generate uncompressed asset
    uncompressed_url = generate_asset_file(name, data, Rails.application.config.assets.uncompressed_prefix)

    sourcemap['sources'] = [uncompressed_url]
  end

  sourcemap['file'] = "#{name}.js"
  sourcemap_json = sourcemap.to_json

  # Generate sourcemap file
  sourcemap_url = generate_asset_file(
    name, sourcemap_json,
    Rails.application.config.assets.sourcemaps_prefix,
    'js.map'
  )

  js = compressed_js.concat "\n//# sourceMappingURL=#{sourcemap_url}\n"

  { data: js, map: sourcemap }
end