FlandreDaisuki / rollup-plugin-userscript-metablock

Transform json file to userscript metablock and append on.
https://www.npmjs.com/package/rollup-plugin-userscript-metablock
MIT License
35 stars 8 forks source link

Generate sourcemap #15

Closed cvzi closed 3 years ago

cvzi commented 3 years ago

Currently this plugin breaks sourcemapping in rollup. If we use MagicString.prepend() to prepend the metablock to the code, we can generate a sourcemap for rollup.

FlandreDaisuki commented 3 years ago

Interesting stuff! I have no idea what situation we need a source map in userscript development. I have no offensive thinking to this PR, just very curious. I have no experience using source map when develop userscripts. I want to try and test this.

cvzi commented 3 years ago

I don't really need it for my use case either, but I thought it would be nice to include it, because it is simple with magic-string

I do use source maps like this:

In my case I use rollup --watch to automatically build the userscript when I change a source file. Then I have a webserver running that serves the generated userscript, e.g. on http://localhost:8080/rollupbundle.user.js I dont't install the bundled userscript in Tampermoneky but this little userscript:

// ==UserScript==
// ...
// ==/UserScript==
const url = `http://localhost:8080/rollupbundle.user.js`
GM.xmlHttpRequest({
  url: url,
  onload: function (r) {
    eval(r.responseText + '\n//# sourceURL=' + url)
  }
})

If I do a reload with F5, it fetches the current file from the server and executes it with eval. So I don't need to copy+paste the userscript into tampermonkey everytime I change something.

The problem is if there is an error in the userscript, the developer console will only show something like this:

Uncaught ReferenceError: foobar is not defined                eval line 3 > eval line 31978 > eval:473:5

which is a bit cryptic.

Because I added #sourceURL=http://localhost:8080/rollupbundle.user.js to eval call, it can show the error at the correct line in the bundled userscript. For example it will show:

Uncaught ReferenceError: foobar is not defined                rollupbundle.user.js:473:5

But I prefer to see the error in my original source file, so if rollup generated a sourcemap, I can actually see the error at the correct line in my original source. So something like:

Uncaught ReferenceError: foobar is not defined                src/originalfile.js:12:5

You can try it with this example: https://github.com/cvzi/rollup-userscript-template

FlandreDaisuki commented 3 years ago

Big thanks to the PR & PoC example 🥰