UP | HOME

Integrate WebAssembly in any JavaScript project

Read: https://developers.google.com/web/updates/2019/01/emscripten-npm#integration_with_npm

By using Docker and NPM, we can integrate WebAssembly into any JS project.

First, create a new entry in NPM scripts to run build.sh, a script to build your WASM module, like this:

"build:emscripten": "docker run --rm -v $(pwd):/src trzeci/emscripten ./build.sh",

To avoid messing up with environment, we can use docker to hold the WASM build environment. The -v $(pwd) parameter is bind the current folder into docker container so we can actually build.

Second, write the build script, it will be something like:

emcc <src> -o /dist

All of the JavaScript and Wasm files will be put into dist folder, and this is where you use it.

Finally, you can use it by importing, just like any other JS modules.

<!doctype html>
<title>Emscripten + npm example</title>
Open the console to see the output from the wasm module.
<script type="module">
import wasmModule from "./my-module.js";

const instance = wasmModule({
  onRuntimeInitialized() {
     // Do something with instance
  }
});
</script>

Date: 2019-01-16 Wed 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41