Move a WebAssembly module into its own thread
You can install wasm-worker using npm:
npm install --save wasm-worker
If you aren't using npm in your project, you can include wasmWorker using UMD build in the dist folder with
Once you have installed wasm-worker, supposing a CommonJS environment, you can import and use it in this way:
;// supposing an "add.wasm" module that exports a single function "add";// you can also run js functions inside the worker// to access importObject for example;
type JsCallback = context:module: WebAssemblyModuleinstance: WebAssemblyInstanceimportObject: importObjectparams: anyany;type WasmWorkerModule =exports:export: string: Promise<any>// run a js function inside the worker and provides it the given params// ⚠️ Caveat: the function you pass cannot rely on its surrounding scope, since it is executed in an isolated context.// Please use the "params" parameter to provide some values to the callbackPromise<any>;type Options =// the first 3 properties are used to create the Web Worker//name: stringtype: 'classic' | 'module'credentials: 'omit' | 'same-origin' | 'include'// the getImportObject function is used to get the options to instantiate the WebAssembly Module// ⚠️ Caveat: the function you pass cannot rely on its surrounding scope, since it is executed in an isolated context.//importObject;: Promise<WasmWorkerModule> // browser only: Promise<WasmWorkerModule>
if !windowfetch || !windowWorker || !windowWebAssembly...else...
If your app has a Content-Security-Policy,
worker-src data: and
script-src data: in your config.
This project is inspired by greenlet.
Copyright and License
Copyright (c) 2018, Matteo Basso.
wasm-worker source code is licensed under the MIT License.