Class: BabelSchmoozeSprockets::BabelProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/babel-schmooze-sprockets/babel_processor.rb

Constant Summary collapse

DEFAULT_PRESETS =
%w[
  es2015
].freeze
DEFAULT_PLUGINS =
%w[
  transform-async-to-generator
  transform-es2015-modules-amd
  transform-es3-member-expression-literals
  transform-es3-property-literals
  transform-function-bind
].freeze
DEFAULT_BABEL_OPTIONS =
{
  presets: DEFAULT_PRESETS,
  plugins: DEFAULT_PLUGINS
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ BabelProcessor

Returns a new instance of BabelProcessor.



31
32
33
34
35
36
37
38
39
40
# File 'lib/babel-schmooze-sprockets/babel_processor.rb', line 31

def initialize(options)
  @options = options

  @cache_key = [
    self.class.name,
    Babel.new(@options.fetch(:root_dir)).version,
    VERSION,
    @options
  ].freeze
end

Class Method Details

.call(input) ⇒ Object



27
28
29
# File 'lib/babel-schmooze-sprockets/babel_processor.rb', line 27

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

.instanceObject



20
21
22
23
24
25
# File 'lib/babel-schmooze-sprockets/babel_processor.rb', line 20

def self.instance
  @instance ||= BabelProcessor.new(
    root_dir: File.expand_path("#{__dir__}/../.."),
    options: BabelProcessor::DEFAULT_BABEL_OPTIONS
  )
end

Instance Method Details

#call(input) ⇒ Object



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
69
70
71
72
# File 'lib/babel-schmooze-sprockets/babel_processor.rb', line 42

def call(input)
  data = input[:data]

  result = input[:cache].fetch(@cache_key + [input[:filename]] + [data]) do
    options = {
      moduleIds: true,
      sourceRoot: input[:load_path],
      moduleRoot: nil,
      filename: input[:filename],
      filenameRelative: Sprockets::PathUtils.split_subpath(input[:load_path], input[:filename]),
      sourceFileName: input[:source_path],
      sourceMaps: true,
      ast: false
    }.merge(@options.fetch(:options))

    if options[:moduleIds] && options[:moduleRoot]
      options[:moduleId] ||= File.join(options[:moduleRoot], input[:name])
    elsif options[:moduleIds]
      options[:moduleId] ||= input[:name]
    end

    Babel
      .new(@options.fetch(:root_dir))
      .transform(data, options)
  end

  map = Sprockets::SourceMapUtils.decode_json_source_map(JSON.generate(result["map"]))
  map = Sprockets::SourceMapUtils.combine_source_maps(input[:metadata][:map], map["mappings"])

  {data: result["code"], map: map}
end