WebAssembly, Typescript, Web Workers and create-react-app
The runnable code and template for an application can be found here.
More explanation on how to get .wasm to play nice with create-react-app
can be found here.
Disclaimer
At the time of writing, this create-react-app
doesn’t technically support web workers, but it’s not too much of a hack.
The limit of my create-react-app
modification is the following snippet in project_root/config-overrides.js
Setting up the project
I’m starting with my basic wasm-react-template, which can be cloned here, and read about here. I ran create-react-app --typescript
and configured my build paths accordingly. You should now have a relatively clean slate from create-react-app
Rewiring
I use https://github.com/timarney/react-app-rewired to set config.output.globalObject = 'this'
to prevent the worker from trying to access the window
object.
Removing this line makes our worker error out. This PR will apparently add support for workers in CRA, however, as of writing this, it hasn’t been merged.
root/config-overrides.js
App.tsx
We’re going to hack in the worker-loader
plugin. ESLint
and Typescript
won't like this, but I don’t care.
The following three lines are the important ones out of App.tsx
/* eslint import/no-webpack-loader-syntax:0 */
// @ts-ignore
import MyWorker from 'worker-loader?name=dist/[name].js!./worker'
https://gist.github.com/7a7d77df7275b9d38e8a412e42b01674
worker.ts
The rxjs
isn’t required, but it lets me read printf
s from my C program. We’ll receive a string, which we’ll post to our wasm
and hope that we get the same string back
// @ts-ignore Workers don't have the window object
self.window = self;// @ts-ignore
const ctx: Worker = self as any;
The .wasm
It will read your text from a file, and then write it to a new file. File-based IO is the only way to process large amounts of data, which is why I chose this example. See here for information on how this works.