Last active
April 26, 2018 11:07
-
-
Save dmnsgn/d09673ab8ee80e0607909314732c2abd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Disclaimer: this is not stable nor properly tested | |
// Not sure about the security implications of hijacking the fetch request either | |
// https://gist.github.com/pilwon/ff55634a29bb4456e0dd | |
const ES_MODULE_IMPORT_REGEX = /\bimport\s+(?:.+\s+from\s+)?[\'"]([^"\']+)["\']/g; | |
const packages = new Map().set( | |
"lodash/clamp", | |
"https://cdn.jsdelivr.net/npm/[email protected]/clamp.js" | |
); | |
self.addEventListener("fetch", event => { | |
// Intercept js files | |
if (event.request.url.endsWith(".js")) { | |
// Hijack the fetch request | |
event.respondWith( | |
fetch(event.request.url) | |
.then(response => response.text()) | |
.then(body => { | |
// Replace module imports with the ones defined in the packages Map | |
const mappedBody = body.replace( | |
ES_MODULE_IMPORT_REGEX, | |
function replacer(match, p1) { | |
if (!packages.has(p1)) return match; | |
return match.replace(p1, packages.get(p1)); | |
} | |
); | |
// Return the updated module | |
return new Response(mappedBody, { | |
headers: new Headers({ | |
"Content-Type": "application/javascript" | |
}) | |
}); | |
}) | |
); | |
} | |
}); | |
self.addEventListener("install", event => { | |
event.waitUntil(self.skipWaiting()); | |
}); | |
self.addEventListener("activate", event => { | |
event.waitUntil(self.clients.claim()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment