I am trying to import a module generated with emscripten as a es6 module. I am trying with the basic example from emscripten doc.
This is the command I am using to generate the js module from the C module:
emcc example.cpp -o example.js -s EXPORTED_FUNCTIONS="['_int_sqrt']" -s EXTRA_EXPORTED_RUNTIME_METHODS="['ccall', 'cwrap']" -s EXPORT_ES6=1 -s MODULARIZE=1
The C module :
#include <math.h>
extern "C" {
int int_sqrt(int x) {
return sqrt(x);
}
}
Then importing the generated js module:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Wasm example</title>
</head>
<body>
<script type="module">
import Module from './example.js'
int_sqrt = Module.cwrap('int_sqrt', 'number', ['number']);
console.log(int_sqrt(64));
</script>
</body>
</html>
This is failing because cwrap is not available on the Module object:
Uncaught TypeError: Module.cwrap is not a function
To conditionally import an ES6 module with JavaScript, we can use the import function. const myModule = await import(moduleName); in an async function to call import with the moduleName string to import the module named moduleName . And then we get the module returned by the promise returned by import with await .
ES6 module loaders will be asynchronous while node.
Examples of side effects:A polyfill that enables ES6 features in the browsers that don't support them, like babel polyfill is a side effect. Many jQuery plugins attach themselves to the global jQuery object. Analytics modules that run in the background, monitor user interaction, and send the data to a server.
As you're using MODULARIZE
, you have to make an instance of the Module first.
import Module from './example.js'
const mymod = Module();
const int_sqrt = mymod.cwrap('int_sqrt', 'number', ['number']);
console.log(int_sqrt(64));
You could also try the MODULARIZE_INSTANCE
option.
You may need to wait for it to finish initialising - I'm not sure when the function is so simple. That would look like this:
import Module from './example.js'
Module().then(function(mymod) {
const int_sqrt = mymod.cwrap('int_sqrt', 'number', ['number']);
console.log(int_sqrt(64));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With