kenchris / urlpattern-polyfill

URLPattern polyfill
https://www.npmjs.com/package/urlpattern-polyfill
MIT License
268 stars 31 forks source link

Publish UMD (or IIFE) build for importScripts() use case #16

Closed jeffposnick closed 3 years ago

jeffposnick commented 3 years ago

I'm looking to use urlpattern-polyfill from within a service worker, loaded via importScripts().

As far as I can tell, only the unbundled ES modules for urlpattern-polyfill are published to npm, but using ES modules natively is not widely supported inside of a service worker.

Would it be possible to publish a single UMD (or IIFE) bundle to npm alongside the ES modules? That would make it possible to use importScripts() directly to pull in the polyfill from an npm CDN like https://unpkg.com/

(I've found https://github.com/developit/microbundle to be the easiest build tool to use for this sort of thing.)

kenchris commented 3 years ago

Sure thing

kenchris commented 3 years ago

Could you verify that something like this would work for you?

-  "main": "dist/index.js",
-  "module": "dist/index.js",
+  "main": "./dist/index.cjs",
+  "module": "./dist/index.js",
+  "unpkg": "./dist/index.umd.js",
   "files": [
     "src",
     "dist"
@@ -15,6 +16,7 @@
   "devDependencies": {
     "ava": "^3.14.0",
     "esm": "^3.2.25",
+    "microbundle": "^0.13.3",
     "rimraf": "^3.0.2",
     "rollup": "^2.35.1",
     "rollup-plugin-filesize": "^9.1.0",
@@ -22,7 +24,7 @@
     "typescript": "^4.1.3"
   },
   "scripts": {
-    "build": "rimraf dist/ && tsc",
+    "build": "rimraf dist/ && tsc && microbundle",
     "build:watch": "tsc --watch",
     "test": "npm run build && ava --fail-fast -s",
     "quicktest": "ava --fail-fast -s",
jeffposnick commented 3 years ago

I think you can simplify things further; your build just needs to be rimraf dist/ && microbundle, and you should be able to drop all the direct tsc and rollup devDependencies entirely.

But yeah, in general that should work! The code to use the polyfill from a service worker in that case would end up looking like:

if (!('URLPattern' in self)) {
  importScripts('/path/to/index.umd.js');
  self.URLPattern = urlpatternPolyfill.URLPattern;
}
kenchris commented 3 years ago

OK, done. We will first release when the tests are passing again, but feel free to test it out

jeffposnick commented 3 years ago

I can confirm that importScripts('https://unpkg.com/urlpattern-polyfill@1.0.0-rc1/dist/index.umd.js') works as expected when used from https://glitch.com/edit/#!/urlpattern-sw-routing?path=service-worker.js%3A6%3A0