Skip to content
This repository has been archived by the owner on Jan 26, 2019. It is now read-only.

Support Web Workers #308

Open
doxxx opened this issue Apr 17, 2018 · 0 comments
Open

Support Web Workers #308

doxxx opened this issue Apr 17, 2018 · 0 comments

Comments

@doxxx
Copy link

doxxx commented Apr 17, 2018

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:

  1. yarn run eject
  2. Add worker-loader to dev dependencies.
  3. Modify webpack.config.dev.js and webpackage.config.prod.js to include the following in the module rules:
{
  test: /\.worker\.js$/,
  use: { loader: 'worker-loader' }
}
  1. 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);
});
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant