Skip to content

Instantly share code, notes, and snippets.

@damienmortini
Created January 27, 2020 18:03
Show Gist options
  • Save damienmortini/9d250a48877cf7b6eb1667d2718ed4c6 to your computer and use it in GitHub Desktop.
Save damienmortini/9d250a48877cf7b6eb1667d2718ed4c6 to your computer and use it in GitHub Desktop.
Service Worker to replace absolute module paths by relatives node_module paths
self.addEventListener('activate', () => {
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET' || event.request.destination !== 'script') {
return;
}
event.respondWith(fetch(event.request).then((response) => {
return response.clone().text().then((data) => {
data = data.replace(/(\bimport\b.+[`'"])([^./].+?)([`'"])/g, `$1${self.location.origin}/node_modules/$2$3`);
return new Response(data, {
status: response.status,
statusText: response.statusText,
headers: Object.assign({ 'Content-Type': 'application/javascript' }, response.headers),
});
});
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment