Parse WAT module, compile to WebAssembly binary, and instantiate to compute 'add(20, 22)' result (42).

by Will Stott

HTML

<script src="https://unpkg.com/[email protected]/index.js"></script>

JavaScript

WabtModule().then((wabt) => {
  const out = document.getElementById('out');
  const log = (...xs) => (out.textContent += xs.join(' ') + '\n');

  // Minimal WAT module: exports an `add` function
  const wat = `
    (module
      (import "my" "funcs.yes" (func $imp_func (result i32)))
      (func (export "add") (param i32 i32) (result i32)
        local.get 0
        local.get 1
        i32.add
      )
      (func (export "get") (result i32)
        call $imp_func
      )
    )
  `;

  // Parse WAT and produce a WASM binary
  const module = wabt.parseWat('inline.wat', wat);

  // Optional: run validations / finalize
  module.resolveNames();
  module.validate();

  const { buffer } = module.toBinary({
    log: false,
    write_debug_names: true,
  });

  // Instantiate and call the export
  WebAssembly.instantiate(buffer, {
    'my.funcs.prototype': { yes: () => 43 },
    my: {funcs: { yes: () => 43 }}
  }).then(({ instance }) => {
    // const result = instance.exports.add(20, 22);
    const result = instance.exports.get();

    console.log('add(20, 22) =', result); // -> 42
  })
}).catch((e) => {console.error(e.toString())});;