├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── react-app-rewired.config.js ├── src ├── App.css ├── App.test.tsx ├── App.tsx ├── MyComlinkWorker.worker.ts ├── MyWorker.worker.ts ├── index.css ├── index.tsx ├── logo.svg ├── react-app-env.d.ts ├── serviceWorker.ts └── setupTests.ts └── tsconfig.json /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: push 4 | 5 | jobs: 6 | build: 7 | name: Build 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout repository 11 | uses: actions/checkout@v2 12 | - name: Setup NodeJS 13 | uses: actions/setup-node@v1 14 | with: 15 | node-version: 14.15.x 16 | - name: Install dependencies 17 | run: npm ci 18 | - name: Build 19 | run: npm run build 20 | env: 21 | CI: true 22 | 23 | test: 24 | name: Test 25 | needs: build 26 | runs-on: ubuntu-latest 27 | steps: 28 | - name: Checkout repository 29 | uses: actions/checkout@v2 30 | - name: Setup NodeJS 31 | uses: actions/setup-node@v1 32 | with: 33 | node-version: 14.15.x 34 | - name: Install dependencies 35 | run: npm ci 36 | - name: Test 37 | run: npm run test 38 | env: 39 | CI: true 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | 3 | # Created by https://www.gitignore.io/api/node,visualstudiocode 4 | # Edit at https://www.gitignore.io/?templates=node,visualstudiocode 5 | 6 | ### Node ### 7 | # Logs 8 | logs 9 | *.log 10 | npm-debug.log* 11 | yarn-debug.log* 12 | yarn-error.log* 13 | lerna-debug.log* 14 | 15 | # Diagnostic reports (https://nodejs.org/api/report.html) 16 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 17 | 18 | # Runtime data 19 | pids 20 | *.pid 21 | *.seed 22 | *.pid.lock 23 | 24 | # Directory for instrumented libs generated by jscoverage/JSCover 25 | lib-cov 26 | 27 | # Coverage directory used by tools like istanbul 28 | coverage 29 | *.lcov 30 | 31 | # nyc test coverage 32 | .nyc_output 33 | 34 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 35 | .grunt 36 | 37 | # Bower dependency directory (https://bower.io/) 38 | bower_components 39 | 40 | # node-waf configuration 41 | .lock-wscript 42 | 43 | # Compiled binary addons (https://nodejs.org/api/addons.html) 44 | build/Release 45 | 46 | # Dependency directories 47 | node_modules/ 48 | jspm_packages/ 49 | 50 | # TypeScript v1 declaration files 51 | typings/ 52 | 53 | # TypeScript cache 54 | *.tsbuildinfo 55 | 56 | # Optional npm cache directory 57 | .npm 58 | 59 | # Optional eslint cache 60 | .eslintcache 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # next.js build output 79 | .next 80 | 81 | # nuxt.js build output 82 | .nuxt 83 | 84 | # rollup.js default build output 85 | dist/ 86 | 87 | # Uncomment the public line if your project uses Gatsby 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # https://create-react-app.dev/docs/using-the-public-folder/#docsNav 90 | # public 91 | 92 | # Storybook build outputs 93 | .out 94 | .storybook-out 95 | 96 | # vuepress build output 97 | .vuepress/dist 98 | 99 | # Serverless directories 100 | .serverless/ 101 | 102 | # FuseBox cache 103 | .fusebox/ 104 | 105 | # DynamoDB Local files 106 | .dynamodb/ 107 | 108 | # Temporary folders 109 | tmp/ 110 | temp/ 111 | 112 | ### VisualStudioCode ### 113 | .vscode/* 114 | !.vscode/settings.json 115 | !.vscode/tasks.json 116 | !.vscode/launch.json 117 | !.vscode/extensions.json 118 | 119 | ### VisualStudioCode Patch ### 120 | # Ignore all local history of files 121 | .history 122 | 123 | # End of https://www.gitignore.io/api/node,visualstudiocode 124 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Dominique Müller 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | # create-react-app-typescript-web-worker-setup 4 | 5 | Using **[Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)** in a 6 | **[TypeScript](https://github.com/microsoft/TypeScript)** **[React](https://github.com/facebook/react)** project based on 7 | **[create-react-app](https://github.com/facebook/create-react-app)**. 8 | 9 |
10 | 11 |


12 | 13 | ## How to use Web Workers in a TypeScript React app 14 | 15 | This project is an example React application that uses Web Workers. You can clone it and play around with it (see **[Commands](#commands)**). 16 | The following sub-chapters explain how to setup Web Worker support in a `create-react-app` project, and how to use Web Workers in your app - 17 | both vanilla and using **[Comlink](https://github.com/GoogleChromeLabs/comlink)**. 18 | 19 |
20 | 21 | ### 1. Install dependencies 22 | 23 | First of all, we need a few new dependencies. In particular: 24 | 25 | - We need **[react-app-rewired](https://github.com/timarney/react-app-rewired)** to hook into the Webpack configuration that `react-scripts` 26 | uses under the hood (without having to eject the config) 27 | - We use the Webpack **[worker-loader](https://github.com/webpack-contrib/worker-loader)** to integrate Web Workers into our build process 28 | 29 | Add both dependencies to your `package.json` file and install them. For example: 30 | 31 | ```diff 32 | { 33 | "devDependencies": { 34 | + "react-app-rewired": "2.1.x", 35 | + "worker-loader": "3.0.x" 36 | } 37 | } 38 | ``` 39 | 40 |
41 | 42 | ### 2. Customize the build process 43 | 44 | First, replace all mentions of `react-scripts` within the `scripts` area of your `package.json` file by `react-app-rewired`. This enables us 45 | to tap into the build process in the next step. For example: 46 | 47 | ```diff 48 | { 49 | "scripts": { 50 | - "start": "react-scripts start", 51 | + "start": "react-app-rewired start", 52 | - "build": "react-scripts build", 53 | + "build": "react-app-rewired build", 54 | - "test": "react-scripts test", 55 | + "test": "react-app-rewired test", 56 | } 57 | } 58 | ``` 59 | 60 | Then, create a file named `react-app-rewired.config.js` (or whatever name you prefer) within the root folder of your project. This file will 61 | be used by `react-app-rewired` when the build process runs, and allows us to customize the underlying Webpack configuration before the build 62 | runs. Fill it with the following content: 63 | 64 | ```js 65 | /** 66 | * React App Rewired Config 67 | */ 68 | module.exports = { 69 | // Update webpack config to use custom loader for worker files 70 | webpack: (config) => { 71 | // Note: It's important that the "worker-loader" gets defined BEFORE the TypeScript loader! 72 | config.module.rules.unshift({ 73 | test: /\.worker\.ts$/, 74 | use: { 75 | loader: 'worker-loader', 76 | options: { 77 | // Use directory structure & typical names of chunks produces by "react-scripts" 78 | filename: 'static/js/[name].[contenthash:8].js', 79 | }, 80 | }, 81 | }); 82 | 83 | return config; 84 | }, 85 | }; 86 | ``` 87 | 88 | Finally, reference the `react-app-rewired.config.js` file in your `package.json` file by adding the following line: 89 | 90 | ```diff 91 | { 92 | + "config-overrides-path": "react-app-rewired.config.js", 93 | } 94 | ``` 95 | 96 |
97 | 98 | ### 3. Create and use a Web Worker 99 | 100 | Now you can start using Web Workers! Two things are important here: Files that contain a Web Worker must end with `*.worker.ts`, and they 101 | must start with the following two lines of code in order to work nicely together with TypeScript: 102 | 103 | ```ts 104 | declare const self: DedicatedWorkerGlobalScope; 105 | export default {} as typeof Worker & { new (): Worker }; 106 | 107 | // Your code ... 108 | ``` 109 | 110 | In your application, you can import your Web Workers like a normal module, and instantiate them as a class. For example: 111 | 112 | ```ts 113 | import MyWorker from './MyWorker.worker'; 114 | 115 | const myWorkerInstance: Worker = new MyWorker(); 116 | ``` 117 | 118 | > Implementation pointers: 119 | > 120 | > - [Web Worker implementation](https://github.com/dominique-mueller/react-web-worker-experiment/blob/master/src/MyWorker.worker.ts) 121 | > - [Using the Web Worker](https://github.com/dominique-mueller/react-web-worker-experiment/blob/master/src/App.tsx#L9) 122 | 123 |
124 | 125 | ### Bonus: Using [Comlink](https://github.com/GoogleChromeLabs/comlink) 126 | 127 | Using Web Workers as is comes with the additional overhead of messaging between the main thread and the worker thread. 128 | **[Comlink](https://github.com/GoogleChromeLabs/comlink)** is a library by Googlers that simplifies the usage of Web Workers by turning 129 | the message-based communication into a "remote function execution"-like system. 130 | 131 | Within your React app, you can use Comlink just like you would expect. For example, expose your API within your worker: 132 | 133 | ```ts 134 | import { expose } from 'comlink'; 135 | 136 | export default {} as typeof Worker & { new (): Worker }; 137 | 138 | // Define API 139 | export const api = { 140 | createMessage: (name: string): string => { 141 | return `Hello ${name}!`; 142 | }, 143 | }; 144 | 145 | // Expose API 146 | expose(api); 147 | ``` 148 | 149 | Then, from within you main thread, wrap the instantiated worker and use the worker API (asynchronously): 150 | 151 | ```ts 152 | import { wrap } from 'comlink'; 153 | import MyComlinkWorker, { api } from './MyComlinkWorker.worker'; 154 | 155 | // Instantiate worker 156 | const myComlinkWorkerInstance: Worker = new MyComlinkWorker(); 157 | const myComlinkWorkerApi = wrap(myComlinkWorkerInstance); 158 | 159 | // Call function in worker 160 | myComlinkWorkerApi.createMessage('John Doe').then((message: string) => { 161 | console.log(message); 162 | }); 163 | ``` 164 | 165 | > Implementation pointers: 166 | > 167 | > - [Web Worker implementation](https://github.com/dominique-mueller/react-web-worker-experiment/blob/master/src/MyComlinkWorker.worker.ts) 168 | > - [Using the Web Worker](https://github.com/dominique-mueller/react-web-worker-experiment/blob/master/src/App.tsx#L14) 169 | 170 |
171 | 172 | ### A note on testing 173 | 174 | Soooo, Jest does not support Web Workers (see **[jest/#3449](https://github.com/facebook/jest/issues/3449)**). Plus, Jest does not use our 175 | customized Webpack configuration anyways. Thus - using one of the many ways you can mock stuff in Jest - mock away Web Workers when testing 176 | code that instantes them / works with them. 177 | 178 |

179 | 180 | ## Commands 181 | 182 | The following commands are available: 183 | 184 | | Command | Description | CI | 185 | | --------------------- | -------------------------------------------------- | ------------------ | 186 | | `npm start` | Creates a development build, running in watch mode | | 187 | | `npm run build` | Creates a production build | :heavy_check_mark: | 188 | | `npm run start:build` | Runs the production build | | 189 | | `npm run test` | Executes all unit tests | :heavy_check_mark: | 190 | | `npm run test:watch` | Executes all unit tests, running in watch mode | | 191 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "create-react-app-typescript-web-worker-setup", 3 | "version": "1.0.0", 4 | "description": "Using Web Workers in a TypeScript React project, based on create-react-app", 5 | "private": true, 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/dominique-mueller/create-react-app-typescript-web-worker-setup" 9 | }, 10 | "scripts": { 11 | "start": "react-app-rewired start", 12 | "start:build": "lite-server --baseDir=\"build\"", 13 | "build": "react-app-rewired build", 14 | "test": "react-app-rewired test --watchAll=false", 15 | "test:watch": "react-app-rewired test" 16 | }, 17 | "dependencies": { 18 | "comlink": "4.3.x", 19 | "react": "17.0.x", 20 | "react-dom": "17.0.x" 21 | }, 22 | "devDependencies": { 23 | "@testing-library/jest-dom": "5.11.x", 24 | "@testing-library/react": "11.1.x", 25 | "@testing-library/user-event": "12.2.x", 26 | "@types/jest": "26.0.x", 27 | "@types/node": "14.14.x", 28 | "@types/react": "16.9.x", 29 | "@types/react-dom": "16.9.x", 30 | "lite-server": "2.5.x", 31 | "react-app-rewired": "2.1.x", 32 | "react-scripts": "4.0.x", 33 | "ts-jest": "26.4.x", 34 | "ts-node": "9.0.x", 35 | "typescript": "4.0.x", 36 | "worker-loader": "3.0.x" 37 | }, 38 | "config-overrides-path": "react-app-rewired.config.js", 39 | "eslintConfig": { 40 | "extends": "react-app" 41 | }, 42 | "browserslist": { 43 | "production": [ 44 | ">0.2%", 45 | "not dead", 46 | "not op_mini all" 47 | ], 48 | "development": [ 49 | "last 1 chrome version", 50 | "last 1 firefox version", 51 | "last 1 safari version" 52 | ] 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dominique-mueller/create-react-app-typescript-web-worker-setup/92fa103e6b1f0a453b036aae2590f896f501fb7a/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 14 | 15 | 24 | create-react-app-typescript-web-worker-setup 25 | 26 | 27 | 28 |
29 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dominique-mueller/create-react-app-typescript-web-worker-setup/92fa103e6b1f0a453b036aae2590f896f501fb7a/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dominique-mueller/create-react-app-typescript-web-worker-setup/92fa103e6b1f0a453b036aae2590f896f501fb7a/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "create-react-app-typescript-web-worker-setup", 3 | "name": "create-react-app-typescript-web-worker-setup", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /react-app-rewired.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * React App Rewired Config 3 | */ 4 | module.exports = { 5 | // Update webpack config to use custom loader for worker files 6 | webpack: (config) => { 7 | // Note: It's important that the "worker-loader" gets defined BEFORE the TypeScript loader! 8 | config.module.rules.unshift({ 9 | test: /\.worker\.ts$/, 10 | use: { 11 | loader: 'worker-loader', 12 | options: { 13 | // Use directory structure & typical names of chunks produces by "react-scripts" 14 | filename: 'static/js/[name].[contenthash:8].js', 15 | }, 16 | }, 17 | }); 18 | 19 | return config; 20 | }, 21 | }; 22 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/App.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | jest.mock('./MyWorker.worker', () => { 6 | return class MockWorker { 7 | public postMessage(): void { 8 | // noop 9 | } 10 | }; 11 | }); 12 | 13 | jest.mock('./MyComlinkWorker.worker', () => { 14 | return class MockWorker {}; 15 | }); 16 | 17 | jest.mock('comlink', () => { 18 | return { 19 | wrap: () => { 20 | return { 21 | createMessage: () => { 22 | return Promise.resolve('Response'); 23 | }, 24 | }; 25 | }, 26 | }; 27 | }); 28 | 29 | test('renders learn react link', () => { 30 | render(); 31 | const linkElement = screen.getByText(/learn react/i); 32 | expect(linkElement).toBeInTheDocument(); 33 | }); 34 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import logo from './logo.svg'; 3 | import './App.css'; 4 | 5 | import MyWorker from './MyWorker.worker'; 6 | import MyComlinkWorker, { api } from './MyComlinkWorker.worker'; 7 | import { wrap } from 'comlink'; 8 | 9 | // Example: Using workers natively, e.g. by using "postMessage()" 10 | const myWorkerInstance: Worker = new MyWorker(); 11 | console.log('[App] MyWorker instance:', myWorkerInstance); 12 | myWorkerInstance.postMessage('This is a message from the main thread!'); 13 | 14 | // Example: Using workers via Comlink (comparable to remote execution) 15 | const myComlinkWorkerInstance: Worker = new MyComlinkWorker(); 16 | const myComlinkWorkerApi = wrap(myComlinkWorkerInstance); 17 | console.log('[App] MyComlinkWorker instance:', myComlinkWorkerInstance); 18 | myComlinkWorkerApi.createMessage('John Doe').then((message: string): void => { 19 | console.log('[App] MyComlinkWorker message:', message); 20 | }); 21 | 22 | function App() { 23 | return ( 24 |
25 |
26 | logo 27 |

28 | Edit src/App.tsx and save to reload. 29 |

30 | 31 | Learn React 32 | 33 |
34 |
35 | ); 36 | } 37 | 38 | export default App; 39 | -------------------------------------------------------------------------------- /src/MyComlinkWorker.worker.ts: -------------------------------------------------------------------------------- 1 | import { expose } from 'comlink'; 2 | 3 | export default {} as typeof Worker & { new (): Worker }; 4 | 5 | console.log('[MyComlinkWorker] Running.'); 6 | 7 | export const api = { 8 | createMessage: (name: string): string => { 9 | return `Hello ${name}!`; 10 | }, 11 | }; 12 | 13 | expose(api); 14 | -------------------------------------------------------------------------------- /src/MyWorker.worker.ts: -------------------------------------------------------------------------------- 1 | declare const self: DedicatedWorkerGlobalScope; 2 | export default {} as typeof Worker & { new (): Worker }; 3 | 4 | console.log('[MyWorker] Running.'); 5 | 6 | self.addEventListener('message', (event: MessageEvent): void => { 7 | console.log('[MyWorker] Incoming message from main thread:', event.data); 8 | }); 9 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | 6 | ReactDOM.render( 7 | 8 | 9 | , 10 | document.getElementById('root') 11 | ); 12 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src/serviceWorker.ts: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/), 19 | ); 20 | 21 | export function register(config: any) { 22 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 23 | // The URL constructor is available in all browsers that support SW. 24 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 25 | if (publicUrl.origin !== window.location.origin) { 26 | // Our service worker won't work if PUBLIC_URL is on a different origin 27 | // from what our page is served on. This might happen if a CDN is used to 28 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 29 | return; 30 | } 31 | 32 | window.addEventListener('load', () => { 33 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 34 | 35 | if (isLocalhost) { 36 | // This is running on localhost. Let's check if a service worker still exists or not. 37 | checkValidServiceWorker(swUrl, config); 38 | 39 | // Add some additional logging to localhost, pointing developers to the 40 | // service worker/PWA documentation. 41 | navigator.serviceWorker.ready.then(() => { 42 | console.log('This web app is being served cache-first by a service worker. To learn more, visit https://bit.ly/CRA-PWA'); 43 | }); 44 | } else { 45 | // Is not localhost. Just register service worker 46 | registerValidSW(swUrl, config); 47 | } 48 | }); 49 | } 50 | } 51 | 52 | function registerValidSW(swUrl: string, config: any) { 53 | navigator.serviceWorker 54 | .register(swUrl) 55 | .then((registration) => { 56 | registration.onupdatefound = () => { 57 | const installingWorker = registration.installing; 58 | if (installingWorker == null) { 59 | return; 60 | } 61 | installingWorker.onstatechange = () => { 62 | if (installingWorker.state === 'installed') { 63 | if (navigator.serviceWorker.controller) { 64 | // At this point, the updated precached content has been fetched, 65 | // but the previous service worker will still serve the older 66 | // content until all client tabs are closed. 67 | console.log('New content is available and will be used when all tabs for this page are closed. See https://bit.ly/CRA-PWA.'); 68 | 69 | // Execute callback 70 | if (config && config.onUpdate) { 71 | config.onUpdate(registration); 72 | } 73 | } else { 74 | // At this point, everything has been precached. 75 | // It's the perfect time to display a 76 | // "Content is cached for offline use." message. 77 | console.log('Content is cached for offline use.'); 78 | 79 | // Execute callback 80 | if (config && config.onSuccess) { 81 | config.onSuccess(registration); 82 | } 83 | } 84 | } 85 | }; 86 | }; 87 | }) 88 | .catch((error) => { 89 | console.error('Error during service worker registration:', error); 90 | }); 91 | } 92 | 93 | function checkValidServiceWorker(swUrl: string, config: any) { 94 | // Check if the service worker can be found. If it can't reload the page. 95 | fetch(swUrl, { 96 | headers: { 'Service-Worker': 'script' }, 97 | }) 98 | .then((response) => { 99 | // Ensure service worker exists, and that we really are getting a JS file. 100 | const contentType = response.headers.get('content-type'); 101 | if (response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1)) { 102 | // No service worker found. Probably a different app. Reload the page. 103 | navigator.serviceWorker.ready.then((registration) => { 104 | registration.unregister().then(() => { 105 | window.location.reload(); 106 | }); 107 | }); 108 | } else { 109 | // Service worker found. Proceed as normal. 110 | registerValidSW(swUrl, config); 111 | } 112 | }) 113 | .catch(() => { 114 | console.log('No internet connection found. App is running in offline mode.'); 115 | }); 116 | } 117 | 118 | export function unregister() { 119 | if ('serviceWorker' in navigator) { 120 | navigator.serviceWorker.ready 121 | .then((registration) => { 122 | registration.unregister(); 123 | }) 124 | .catch((error) => { 125 | console.error(error.message); 126 | }); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "allowSyntheticDefaultImports": true, 5 | "esModuleInterop": true, 6 | "forceConsistentCasingInFileNames": true, 7 | "isolatedModules": true, 8 | "jsx": "react", 9 | "lib": ["dom", "dom.iterable", "esnext", "webworker"], 10 | "module": "esnext", 11 | "moduleResolution": "node", 12 | "noEmit": true, 13 | "noFallthroughCasesInSwitch": true, 14 | "noImplicitAny": false, 15 | "noUnusedLocals": true, 16 | "noUnusedParameters": true, 17 | "resolveJsonModule": true, 18 | "skipLibCheck": true, 19 | "strict": true, 20 | "target": "es5" 21 | }, 22 | "include": ["src"] 23 | } 24 | --------------------------------------------------------------------------------