developit / microbundle

📦 Zero-configuration bundler for tiny modules.
https://npm.im/microbundle
MIT License
8.06k stars 361 forks source link

scriptURL of serviceWorker.register isn't considered part of bundle #814

Open TimDaub opened 3 years ago

TimDaub commented 3 years ago

👋🏼

I'm currently working with microbundle to package a service worker library. I have a file index.mjs that takes care of initializing and handling the SW in the main thread. And I have a file worker.mjs that separates the service worker code.

After browser compatability, I register the worker like this:

await navigator.serviceWorker.register('./worker.mjs');

I use microbundle in a standard way by configuring it in package.json.

I'm aware that no bundler would take the input of register(scriptURI) and make it somehow part of the output. Usually, a developer has to care for this separately e.g. in rollup by adding a secondary input and output. But today while doing that I found it annoying and I asked myself why?

Couldn't microbundle just take care of transpiling the worker.mjs file and include it somehow? E.g. it could be bundled as a base64 data URI...

developit commented 3 years ago

Service Workers cannot be loaded from a Data URL or Blob URL, only HTTP(S) URLs are supported.

I'm not sure how Microbundle could know the correct URL to use, since we don't know where anything is hosted.

Are you providing a library that registers its own Service Worker? If so I think the only option is to require that the consumer of the library pass the location of your service worker JS file.

developit commented 3 years ago

I just peeked at the source - I would recommend doing this:

{
  "main": "./dist/web3-service-worker-cache.js",
  "module": "./dist/web3-service-worker-cache.module.js",
  "scripts": {
    "build": "microbundle -f iife --external none src/sw.js && microbundle src/index.js"
  }
}
// src/index.js
export async function init(swURL) {
  await navigator.serviceWorker.register(swURL);
  // etc
}
TimDaub commented 3 years ago

Hey @developit,

cool! Thanks for the answer I'll take a look. In the meantime, I've attempted to add web worker bundling support via code splitting in #815. Hope we can get that merged somehow.

Edit: Re: https://github.com/developit/microbundle/issues/814#issuecomment-790702646

Works well. See b532868 Thx!

developit commented 3 years ago

The worker bundling seems interesting, I'll take a look. The problem last time I tried to land this was that there isn't actually a way to bundle workers and get a usable path/URL (for the same reason as above).