Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replacing/Merging with noopServiceWorkerMiddleware for CRA Development mode #10

Open
Quadriphobs1 opened this issue May 27, 2018 · 2 comments
Labels

Comments

@Quadriphobs1
Copy link

Is it possible to also replace the noopServiceWorkerMiddleware of react-dev-utils during development mode.

@ThiefMaster
Copy link

I'd like to have an answer to this question as well :) When using the service worker just for push notifications (and no caching at all), then it makes absolutely no sense to not have it in development mode as well...

@Zemke
Copy link

Zemke commented Jan 17, 2020

This is hardcoded in the dev server. You'd need to use a differently named Service Worker file to avoid noopServiceWorkerMiddleware.

https://github.com/facebook/create-react-app/blob/master/packages/react-dev-utils/noopServiceWorkerMiddleware.js#L12

Then there's serviceWorker.js where the Service Worker generation is configured:

     window.addEventListener('load', () => {
-      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
+      const swUrl = process.env.NODE_ENV === 'production'
+        ? `${process.env.PUBLIC_URL}/service-worker.js`
+        : `${process.env.PUBLIC_URL}/append-sw.js`;

// ...

There I specify the one that's to be appended to the original. The development Service Worker would then only consist of what would be appended to the generated Service Worker in a production environment. That's just fine for me as in development I don't care so much about caching.

For a Service Worker to install at all you also need to leave out the environment check.

 export function register(config) {
-  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
+  if ('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) {

Your append-sw.js needs to be in public/ for the development server to correctly serve it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants