sprockets-rails
sprockets-rails copied to clipboard
Fix sourcemap with path prefix when using esbuild with publicPath
Esbuild puts the publicPath as a prefix in the sourceMappingURL and because I am using editor/editor to generate the script tag sprockets-rails generating the wrong path and removing the sourceMappingURL from the compiled file.
<%= javascript_include_tag 'editor/editor', defer: true, integrity: true, crossorigin: "anonymous" %>
// build.js
esbuild
.build({
bundle: true,
sourcemap: true,
format: 'esm',
outdir: path.join(process.cwd(), '../../app/assets/builds/editor'),
publicPath: './editor',
entryPoints: ['packs/editor.js'],
...
// app/assets/builds/editor/editor.js
.
.
.
//# sourceMappingURL=editor/editor.js.map
This PR fixes it by only running the special case path when sourceMappingURL does not have a directory prefix.
Hey @vzaramel, thanks for this PR!
Unfortunatelly, this code doesn't work for our case (publicPath set to /assets so static files can be correctly resolved when imported in JS files) as our sourcefile was application but sourcemap was /assets/sourcemap.js.map.
I took the inspiration from your code and fixed it (temporarily) like this:
Sprockets::Rails::SourcemappingUrlProcessor.class_eval do
def self.combine_sourcemap_logical_path(sourcefile:, sourcemap:)
if (parts = sourcefile.split('/')).many?
parts[0..-2].append(sourcemap).join('/')
elsif (parts = sourcemap.split('/')).many?
parts.last
else
sourcemap
end
end
end