Skip to content
Advertisement

Unable to import compiled javascript file from Emscripten for WebAssembly (C++ wrriten) to React

Hi I’ve compiled the C++ file via emcc (emscripten frontends). The output I expected is one .wasm file and .js file to implement javascript.

I build React application which try to import WebAssembly via .js module like below. (./wasm/dist/my-module is .js module compiled by emcc)

import { useEffect } from 'react';
import myModule from './wasm/dist/my-module'
import './App.css';

function App() {
  useEffect(() => {
    myModule().then((output: unknown) => console.log(output))
  }, [])

  
  return (
    <div className="App">
      <header className="App-header">
        <h1>Docker Wasm Builder.</h1>
      </header>
    </div>
  );
}

export default App;

The problem is the console in chrome expresses error “file:// protocol not allow” which is strange. Because I already build it and run the output in webserver (nginx). error from google chrome console

*I already tried to create a standalone .html file and import my .js module (from emcc compiler). It worked fine but not in React.

My emcc script

emcc 
${OPTIMIZE} 
--bind 
--no-entry 
-s STRICT=1 
-s ALLOW_MEMORY_GROWTH=1 
-s MALLOC=emmalloc 
-s MODULARIZE=1 
-s EXPORT_ES6=1 
-s ENVIRONMENT=web 
-o ./my-module.js 
src/wasm/my-module.cpp

Advertisement

Answer

Have a look at this. Basically, compile into -o something.mjs and add -s SINGLE_FILE=1. This will give you a single .mjs instead of a regular pair of .js and .wasm, avoiding all the trouble.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement