Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load .wasm file in React-Native?

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!

like image 561
Joris van Dongen Avatar asked Mar 13 '20 16:03

Joris van Dongen


People also ask

Can I use WebAssembly in react native?

A polyfill to use WebAssembly in React Native. This package instantiates WebAssembly in a native WebView environment and makes the communication with React Native to simulate original behavior.

How do I load Wasm in react?

Use file: notation to import the wasm package that we created using wasm-pack in the package. json. After adding the package, you just need to run npm install to install the packages. One additional thing you need to take care of is changing the scripts from react-scripts to craco .

How is react native built?

React Native uses JavaScript to compile the app's user interface, but using native-OS views. For more complex features, it allows code implementation in OS-native languages (Swift and Objective-C for iOS, and Java and Kotlin for Android).


1 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.

like image 146
sancelot Avatar answered Sep 20 '22 11:09

sancelot