I ran npx create-react-app my-app --template cra-template-pwa-typescript to build a Progressive Web App.
In the serviceworkerRegistration.ts file I have:
export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://cra.link/PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
This function is called in my index.ts file:
ReactDOM.render( ......)
serviceWorker.register();
reportWebVitals();
I read https://create-react-app.dev/docs/making-a-progressive-web-app/ and I don't understand why the service worker is not registered in my localhost and my console didn't print 'This web app is being served cache-first by a service worker. To learn more, visit https://cra.link/PWA'
When I hard code in index.html
<script>navigator.serviceWorker.register("frontend/src/service-worker.ts")</script>
the serviceworker is loaded (with errors due to my content security policy which doesn't allow this script execution in production mode).
How can I register properly in my localhost to do tests and code more complex features in my service worker? What did I do wrong? I have no errors or warnings.