This repository was archived by the owner on Jan 26, 2019. It is now read-only.
This repository was archived by the owner on Jan 26, 2019. It is now read-only.
Support Web Workers #308
Open
Description
Upstream is working on adding Web Worker support: facebook/create-react-app#3660. It would be nice to support that as well here, with the necessary type declarations for Web Workers.
Currently, if I eject and modify my Webpack config to use worker-loader, I can only use a Typescript-based Web Worker by defining a custom .d.ts
file with a limited set of the APIs available in Web Workers (e.g. postMessage
). If I try to enable the webworker
lib in tsconfig.json
, I get type declaration conflicts with the dom
library, which is to be expected. Perhaps a tsconfig.webworkers.json
is needed that is only applied to Web Worker .ts
files?
What I have working so far:
yarn run eject
- Add
worker-loader
to dev dependencies. - Modify
webpack.config.dev.js
andwebpackage.config.prod.js
to include the following in the module rules:
{
test: /\.worker\.js$/,
use: { loader: 'worker-loader' }
}
- Create a
worker-loader.d.ts
custom typings file:
declare module 'worker-loader!*' {
class WebpackWorker extends Worker {
constructor();
}
// noinspection JSUnusedGlobalSymbols
export default WebpackWorker;
}
// noinspection TsLint
declare function postMessage(message: any, transfer?: any[]): void;
I can now define a test.worker.ts
like so:
import { someStuff } from './another/typescript/file';
// Post data to parent thread
postMessage({ foo: 'foo' });
// Respond to message from parent thread
addEventListener('message', event => console.log('message from main thread', event));
And create it in the app's index.tsx
like so:
import TestWorker from 'worker-loader!./test.worker';
const worker = new TestWorker();
worker.postMessage({ a: 1 });
worker.onmessage = event => {
console.log('onmessage from worker', event);
};
worker.addEventListener('message', event => {
console.log('message event from worker', event);
});
Metadata
Metadata
Assignees
Labels
No labels