Skip to content

Instantly share code, notes, and snippets.

@yurydelendik
Last active November 2, 2016 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yurydelendik/37566c46197f6208dc457c680810f595 to your computer and use it in GitHub Desktop.
Save yurydelendik/37566c46197f6208dc457c680810f595 to your computer and use it in GitHub Desktop.

Using WebAssembly code as JavaScript modules

Simple project structure and dependencies:

# Prepare directory and project
mkdir answer
cd answer
npm init # answer all/most with default values
npm install jspm
# We need system.js for magic
node_modules/.bin/jspm init # answer all/most with default values
# WASM module loader
node_modules/.bin/jspm install wasm=npm:system-wasm

Project files:

  1. Create index.html (see below)

  2. Create main.js (see below)

  3. Create answer.wasm (or data:application/wasm;base64,AGFzbQ0AAAABhYCAgAABYAABfwOCgICAAAEABoGAgIAAAAeNgICAAAEJZ2V0QW5zd2VyAAAKioCAgAABhICAgAAAQSoL):

a. Install wast-to-wasm converter, e.g. `npm install spidermonkey-m-wabt`

b. Save answer.wast (see below)

c. Convert e.g. `node_modules/.bin/sm-wabt wast2wasm answer.wast answer.wasm`      
  1. Start a web server and navigate e.g. http://localhost:8000/index.html

(more is possible, e.g. wasm can depend on JS module)

(module
(func $getAnswer (result i32) (i32.const 42))
(export "getAnswer" $getAnswer))
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<script>
System.import('main.js');
</script>
var a = require('answer.wasm!');
console.log('Answer: ' + a.getAnswer());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment