sprockets-rails
sprockets-rails copied to clipboard
Add rewriting of sourceMappingURL comment for css
Previously only javascript files had their sourceMappingURL comments rewritten with the digested asset location. This PR adds the same treatment to sourceMappingURL comments in css files
Hi @fcheung, consider hooking this up with register_bundle_processor as otherwise the annotation will get clobbered by e.g. autoprefixer-rails.
I've temporarily worked around the issue while waiting for your PR to be merged by doing the following:
# config/initializers/source_maps.rb
class CustomSourcemappingUrlProcessor < Sprockets::Rails::SourcemappingUrlProcessor
FIXED_REGEX = %r{(/(?:/|\*))# sourceMappingURL=(?:.*/)?(.*\.map)(?:;)(.*?)$}.freeze
class << self
def call(input)
env = input[:environment]
context = env.context_class.new(input)
data = input[:data].gsub(FIXED_REGEX) do |_match|
sourcemap_logical_path = combine_sourcemap_logical_path(sourcefile: input[:name], sourcemap: ::Regexp.last_match(2))
begin
resolved_sourcemap_comment(sourcemap_logical_path, context: context, prefix: ::Regexp.last_match(1), suffix: ::Regexp.last_match(3))
rescue Sprockets::FileNotFound
removed_sourcemap_comment(sourcemap_logical_path, filename: input[:filename], env: env)
end
end
{ data: data }
end
private
def resolved_sourcemap_comment(sourcemap_logical_path, context:, prefix:, suffix:)
"#{prefix}# sourceMappingURL=#{sourcemap_asset_path(sourcemap_logical_path, context: context)}#{suffix}\n#{prefix} !#{suffix}\n"
end
end
end
Rails.application.config.assets.configure do |env|
# Remove broken processor
env.unregister_postprocessor 'application/javascript', Sprockets::Rails::SourcemappingUrlProcessor
# Replace with working processor, make sure it's placed after autoprefixer-rails' one
# by placing it in a config.assets.configure block and registering it as a bundle processor
env.register_bundle_processor 'text/css', CustomSourcemappingUrlProcessor
env.register_bundle_processor 'application/javascript', CustomSourcemappingUrlProcessor
end