How to include a JavaScript source map file in a Firefox WebExtension?

Viewed 2179

When attempting to use a library with a source map from within a WebExtension, I encounter this error.

Source map error: TypeError: NetworkError when attempting to fetch resource.
Resource URL: moz-extension://090d55cc-e9cf-4627-9511-ce49ed5b54c8/source.js
Source Map URL: source.map

According to MDN's How to - "Use a Source Map",

You must put a comment at the very end of your file.

//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map

When working on a Firefox WebExtension with local copies of external libraries (as is advised for security, and as is desired for speed and predictable availability, and which may be necessary if the library is self-written and you don't have access to CDN networks, or the CDN version needs customization, etc), this fails.

// At the bottom of source.js
//# sourceMappingURL=source.map

Because all extension URI's live in a browser profile somewhere and must be explicitly prefixed with the appropriate absolute path based on a UUID that is randomly generated on each run of the WebExtension. So you would need to dynamically specify the following.

// At the bottom of source.js
//# sourceMappingURL=moz-extension://090d55cc-e9cf-4627-9511-ce49ed5b54c8/source.map

The only way to get the path is at runtime by calling browser.runtime.getURL(), which can not be used - either inline or previously called with result stored to a variable to access here - because this is a comment, and comments are ignored.

GENIUS mechanism for specifying a map file. Not!

So how can this be achieved? Or can it only be confirmed to not work? Is there some other technique? Is this part of some W3C specifications Working Group? Has this been discussed or considered anywhere at all? Searching didn't yield any relevant links.

2 Answers

Even if you don't need to manually set your extension ID during development, I recommend you to do so as some storage API methods are not available using only the random internal temporary UUID.

Anyway, something seems to be wrong with your source map files. If you're using webpack, this simple configuration should work.

webpack.config.dev.js

output: {
  sourceMapFilename: '[name].map.js',
  filename: '[name].js',
  path: path.resolve(__dirname, `your_output_dir`)
},

devtool: 'cheap-module-source-map'

Devtools debugging tab

Also, if you paste your extension internal UUID into the Firefox adrress bar, you'll get your extension files with source maps. For example:

moz-extension://7c26e712-c8ac-41ef-b074-500f40601ab2/

Related