├── .gitignore ├── BLOG.md ├── LICENSE ├── README.md ├── blocking-react.gif ├── blocking.gif ├── config ├── env.js ├── jest │ ├── cssTransform.js │ └── fileTransform.js ├── modules.js ├── paths.js ├── pnpTs.js ├── webpack.config.js └── webpackDevServer.config.js ├── non-blocking-react.gif ├── non-blocking.gif ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── scripts ├── build.js ├── start.js └── test.js ├── src ├── App.css ├── App.hooks.ts ├── App.test.tsx ├── App.tsx ├── index.css ├── index.tsx ├── logo.svg ├── my-first-worker │ ├── index.ts │ └── tsconfig.json ├── react-app-env.d.ts ├── serviceWorker.ts ├── setupTests.ts └── takeALongTimeToDoSomething.ts ├── tsconfig.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /BLOG.md: -------------------------------------------------------------------------------- 1 | # Web Workers, comlink, TypeScript and React 2 | 3 | JavaScript is famously single threaded. However, if you're developing for the web, you may well know that this is not quite accurate. There are [`Web Workers`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers): 4 | 5 | > A worker is an object created using a constructor (e.g. `Worker()`) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. 6 | 7 | Given that there is a way to use other threads for background processing, why doesn't this happen all the time? Well there's a number of reasons; not the least of which is the ceremony involved in interacting with Web Workers. Consider the following example that illustrates moving a calculation into a worker: 8 | 9 | ```js 10 | // main.js 11 | function add2NumbersUsingWebWorker() { 12 | const myWorker = new Worker("worker.js"); 13 | 14 | myWorker.postMessage([42, 7]); 15 | console.log('Message posted to worker'); 16 | 17 | myWorker.onmessage = function(e) { 18 | console.log('Message received from worker', e.data); 19 | } 20 | } 21 | 22 | add2NumbersUsingWebWorker(); 23 | 24 | // worker.js 25 | onmessage = function(e) { 26 | console.log('Worker: Message received from main script'); 27 | const result = e.data[0] * e.data[1]; 28 | if (isNaN(result)) { 29 | postMessage('Please write two numbers'); 30 | } else { 31 | const workerResult = 'Result: ' + result; 32 | console.log('Worker: Posting message back to main script'); 33 | postMessage(workerResult); 34 | } 35 | } 36 | ``` 37 | 38 | *This is not simple.* It's hard to understand what's happening. Also, this approach only supports a single method call. I'd much rather write something that looked more like this: 39 | 40 | ```js 41 | // main.js 42 | function add2NumbersUsingWebWorker() { 43 | const myWorker = new Worker("worker.js"); 44 | 45 | const total = myWorker.add2Numbers([42, 7]); 46 | console.log('Message received from worker', total); 47 | } 48 | 49 | add2NumbersUsingWebWorker(); 50 | 51 | // worker.js 52 | export function add2Numbers(firstNumber, secondNumber) { 53 | const result = firstNumber + secondNumber; 54 | return (isNaN(result)) 55 | ? 'Please write two numbers' 56 | : 'Result: ' + result; 57 | } 58 | ``` 59 | 60 | There's a way to do this using a library made by Google called [comlink](https://github.com/GoogleChromeLabs/comlink). This post will demonstrate how we can use this. We'll use TypeScript and webpack. We'll also examine how to integrate this approach into a React app. 61 | 62 | #### A use case for a Web Worker 63 | 64 | Let's make ourselves a TypeScript web app. We're going to use `create-react-app` for this: 65 | 66 | ```shell 67 | npx create-react-app webworkers-comlink-typescript-react --template typescript 68 | ``` 69 | 70 | Create a `takeALongTimeToDoSomething.ts` file alongside `index.tsx`: 71 | 72 | ```ts 73 | export function takeALongTimeToDoSomething() { 74 | console.log('Start our long running job...'); 75 | const seconds = 5; 76 | const start = new Date().getTime(); 77 | const delay = seconds * 1000; 78 | 79 | while (true) { 80 | if ((new Date().getTime() - start) > delay) { 81 | break; 82 | } 83 | } 84 | console.log('Finished our long running job'); 85 | } 86 | ``` 87 | 88 | To `index.tsx` add this code: 89 | 90 | ```ts 91 | import { takeALongTimeToDoSomething } from './takeALongTimeToDoSomething'; 92 | 93 | // ... 94 | 95 | console.log('Do something'); 96 | takeALongTimeToDoSomething(); 97 | console.log('Do another thing'); 98 | ``` 99 | 100 | When our application runs we see this behaviour: 101 | 102 | ![a demo of blocking](blocking.gif) 103 | 104 | The app starts and logs `Do something` and `Start our long running job...` to the console. It then blocks the UI until the `takeALongTimeToDoSomething` function has completed running. During this time the screen is empty and unresponsive. This is a poor user experience. 105 | 106 | #### Hello `worker-plugin` and `comlink` 107 | 108 | To start using comlink we're going to need to eject our `create-react-app` application. The way `create-react-app` works is by giving you a setup that handles a high percentage of the needs for a typical web app. When you encounter an unsupported use case, you can run the `yarn eject` command to get direct access to the configuration of your setup. 109 | 110 | Web Workers are not that commonly used in day to day development at present. Consequently there isn't yet a "plug'n'play" solution for workers supported by `create-react-app`. There's a number of potential ways to support this use case and you can track the various discussions happening against `create-react-app` that covers this. For now, let's eject with: 111 | 112 | ``` 113 | yarn eject 114 | ``` 115 | 116 | Then let's install the packages we're going to be using: 117 | 118 | - [`worker-plugin`](https://github.com/GoogleChromeLabs/worker-plugin) - this webpack plugin automatically compiles modules loaded in Web Workers 119 | - `comlink` - this library provides the RPC-like experience that we want from our workers 120 | 121 | ``` 122 | yarn add comlink worker-plugin 123 | ``` 124 | 125 | We now need to tweak our `webpack.config.js` to use the `worker-plugin`: 126 | 127 | ```js 128 | const WorkerPlugin = require('worker-plugin'); 129 | 130 | // .... 131 | 132 | plugins: [ 133 | new WorkerPlugin(), 134 | 135 | // .... 136 | 137 | ``` 138 | 139 | Do note that there's a number of `plugins` statements in the `webpack.config.js`. You want the top level one; look out for the `new HtmlWebpackPlugin` statement and place your `new WorkerPlugin(),` before that. 140 | 141 | #### Workerize our slow process 142 | 143 | Now we're ready to take our long running process and move it into a worker. Inside the `src` folder, create a new folder called `my-first-worker`. Our worker is going to live in here. Into this folder we're going to add a `tsconfig.json` file: 144 | 145 | ``` 146 | { 147 | "compilerOptions": { 148 | "strict": true, 149 | "target": "esnext", 150 | "module": "esnext", 151 | "lib": [ 152 | "webworker", 153 | "esnext" 154 | ], 155 | "moduleResolution": "node", 156 | "noUnusedLocals": true, 157 | "sourceMap": true, 158 | "allowJs": false, 159 | "baseUrl": "." 160 | } 161 | } 162 | ``` 163 | 164 | This file exists to tell TypeScript that this is a Web Worker. Do note the `"lib": [ "webworker" ` usage which does exactly that. 165 | 166 | Alongside the `tsconfig.json` file, let's create an `index.ts` file. This will be our worker: 167 | 168 | ```ts 169 | import { expose } from 'comlink'; 170 | import { takeALongTimeToDoSomething } from '../takeALongTimeToDoSomething'; 171 | 172 | const exports = { 173 | takeALongTimeToDoSomething 174 | }; 175 | export type MyFirstWorker = typeof exports; 176 | 177 | expose(exports); 178 | ``` 179 | 180 | There's a number of things happening in our small worker file. Let's go through this statement by statement: 181 | 182 | ```ts 183 | import { expose } from 'comlink'; 184 | ``` 185 | 186 | Here we're importing the `expose` method from comlink. Comlink’s goal is to make *expose*d values from one thread available in the other. The `expose` method can be viewed as the comlink equivalent of `export`. It is used to export the RPC style signature of our worker. We'll see it's use later. 187 | 188 | 189 | ```ts 190 | import { takeALongTimeToDoSomething } from '../takeALongTimeToDoSomething'; 191 | ``` 192 | 193 | Here we're going to import our `takeALongTimeToDoSomething` function that we wrote previously, so we can use it in our worker. 194 | 195 | ```ts 196 | const exports = { 197 | takeALongTimeToDoSomething 198 | }; 199 | ``` 200 | 201 | Here we're creating the public facing API that we're going to expose. 202 | 203 | ```ts 204 | export type MyFirstWorker = typeof exports; 205 | ``` 206 | 207 | We're going to want our worker to be strongly typed. This line creates a type called `MyFirstWorker` which is derived from our `exports` object literal. 208 | 209 | ```ts 210 | expose(exports); 211 | ``` 212 | 213 | Finally we expose the `exports` using comlink. We're done; that's our worker finished. Now let's consume it. Let's change our `index.tsx` file to use it. Replace our import of `takeALongTimeToDoSomething`: 214 | 215 | ```ts 216 | import { takeALongTimeToDoSomething } from './takeALongTimeToDoSomething'; 217 | ``` 218 | 219 | With an import of `wrap` from comlink that creates a local `takeALongTimeToDoSomething` function that wraps interacting with our worker: 220 | 221 | ```ts 222 | import { wrap } from 'comlink'; 223 | 224 | function takeALongTimeToDoSomething() { 225 | const worker = new Worker('./my-first-worker', { name: 'my-first-worker', type: 'module' }); 226 | const workerApi = wrap(worker); 227 | workerApi.takeALongTimeToDoSomething(); 228 | } 229 | ``` 230 | 231 | Now we're ready to demo our application using our function offloaded into a Web Worker. It now behaves like this: 232 | 233 | ![a demo of non-blocking](non-blocking.gif) 234 | 235 | There's a number of exciting things to note here: 236 | 237 | 1. The application is now non-blocking. Our long running function is now not preventing the UI from updating 238 | 2. The functionality is lazily loaded via a `my-first-worker.chunk.worker.js` that has been created by the `worker-plugin` and `comlink`. 239 | 240 | #### Using Web Workers in React 241 | 242 | The example we've showed so far demostrates how you could use Web Workers and why you might want to. However, it's a far cry from a real world use case. Let's take the next step and plug our Web Worker usage into our React application. What would that look like? Let's find out. 243 | 244 | We'll return `index.tsx` back to it's initial state. Then we'll make a simple adder function that takes some values and returns their total. To our `takeALongTimeToDoSomething.ts` module let's add: 245 | 246 | ```ts 247 | export function takeALongTimeToAddTwoNumbers(number1: number, number2: number) { 248 | console.log('Start to add...'); 249 | const seconds = 5; 250 | const start = new Date().getTime(); 251 | const delay = seconds * 1000; 252 | while (true) { 253 | if ((new Date().getTime() - start) > delay) { 254 | break; 255 | } 256 | } 257 | const total = number1 + number2; 258 | console.log('Finished adding'); 259 | return total; 260 | } 261 | ``` 262 | 263 | Let's start using our long running calculator in a React component. We'll update our `App.tsx` to use this function and create a simple adder component: 264 | 265 | ```tsx 266 | import React, { useState } from "react"; 267 | import "./App.css"; 268 | import { takeALongTimeToAddTwoNumbers } from "./takeALongTimeToDoSomething"; 269 | 270 | const App: React.FC = () => { 271 | const [number1, setNumber1] = useState(1); 272 | const [number2, setNumber2] = useState(2); 273 | 274 | const total = takeALongTimeToAddTwoNumbers(number1, number2); 275 | 276 | return ( 277 |
278 |

Web Workers in action!

279 | 280 |
281 | 282 | setNumber1(parseInt(e.target.value))} 285 | value={number1} 286 | /> 287 |
288 |
289 | 290 | setNumber2(parseInt(e.target.value))} 293 | value={number2} 294 | /> 295 |
296 |

Total: {total}

297 |
298 | ); 299 | }; 300 | 301 | export default App; 302 | ``` 303 | 304 | When you try it out you'll notice that entering a single digit locks the UI for 5 seconds whilst it adds the numbers. From the moment the cursor stops blinking to the moment the screen updates the UI is non-responsive: 305 | 306 | ![blocking react](./blocking-react.gif) 307 | 308 | So far, so classic. Let's Web Workerify this! 309 | 310 | We'll update our `my-first-worker/index.ts` to import this new function: 311 | 312 | ```ts 313 | import { expose } from "comlink"; 314 | import { 315 | takeALongTimeToDoSomething, 316 | takeALongTimeToAddTwoNumbers 317 | } from "../takeALongTimeToDoSomething"; 318 | 319 | const exports = { 320 | takeALongTimeToDoSomething, 321 | takeALongTimeToAddTwoNumbers 322 | }; 323 | export type MyFirstWorker = typeof exports; 324 | 325 | expose(exports); 326 | ``` 327 | 328 | Alongside our `App.tsx` file let's create an `App.hooks.ts` file. 329 | 330 | ```ts 331 | import { wrap, releaseProxy } from "comlink"; 332 | import { useEffect, useState, useMemo } from "react"; 333 | 334 | /** 335 | * Our hook that performs the calculation on the worker 336 | */ 337 | export function useTakeALongTimeToAddTwoNumbers( 338 | number1: number, 339 | number2: number 340 | ) { 341 | // We'll want to expose a wrapping object so we know when a calculation is in progress 342 | const [data, setData] = useState({ 343 | isCalculating: false, 344 | total: undefined as number | undefined 345 | }); 346 | 347 | // acquire our worker 348 | const { workerApi } = useWorker(); 349 | 350 | useEffect(() => { 351 | // We're starting the calculation here 352 | setData({ isCalculating: true, total: undefined }); 353 | 354 | workerApi 355 | .takeALongTimeToAddTwoNumbers(number1, number2) 356 | .then(total => setData({ isCalculating: false, total })); // We receive the result here 357 | }, [workerApi, setData, number1, number2]); 358 | 359 | return data; 360 | } 361 | 362 | function useWorker() { 363 | // memoise a worker so it can be reused; create one worker up front 364 | // and then reuse it subsequently; no creating new workers each time 365 | const workerApiAndCleanup = useMemo(() => makeWorkerApiAndCleanup(), []); 366 | 367 | useEffect(() => { 368 | const { cleanup } = workerApiAndCleanup; 369 | 370 | // cleanup our worker when we're done with it 371 | return () => { 372 | cleanup(); 373 | }; 374 | }, [workerApiAndCleanup]); 375 | 376 | return workerApiAndCleanup; 377 | } 378 | 379 | /** 380 | * Creates a worker, a cleanup function and returns it 381 | */ 382 | function makeWorkerApiAndCleanup() { 383 | // Here we create our worker and wrap it with comlink so we can interact with it 384 | const worker = new Worker("./my-first-worker", { 385 | name: "my-first-worker", 386 | type: "module" 387 | }); 388 | const workerApi = wrap(worker); 389 | 390 | // A cleanup function that releases the comlink proxy and terminates the worker 391 | const cleanup = () => { 392 | workerApi[releaseProxy](); 393 | worker.terminate(); 394 | }; 395 | 396 | const workerApiAndCleanup = { workerApi, cleanup }; 397 | 398 | return workerApiAndCleanup; 399 | } 400 | ``` 401 | 402 | The `useWorker` and `makeWorkerApiAndCleanup` functions make up the basis of a shareable worker hooks approach. It would take very little work to paramaterise them so this could be used elsewhere. That's outside the scope of this post but would be extremely straightforward to accomplish. 403 | 404 | Time to test! We'll change our `App.tsx` to use the new `useTakeALongTimeToAddTwoNumbers` hook: 405 | 406 | ```tsx 407 | import React, { useState } from "react"; 408 | import "./App.css"; 409 | import { useTakeALongTimeToAddTwoNumbers } from "./App.hooks"; 410 | 411 | const App: React.FC = () => { 412 | const [number1, setNumber1] = useState(1); 413 | const [number2, setNumber2] = useState(2); 414 | 415 | const total = useTakeALongTimeToAddTwoNumbers(number1, number2); 416 | 417 | return ( 418 |
419 |

Web Workers in action!

420 | 421 |
422 | 423 | setNumber1(parseInt(e.target.value))} 426 | value={number1} 427 | /> 428 |
429 |
430 | 431 | setNumber2(parseInt(e.target.value))} 434 | value={number2} 435 | /> 436 |
437 |

438 | Total:{" "} 439 | {total.isCalculating ? ( 440 | Calculating... 441 | ) : ( 442 | {total.total} 443 | )} 444 |

445 |
446 | ); 447 | }; 448 | 449 | export default App; 450 | ``` 451 | 452 | Now our calculation takes place off the main thread and the UI is no longer blocked! 453 | 454 | ![non blocking react](./non-blocking-react.gif) 455 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 John Reilly 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 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `yarn start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `yarn test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `yarn build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `yarn eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | -------------------------------------------------------------------------------- /blocking-react.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnnyreilly/webworkers-comlink-typescript-react/145f17050e0fc1e53b18c1df299c9b148dae6124/blocking-react.gif -------------------------------------------------------------------------------- /blocking.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnnyreilly/webworkers-comlink-typescript-react/145f17050e0fc1e53b18c1df299c9b148dae6124/blocking.gif -------------------------------------------------------------------------------- /config/env.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | 7 | // Make sure that including paths.js after env.js will read .env variables. 8 | delete require.cache[require.resolve('./paths')]; 9 | 10 | const NODE_ENV = process.env.NODE_ENV; 11 | if (!NODE_ENV) { 12 | throw new Error( 13 | 'The NODE_ENV environment variable is required but was not specified.' 14 | ); 15 | } 16 | 17 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use 18 | const dotenvFiles = [ 19 | `${paths.dotenv}.${NODE_ENV}.local`, 20 | `${paths.dotenv}.${NODE_ENV}`, 21 | // Don't include `.env.local` for `test` environment 22 | // since normally you expect tests to produce the same 23 | // results for everyone 24 | NODE_ENV !== 'test' && `${paths.dotenv}.local`, 25 | paths.dotenv, 26 | ].filter(Boolean); 27 | 28 | // Load environment variables from .env* files. Suppress warnings using silent 29 | // if this file is missing. dotenv will never modify any environment variables 30 | // that have already been set. Variable expansion is supported in .env files. 31 | // https://github.com/motdotla/dotenv 32 | // https://github.com/motdotla/dotenv-expand 33 | dotenvFiles.forEach(dotenvFile => { 34 | if (fs.existsSync(dotenvFile)) { 35 | require('dotenv-expand')( 36 | require('dotenv').config({ 37 | path: dotenvFile, 38 | }) 39 | ); 40 | } 41 | }); 42 | 43 | // We support resolving modules according to `NODE_PATH`. 44 | // This lets you use absolute paths in imports inside large monorepos: 45 | // https://github.com/facebook/create-react-app/issues/253. 46 | // It works similar to `NODE_PATH` in Node itself: 47 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders 48 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. 49 | // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. 50 | // https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 51 | // We also resolve them to make sure all tools using them work consistently. 52 | const appDirectory = fs.realpathSync(process.cwd()); 53 | process.env.NODE_PATH = (process.env.NODE_PATH || '') 54 | .split(path.delimiter) 55 | .filter(folder => folder && !path.isAbsolute(folder)) 56 | .map(folder => path.resolve(appDirectory, folder)) 57 | .join(path.delimiter); 58 | 59 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be 60 | // injected into the application via DefinePlugin in Webpack configuration. 61 | const REACT_APP = /^REACT_APP_/i; 62 | 63 | function getClientEnvironment(publicUrl) { 64 | const raw = Object.keys(process.env) 65 | .filter(key => REACT_APP.test(key)) 66 | .reduce( 67 | (env, key) => { 68 | env[key] = process.env[key]; 69 | return env; 70 | }, 71 | { 72 | // Useful for determining whether we’re running in production mode. 73 | // Most importantly, it switches React into the correct mode. 74 | NODE_ENV: process.env.NODE_ENV || 'development', 75 | // Useful for resolving the correct path to static assets in `public`. 76 | // For example, . 77 | // This should only be used as an escape hatch. Normally you would put 78 | // images into the `src` and `import` them in code to get their paths. 79 | PUBLIC_URL: publicUrl, 80 | } 81 | ); 82 | // Stringify all values so we can feed into Webpack DefinePlugin 83 | const stringified = { 84 | 'process.env': Object.keys(raw).reduce((env, key) => { 85 | env[key] = JSON.stringify(raw[key]); 86 | return env; 87 | }, {}), 88 | }; 89 | 90 | return { raw, stringified }; 91 | } 92 | 93 | module.exports = getClientEnvironment; 94 | -------------------------------------------------------------------------------- /config/jest/cssTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // This is a custom Jest transformer turning style imports into empty objects. 4 | // http://facebook.github.io/jest/docs/en/webpack.html 5 | 6 | module.exports = { 7 | process() { 8 | return 'module.exports = {};'; 9 | }, 10 | getCacheKey() { 11 | // The output is always the same. 12 | return 'cssTransform'; 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /config/jest/fileTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const camelcase = require('camelcase'); 5 | 6 | // This is a custom Jest transformer turning file imports into filenames. 7 | // http://facebook.github.io/jest/docs/en/webpack.html 8 | 9 | module.exports = { 10 | process(src, filename) { 11 | const assetFilename = JSON.stringify(path.basename(filename)); 12 | 13 | if (filename.match(/\.svg$/)) { 14 | // Based on how SVGR generates a component name: 15 | // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6 16 | const pascalCaseFilename = camelcase(path.parse(filename).name, { 17 | pascalCase: true, 18 | }); 19 | const componentName = `Svg${pascalCaseFilename}`; 20 | return `const React = require('react'); 21 | module.exports = { 22 | __esModule: true, 23 | default: ${assetFilename}, 24 | ReactComponent: React.forwardRef(function ${componentName}(props, ref) { 25 | return { 26 | $$typeof: Symbol.for('react.element'), 27 | type: 'svg', 28 | ref: ref, 29 | key: null, 30 | props: Object.assign({}, props, { 31 | children: ${assetFilename} 32 | }) 33 | }; 34 | }), 35 | };`; 36 | } 37 | 38 | return `module.exports = ${assetFilename};`; 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /config/modules.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | const chalk = require('react-dev-utils/chalk'); 7 | const resolve = require('resolve'); 8 | 9 | /** 10 | * Get additional module paths based on the baseUrl of a compilerOptions object. 11 | * 12 | * @param {Object} options 13 | */ 14 | function getAdditionalModulePaths(options = {}) { 15 | const baseUrl = options.baseUrl; 16 | 17 | // We need to explicitly check for null and undefined (and not a falsy value) because 18 | // TypeScript treats an empty string as `.`. 19 | if (baseUrl == null) { 20 | // If there's no baseUrl set we respect NODE_PATH 21 | // Note that NODE_PATH is deprecated and will be removed 22 | // in the next major release of create-react-app. 23 | 24 | const nodePath = process.env.NODE_PATH || ''; 25 | return nodePath.split(path.delimiter).filter(Boolean); 26 | } 27 | 28 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 29 | 30 | // We don't need to do anything if `baseUrl` is set to `node_modules`. This is 31 | // the default behavior. 32 | if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { 33 | return null; 34 | } 35 | 36 | // Allow the user set the `baseUrl` to `appSrc`. 37 | if (path.relative(paths.appSrc, baseUrlResolved) === '') { 38 | return [paths.appSrc]; 39 | } 40 | 41 | // If the path is equal to the root directory we ignore it here. 42 | // We don't want to allow importing from the root directly as source files are 43 | // not transpiled outside of `src`. We do allow importing them with the 44 | // absolute path (e.g. `src/Components/Button.js`) but we set that up with 45 | // an alias. 46 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 47 | return null; 48 | } 49 | 50 | // Otherwise, throw an error. 51 | throw new Error( 52 | chalk.red.bold( 53 | "Your project's `baseUrl` can only be set to `src` or `node_modules`." + 54 | ' Create React App does not support other values at this time.' 55 | ) 56 | ); 57 | } 58 | 59 | /** 60 | * Get webpack aliases based on the baseUrl of a compilerOptions object. 61 | * 62 | * @param {*} options 63 | */ 64 | function getWebpackAliases(options = {}) { 65 | const baseUrl = options.baseUrl; 66 | 67 | if (!baseUrl) { 68 | return {}; 69 | } 70 | 71 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 72 | 73 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 74 | return { 75 | src: paths.appSrc, 76 | }; 77 | } 78 | } 79 | 80 | /** 81 | * Get jest aliases based on the baseUrl of a compilerOptions object. 82 | * 83 | * @param {*} options 84 | */ 85 | function getJestAliases(options = {}) { 86 | const baseUrl = options.baseUrl; 87 | 88 | if (!baseUrl) { 89 | return {}; 90 | } 91 | 92 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 93 | 94 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 95 | return { 96 | '^src/(.*)$': '/src/$1', 97 | }; 98 | } 99 | } 100 | 101 | function getModules() { 102 | // Check if TypeScript is setup 103 | const hasTsConfig = fs.existsSync(paths.appTsConfig); 104 | const hasJsConfig = fs.existsSync(paths.appJsConfig); 105 | 106 | if (hasTsConfig && hasJsConfig) { 107 | throw new Error( 108 | 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.' 109 | ); 110 | } 111 | 112 | let config; 113 | 114 | // If there's a tsconfig.json we assume it's a 115 | // TypeScript project and set up the config 116 | // based on tsconfig.json 117 | if (hasTsConfig) { 118 | const ts = require(resolve.sync('typescript', { 119 | basedir: paths.appNodeModules, 120 | })); 121 | config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; 122 | // Otherwise we'll check if there is jsconfig.json 123 | // for non TS projects. 124 | } else if (hasJsConfig) { 125 | config = require(paths.appJsConfig); 126 | } 127 | 128 | config = config || {}; 129 | const options = config.compilerOptions || {}; 130 | 131 | const additionalModulePaths = getAdditionalModulePaths(options); 132 | 133 | return { 134 | additionalModulePaths: additionalModulePaths, 135 | webpackAliases: getWebpackAliases(options), 136 | jestAliases: getJestAliases(options), 137 | hasTsConfig, 138 | }; 139 | } 140 | 141 | module.exports = getModules(); 142 | -------------------------------------------------------------------------------- /config/paths.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const fs = require('fs'); 5 | const url = require('url'); 6 | 7 | // Make sure any symlinks in the project folder are resolved: 8 | // https://github.com/facebook/create-react-app/issues/637 9 | const appDirectory = fs.realpathSync(process.cwd()); 10 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath); 11 | 12 | const envPublicUrl = process.env.PUBLIC_URL; 13 | 14 | function ensureSlash(inputPath, needsSlash) { 15 | const hasSlash = inputPath.endsWith('/'); 16 | if (hasSlash && !needsSlash) { 17 | return inputPath.substr(0, inputPath.length - 1); 18 | } else if (!hasSlash && needsSlash) { 19 | return `${inputPath}/`; 20 | } else { 21 | return inputPath; 22 | } 23 | } 24 | 25 | const getPublicUrl = appPackageJson => 26 | envPublicUrl || require(appPackageJson).homepage; 27 | 28 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer 29 | // "public path" at which the app is served. 30 | // Webpack needs to know it to put the right