Becavalier / Book-DISO-WebAssembly

A book related repository which name is 《深入浅出 WebAssembly》
MIT License
72 stars 17 forks source link

[Emscripten] Use "-s MODULARIZE" to initialize module in an async style. #1

Open Becavalier opened 6 years ago

Becavalier commented 6 years ago

It seems like the latest Emscripten toolchain has a decision to remove the "--post-js" option, here we can use "-s MODULARIZE" to initialize module as a replacement. FYI:

modularize.cc

#include <emscripten.h>
#include <iostream>

using namespace std;

int main (int argc, char **argv) {
  cout << "Hello, Emscripten!" << endl;
  return 0;
}

extern "C" int EMSCRIPTEN_KEEPALIVE add (int x, int y) {
  return x + y;
}

modularize.html (generated by "emcc", need to revise)

...
<script async type="text/javascript" src="module.js"></script>
<script>
  window.onload = function() {
    MyModule().then(function(Module) {
      console.log(Module['asm']['_add'](1, 2));
    });
  }
</script>
...

CMD:

sudo emcc modularize.cc -s WASM=1 -o modularize.html -O3 -s MODULARIZE=1 -s 'EXPORT_NAME="MyModule"'

*BTW, we can also use --pre-js param to append JavaScript code into the resulting script file.