Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
140 lines (111 sloc) 3.28 KB

The hello example

In this example, we setup a string hello world WASM demo and demonstrate interaction with the browser's JS host. Since the string type is NOT natively supported by WASM, we use the wasm-pack and wasm-bindgen utilities to generate corresponding call stub objects in JS.

Set up

$ sudo apt-get update
$ sudo apt-get -y upgrade
$ sudo apt install build-essential

$ sudo apt-get -y install apache2
$ sudo chown -R $USER:$USER /var/www/html
$ sudo systemctl start apache2

$ curl --proto '=https' --tlsv1.2 -sSf | sh
$ source $HOME/.cargo/env

$ curl -sSf | sh

Create new project

$ cargo new --lib hello
$ cd hello

Change the cargo config file

Add the following to the Cargo.toml file.

name = "hello_lib"
path = "src/"
crate-type =["cdylib"]

wasm-bindgen = "0.2.50"

Write Rust code

Below is the entire content of the src/ file.

use wasm_bindgen::prelude::*;

pub fn say(s: String) -> String {
  let r = String::from("hello ");
  return r + &s;

Build the WASM bytecode

$ wasm-pack build --target web

Create a new HTML folder

$ mkdir html
$ cp pkg/hello_lib_bg.wasm html/
$ cp pkg/hello_lib.js html/

Note the hello_lib.js file is generated by wasmp-apck and contains the "glue code" to pass data between the JS host and WASM VM.

Create an html file

Below is the content of the html/index.html file.

    <link rel="stylesheet" href="" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
    <script type="module">
      import init, { say } from './hello_lib.js';
      async function run() {
        await init();
        // const result = say("Michael");
        // console.log(result);
        var buttonOne = document.getElementById('buttonOne');
        buttonOne.addEventListener('click', function() {
          var input = $("#nameInput").val();
        }, false);
    <div class="row">
      <div class="col-sm-4"></div>
      <div class="col-sm-4">
        <b>Wasm - Say hello</b>
      <div class="col-sm-4"></div>
    <hr />
    <div class="row">
      <div class="col-sm-2"></div>
      <div class="col-sm-4">What is your name?</div>
      <div class="col-sm-4"> Click the button</div>
      <div class="col-sm-2"></div>
    <div class="row">
      <div class="col-sm-2"></div>
      <div class="col-sm-4">
        <input type="text" id="nameInput" placeholder="1", value="1">
      <div class="col-sm-4">
        <button class="bg-light" id="buttonOne">Say hello</button>
      <div class="col-sm-2"></div>

Deploy the static files to Apache

$ cp html/* /var/www/html/

You can’t perform that action at this time.