-
-
Notifications
You must be signed in to change notification settings - Fork 27.2k
Description
I couldn't make it work by this method. The console always printed:
ServiceWorker registration failed: DOMException: Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/sw.js'): The script has an unsupported MIME type ('text/html').
Thanks @antoaravinth for bringing this up. Myself I just wanted to use SW first as a POC then possibly something to include in a presentation.
@redixhumayun if you're still looking on how to do it in dev without changing the sw prod setup.
Create a simple sw register function in /src:
export default function LocalServiceWorkerRegister() {
const swPath = `${process.env.PUBLIC_URL}/sw.js`;
if ('serviceWorker' in navigator && process.env.NODE_ENV !== 'production') {
window.addEventListener('load', function() {
navigator.serviceWorker.register(swPath).then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
}
Then in index.tsx import and call:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import LocalServiceWorkerRegister from './sw-register';
//import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<App />,
document.getElementById('root') as HTMLElement
);
LocalServiceWorkerRegister();
//registerServiceWorker();
Then call your dev service worker file: sw.js (something different than prod) and put it in your /public folder.
npm start
Originally posted by @nick-gaudreau in #2396 (comment)