Skip to content

Instantly share code, notes, and snippets.

@jcward
Last active July 23, 2021 18:50
Show Gist options
  • Save jcward/bdadcbaa388a8a7d3a463e3cd3d891c6 to your computer and use it in GitHub Desktop.
Save jcward/bdadcbaa388a8a7d3a463e3cd3d891c6 to your computer and use it in GitHub Desktop.
Inline a source map file into the JavaScript source file as a data URI

Description:

A quick script to inline / inject a source map file into the JavaScript source file.

Use case: Sometimes you have a script.js and a script.js.map file, and you'd prefer to inline the source map as a data URI directly into the script.js file.

NOTE: Modifies the script.js file in-place

Usage:

inline_source_map.rb <script.js>
  • script.js must end with //# sourceMappingURL=some.js.map
  • Modifies script.js in-place, injecting the base-64 encoded data URI in place of the some.js.map reference
#!/usr/bin/env ruby
require 'pathname'
require 'base64'
js_file = ARGV[0]
if (js_file==nil) then
puts "Usage: inline_source_map.rb <script.js>"
puts " - script.js is expected to have a trailing //# sourceMappingURL=file.map"
exit 1
end
js_file = Pathname.new(File.join(Dir.pwd, js_file)).cleanpath.to_s
js_dir = File.dirname(js_file)
puts "Reading #{ js_file }"
js = File.read(js_file)
map_file = js.match(/\/\/# sourceMappingURL=([\w.\/]+\.map)\s*$/)
if (map_file && map_file[1]) then
map_content = File.read(File.join(js_dir, map_file[1]))
encoded = Base64::encode64(map_content).gsub(/\s/, "")
js.sub!(/\/\/# sourceMappingURL=([\w.\/]+\.map)\s*$/, "//# sourceMappingURL=data:application/json;charset=utf-8;base64,#{ encoded }")
puts "Writing #{ js_file } (adding ~#{ encoded.length } bytes)"
File.open(js_file, "w") { |f| f.puts js }
else
puts "Error: did not find trailing //# sourceMappingURL=file.map"
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment