Class: SprocketsTerserWithSourceMaps::Compressor

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

Overview

Custom compressor to generate sourcemaps

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Compressor



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

def initialize(options = {})
  @logger = ::Logger.new($stdout)
  @logger.level = ::Logger::INFO

  options[:comments] ||= :none
  @options = options.merge(Rails.application.config.assets.terser.to_h)
  @cache_key = -"Terser:#{Autoload::Terser::VERSION}:#{VERSION}:#{::Sprockets::DigestUtils.digest(@options)}"
  @terser = Autoload::Terser.new(@options)
end

Instance Attribute Details

#cache_keyObject (readonly)

Returns the value of attribute cache_key.



34
35
36
# File 'lib/sprockets_terser_with_source_maps/compressor.rb', line 34

def cache_key
  @cache_key
end

#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

Class Method Details

.cache_keyObject



30
31
32
# File 'lib/sprockets_terser_with_source_maps/compressor.rb', line 30

def self.cache_key
  instance.cache_key
end

.call(input) ⇒ Object



26
27
28
# File 'lib/sprockets_terser_with_source_maps/compressor.rb', line 26

def self.call(input)
  instance.call(input)
end

.instanceObject



22
23
24
# File 'lib/sprockets_terser_with_source_maps/compressor.rb', line 22

def self.instance
  @instance ||= new
end

Instance Method Details

#call(input) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/sprockets_terser_with_source_maps/compressor.rb', line 36

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