19

I have been trying to load a WebAssembly (.wasm) file - generated C++ code compiled to WebAssembly by Emscripten - in a React-Native app.

This is my code to fetch the .wasm file:

import fs from 'react-native-fs';

if (!global.WebAssembly) {
  global.WebAssembly = require('webassemblyjs');
}

const fetchWasm = async () => {
  const wasm = await fetch(`${fs.MainBundlePath}/calculator.wasm`);

  console.log(wasm);
  // Returns: Response {type: "default", status: 200, ok: true, statusText: undefined, headers: Headers, …}

  const mod = await WebAssembly.instantiateStreaming(wasm);

  console.log(mod);
  // Throws: TypeError: Failed to execute 'compile' on 'WebAssembly': An argument must be provided, which must be a Response or Promise<Response> object
};

I tried everything in the Google search results I could find, but nothing worked so far. Unfortunately, the most related questions were unanswered.

Is there anyone who knows what I am doing wrong? Any help would be greatly appreciated!

  • According to the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming) WebAssembly.instantiateStreaming, returns a promise. In order to retrieve its output i think you need to add a `.then()` – Kevin Hernandez Mar 13 '20 at 16:13
  • 2
    I use the await to get the result of the Promise and assign it to the 'mod' variable. – Joris van Dongen Mar 13 '20 at 16:33
  • Try: `const mod = await WebAssembly.instantiateStreaming(wasm).then(mod => console.log(mod));` – Kevin Hernandez Mar 13 '20 at 16:35
  • Just a wild guess because I think I've ran into a similar issue before. I think your `wasm` variable is not an actual object, otherwise `console.log` would not append "Response" to the beginning. You probably need to use `JSON.parse(wasm)`. – Tom Daniel Sep 08 '20 at 00:17
  • Did you manage to get this working? – Kay Mar 06 '21 at 10:07
  • have you added wasm in `assetExts` of metro.config.js? – Horst Sep 23 '21 at 09:54

2 Answers2

2

There is one thing to be aware when wanting to load wasm :

Your webserver must report .wasm mime type as "application/wasm" , otherwise you won't be able loading it.

sancelot
  • 1,905
  • 12
  • 31
1

I assume still React-native JS runtime JSC still not support WebAssembly in Android build the issue is still open https://github.com/react-native-community/jsc-android-buildscripts/issues/113

Another way is to use Webview but I assume it is not you are expecting. https://github.com/ExodusMovement/react-native-wasm

Asanka
  • 552
  • 6
  • 15