class Sprockets::Webpackit

Constants

DEFAULT_PATTERN

Public Class Methods

call(input) click to toggle source
# File lib/sprockets/webpackit.rb, line 97
def call(input)
  context = input[:environment].context_class.new(input)
  source = input[:data]
  load_path = input[:load_path]
  filename  = input[:filename]

  path = filename[load_path.length..-1]
  if filename =~ pattern
    process(context, filename)
  else
    { :data => source }
  end
end
extract_dependencies(h) click to toggle source

get a list of dependent filenames from the json webpack stats

# File lib/sprockets/webpackit.rb, line 25
def extract_dependencies(h)
  out = []
  h['modules'].each do |m|
    if m['cacheable'] == true
      out << File.absolute_path(m['name'])
      out.concat(extract_dependencies(m)) if m['modules']
    end
  end
  out
end
extract_errors(h) click to toggle source
# File lib/sprockets/webpackit.rb, line 36
def extract_errors(h)
  out = []
  h['modules'].each do |m|
    if m['errors'] > 0
      out << m['name']
      out.concat(extract_dependencies(m)) if m['modules']
    end
  end
  out
end
mode() click to toggle source
# File lib/sprockets/webpackit.rb, line 47
def mode
  @_mode ||= ENV['RACK_ENV'] || 'development'
end
mode=(val) click to toggle source
# File lib/sprockets/webpackit.rb, line 51
def mode=(val)
  @_mode = val
end
pattern() click to toggle source
# File lib/sprockets/webpackit.rb, line 93
def pattern
  @_pattern ||= DEFAULT_PATTERN
end
pattern=(value) click to toggle source
# File lib/sprockets/webpackit.rb, line 89
def pattern=(value)
  @_pattern = Regexp.new(value)
end
process(context, path) click to toggle source

run a file through webpack and return the result. also maintain a list of dependencies.

# File lib/sprockets/webpackit.rb, line 57
def process(context, path)
  temp = Tempfile.new('sprockets')

  command = "npx webpack #{path}"\
      " --mode #{mode} --json --display normal"\
      " -o #{temp.path}"

  puts "command ='#{command}'" if $VERBOSE || $DEBUG
  stats, err, status = Open3.capture3(command)
  # stats = %x(#{command})
  hash = JSON.parse(stats)
  errors = nil
  if status.success?
    deps = extract_dependencies(hash)
    deps.each do |fname|
      next if fname == path

      context.metadata[:dependencies] << Sprockets::URIUtils.build_file_digest_uri(fname)
    end
    result = File.read(temp.path)
  else
    errors = hash['errors']
    puts errors
    result = errors.join("\n")
  end

  temp.close
  temp.unlink

  context.metadata.merge(:data => result)
end