The maintainer of this website has a Spotify Coding Playlist of their Lo-fi Hip Hop beats!

WebAssembly Logo

Wasm By Example

Language:

Exports

Overview

In our Hello World Example, we called a function exported from WebAssembly, in our Javascript. Let's dive a little deeper into exports and how they are used.


Implementation

If you haven't done so already, you should set up your project following the steps laid out in the Hello World Example example.

First, let's add the following to our src/lib.rs file:

// The wasm-pack uses wasm-bindgen to build and generate JavaScript binding file.
// Import the wasm-bindgen crate.
use wasm_bindgen::prelude::*;

// This exports an add function.
// It takes in two 32-bit integer values
// And returns a 32-bit integer value.
#[wasm_bindgen]
pub fn call_me_from_javascript(a: i32, b: i32) -> i32 {
  return add_integer_with_constant(a, b);
}

// A NOT exported constant
// Rust does not support exporting constants
// for Wasm (that I know of).
const ADD_CONSTANT: i32 = 24;

// A NOT exported function
// It takes in two 32-bit integer values
// And returns a 32-bit integer value.
fn add_integer_with_constant(a: i32, b: i32) -> i32 {
  return a + b + ADD_CONSTANT;
}

Then, let's compile that using wasm-pack, which will create a pkg/ directory:

wasm-pack build --target web

Next, lets create an index.js file to load and run our wasm output. Let's import the wasm initialization module from pkg/exports.js that was generated by wasm-pack. Then, let's call the module passing in the path to our wasm file at pkg/exports_bg.wasm that was generated by wasm-pack. Then, let's go ahead and call out exported functions, and explore what functions were NOT exported:

NOTE: In this example, we are using the exported function from the wasm module directly to help highlight the WebAssembly API. wasm-bindgen generates JavaScript bindings code that can be imported as an ES6 import, and is the reccomended way to work with your Rust Wasm modules. These JavaScript bindings are shown in the "Passing High Level Data Types with wasm-bindgen" example.

import wasmInit from "./pkg/exports.js";

const runWasm = async () => {
  // Instantiate our wasm module
  const rustWasm = await wasmInit("./pkg/exports_bg.wasm");

  // Call the Add function export from wasm, save the result
  const result = rustWasm.call_me_from_javascript(24, 24);

  console.log(result); // Should output '72'
  console.log(rustWasm.ADD_CONSTANT); // Should output 'undefined'
  console.log(rustWasm.add_integer_with_constant); // Should output 'undefined'
};
runWasm();

Lastly, lets load our ES6 Module, index.js Javascript file in our index.html. And you should get something similar to the demo (Source Code) below!


Demo

Next let's take a look at WebAssembly Linear Memory.