Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rewriting of sourceMappingURL comment for css #498

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

fcheung
Copy link

@fcheung fcheung commented Feb 7, 2022

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

@ghost
Copy link

ghost commented May 23, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant