Integrate WebAssembly in any JavaScript project


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

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

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

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

Date: 2019-01-16 Wed 00:00

Author: Huy Tran

Created: 2020-02-09 Sun 14:59