How to load .wasm file in React-Native?

Viewed 6252

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!

2 Answers

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.

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

Related