I am creating a React App using the Create React App utility and I want to override the default service worker that it provides.
Since I don't want to eject my app, I am using the workbox-build
package to create my service worker (I also used yarn to install the workbox-sw
package).
My service worker code is the following:
/* eslint-disable no-restricted-globals */
import * as core from 'workbox-core';
import * as routing from 'workbox-routing';
import * as strategies from 'workbox-strategies';
import * as precaching from 'workbox-precaching';
self.addEventListener('message', event => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
core.clientsClaim();
routing.registerRoute(
new RegExp('^https://fonts.googleapis.com'),
new strategies.StaleWhileRevalidate({
cacheName: 'google-fonts-stylesheets-v1',
})
);
precaching.precacheAndRoute([]);
routing.registerNavigationRoute(
precaching.getCacheKeyForURL('/index.html'), {
blacklist: [/^\/_/, /\/[^/?]+\.[^/]+$/],
}
);
And my workbox-build
script is:
const workboxBuild = require('workbox-build');
// NOTE: This should be run *AFTER* all your assets are built
const buildSW = () => {
// This will return a Promise
return workboxBuild.injectManifest({
swSrc: 'src/service-worker.js',
swDest: 'build/service-worker.js',
globDirectory: 'build',
globPatterns: [
'**\/*.{js,css,html,png,json}',
]
}).then(({
count,
size,
warnings
}) => {
// Optionally, log any warnings and details.
warnings.forEach(console.warn);
console.log(`${count} files will be precached, totaling ${size} bytes.`);
});
}
buildSW();
For registering the service worker I am using:
import { Workbox } from 'workbox-window';
export function register() {
if ('serviceWorker' in navigator) {
const wb = new Workbox('/service-worker.js');
wb.register();
}
}
However when I run my App I get these errors:
service-worker.js:2 Uncaught SyntaxError: Cannot use import statement outside a module
:3000/107/aggregator:1 Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/service-worker.js'): ServiceWorker script evaluation failed
What am I doing wrong?
There is no module support in workers yet.
importScripts() could do the job for you, but it can not import modules, meaning anything with an "export" keyword inside.
https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With