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

Add typescript support #55

Merged
merged 1 commit into from
Sep 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"parser": "babel-eslint",
"extends": [
"standard",
"standard-react",
"react-app",
"react-app/jest",
"plugin:prettier/recommended",
"prettier"
],
"env": {
"node": true
"node": true,
"serviceworker": true,
"browser": true
},
"parserOptions": {
"ecmaVersion": 2020,
Expand Down
59 changes: 35 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
[![NPM](https://img.shields.io/npm/v/@3m1/service-worker-updater.svg)](https://www.npmjs.com/package/@3m1/service-worker-updater)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
[![Test](https://github.com/emibcn/service-worker-updater/actions/workflows/test.js.yml/badge.svg)](https://github.com/emibcn/service-worker-updater/actions/workflows/test.js.yml)
![Coverage](https://raw.githubusercontent.com/emibcn/service-worker-updater/badges/main/test-coverage.svg)
[![BundlePhobia Minified Size](https://badgen.net/bundlephobia/min/@3m1/service-worker-updater)](https://bundlephobia.com/result?p=@3m1/service-worker-updater)
Expand All @@ -14,6 +13,7 @@
If you have opted-in for the `register` callback of `serviceWorkerRegistration` in the `index.js` of the [PWA version of Create React APP](https://create-react-app.dev/docs/making-a-progressive-web-app/), you probably want to allow your users to update the application once a new service worker has been detected.

## How it works

Usually, browsers check for a new service worker version of a PWA every few days, or whenever the user reloads the page. But reloading the page does not necessarily updates the service worker. As the code managing the service worker is usually outside the React components tree, the message of a _new service worker detected_ needs to be passed through another mechanism than props or contexts. Here, we use an event triggered over `document`, which will previously have been added a listener. The component that adds the listener **is** inside the React's components tree, and receives and saves the `resgistration` object for later use in the `onLoadNewServiceWorkerAccept` callback.

## Install
Expand All @@ -35,81 +35,92 @@ yarn add @3m1/service-worker-updater
This library is composed by 2 parts:

### `onServiceWorkerUpdate`

Callback to be added to the `serviceWorkerRegistration.register` call on your `index.js`. **This step is mandatory**, or the message will not arrive to your inner component.

```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import { onServiceWorkerUpdate } from '@3m1/service-worker-updater';
```tsx
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import * as serviceWorkerRegistration from './serviceWorkerRegistration'
import { onServiceWorkerUpdate } from '@3m1/service-worker-updater'

// Render the App
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
)

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
serviceWorkerRegistration.register({
onUpdate: onServiceWorkerUpdate
});
})

// ...
```

If you are already using the `onUpdate` callback, you need to add this callback in there:

```jsx
```tsx
serviceWorkerRegistration.register({
onUpdate: (registration) => {
// Your code goes here
// ...
// Then, call this callback:
onServiceWorkerUpdate(registration);
onServiceWorkerUpdate(registration)
}
});
})
```

### `withServiceWorkerUpdater`

HOC to wrap a component which will receive 2 extra `props`:

- `newServiceWorkerDetected`: boolean indicating if a new version of the service worker has been detected. If `true`, you should offer the user some way to update the app.
- `onLoadNewServiceWorkerAccept`: a callback which needs to be called once the user accepts to update to the new Service Worker. You choose what actions needs to be taken by the user to update the service worker (a button, a link, a countdown, ...). During its execution, **the page will be reloaded** in order to use the newly activated service worker. **WARNING!** Make sure all unsaved changes are saved before executing it.

```jsx
import React from 'react';
import { withServiceWorkerUpdater } from '@3m1/service-worker-updater';
```tsx
import React from 'react'
import {
withServiceWorkerUpdater,
ServiceWorkerUpdaterProps
} from '@3m1/service-worker-updater'

const Updater = (props) => {
const {newServiceWorkerDetected, onLoadNewServiceWorkerAccept} = props;
const Updater = (props: ServiceWorkerUpdaterProps) => {
const { newServiceWorkerDetected, onLoadNewServiceWorkerAccept } = props
return newServiceWorkerDetected ? (
<>
New version detected.
<button onClick={ onLoadNewServiceWorkerAccept }>Update!</button>
<button onClick={onLoadNewServiceWorkerAccept}>Update!</button>
</>
) : null; // If no update is available, render nothing
) : null // If no update is available, render nothing
}

export default withServiceWorkerUpdater(Updater);
export default withServiceWorkerUpdater(Updater)
```

The message sent to the service worker is `{type: 'SKIP_WAITING'}`, which is the one the [PWA version of Create React APP](https://create-react-app.dev/docs/making-a-progressive-web-app/) expects in order to launch its `self.skipWaiting()` method. If you have a different service worker configuration, you can change it here using the second optional argument:

```jsx
export default withServiceWorkerUpdater( Updater, {message: {myCustomType: 'SKIP_WAITING'} });
```tsx
export default withServiceWorkerUpdater(Updater, {
message: { myCustomType: 'SKIP_WAITING' }
})
```

Just before reloading the page, `'Controller loaded'` will be logged with `console.log`. If you want to change it, do it so:

```jsx
export default withServiceWorkerUpdater( Updater, {log: () => console.warn("App updated!")});
```tsx
export default withServiceWorkerUpdater(Updater, {
log: () => console.warn('App updated!')
})
```

## See also

- [React Service Worker](https://www.npmjs.com/package/@medipass/react-service-worker): A headless React component that wraps around the Navigator Service Worker API to manage your service workers. Inspired by Create React App's service worker registration script.
- [Service Worker Updater - React Hook & HOC](https://www.npmjs.com/package/service-worker-updater): This package provides React hook and HOC to check for service worker updates.
- [@loopmode/cra-workbox-refresh](https://www.npmjs.com/package/@loopmode/cra-workbox-refresh): Helper for `create-react-app` v2 apps that use the workbox service worker. Displays a UI that informs the user about updates and recommends a page refresh.
Expand Down
8 changes: 5 additions & 3 deletions example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
"eject": "react-scripts eject"
},
"dependencies": {
"@3m1/service-worker-updater": "^1.0.5",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "^4.0.3",
"@3m1/service-worker-updater": "^1.0.5"
"react-scripts": "^4.0.3"
},
"devDependencies": {
"@babel/plugin-syntax-object-rest-spread": "^7.8.3"
"@babel/plugin-syntax-object-rest-spread": "^7.8.3",
"@types/react": "^17.0.19",
"@types/react-dom": "^17.0.9"
},
"eslintConfig": {
"extends": "react-app"
Expand Down
14 changes: 0 additions & 14 deletions example/src/App.js

This file was deleted.

File renamed without changes.
17 changes: 17 additions & 0 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react'
import {
withServiceWorkerUpdater,
ServiceWorkerUpdaterProps
} from '@3m1/service-worker-updater'

const App = (props: ServiceWorkerUpdaterProps) => {
const { newServiceWorkerDetected, onLoadNewServiceWorkerAccept } = props
return newServiceWorkerDetected ? (
<>
New version detected.
<button onClick={onLoadNewServiceWorkerAccept}>Update!</button>
</>
) : null // If no update is available, render nothing
}

export default withServiceWorkerUpdater(App)
6 changes: 3 additions & 3 deletions example/src/index.js → example/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import * as serviceWorkerRegistration from './serviceWorkerRegistration'
import { onServiceWorkerUpdate } from '@3m1/service-worker-updater'

// Render the App
Expand All @@ -10,11 +10,11 @@ ReactDOM.render(
<App />
</React.StrictMode>,
document.getElementById('root')
);
)

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
serviceWorkerRegistration.register({
onUpdate: onServiceWorkerUpdate
});
})
1 change: 1 addition & 0 deletions example/src/react-app-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="react-scripts" />
55 changes: 32 additions & 23 deletions example/src/service-worker.js → example/src/service-worker.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */

// This service worker can be customized!
Expand All @@ -7,66 +8,74 @@
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.

import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
import { clientsClaim } from 'workbox-core'
import { ExpirationPlugin } from 'workbox-expiration'
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching'
import { registerRoute } from 'workbox-routing'
import { StaleWhileRevalidate } from 'workbox-strategies'

clientsClaim();
declare const self: ServiceWorkerGlobalScope

clientsClaim()

// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
precacheAndRoute(self.__WB_MANIFEST)

// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$')
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }) => {
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
} // If this is a URL that starts with /_, skip.
return false
}

// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
} // If this looks like a URL for a resource, because it contains // a file extension, skip.
return false
}

// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
} // Return true to signal that we want to use the handler.
return false
}

return true;
// Return true to signal that we want to use the handler.
return true
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
)

// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), // Customize this strategy as needed, e.g., by changing to CacheFirst.
({ url }) =>
url.origin === self.location.origin && url.pathname.endsWith('.png'),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
new ExpirationPlugin({ maxEntries: 50 })
]
})
);
)

// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
self.skipWaiting()
}
});
})

// Any other custom service worker logic can go here.
Loading