Blog, COLDSURF

Building Rust Code into JavaScript Using wasm-pack

#rust

#wasm

#js

1. Installing Rust and wasm-pack

  • If you don't have Rust installed on your machine, you can install it using the Rustup tool.
  • To install wasm-pack, follow the instructions from Wasm-Pack Installer.

2. Creating a Rust Template Using Cargo

cargo new --lib my-lib

Running this command will create a new directory called my-lib with a Rust template for a library.

3. Writing the Cargo.toml File

[package]
name = "<name>"
version = "<version>"
authors = ["<author>"]
edition = "<year>"
description = "<description>"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
wasm-bindgen = "0.2.63"

For more detailed information about Cargo.toml, refer to this guide: Wasm-Pack Cargo.toml Deep Dive.

4. Writing the Rust Code to Export to JavaScript

lib.rs

extern crate wasm_bindgen;

#[wasm_bindgen]
pub fn add(x: i32, y: i32) -> i32 {
    x + y
}

Here, we use wasm_bindgen to define a Rust function add(x, y) that will be callable from JavaScript.

5. Building with wasm-pack

wasm-pack build

After running wasm-pack build, a pkg directory will be generated. This contains the compiled WASM file along with JavaScript and TypeScript bindings created by wasm-bindgen.

6. Importing the Compiled Code into JavaScript

In your package.json, you can link the compiled package:

{
  "dependencies": {
    "rust-wasm": "file:../pkg",
    ...
  }
}

Now, you can import the Rust function in your JavaScript/TypeScript code:

import * as wasm from "rust-wasm/rust_wasm";

alert(wasm.add(1, 2)); // Alerts: 3

References:

  • rust-wasm-ts-template by utilForever
  • Official wasm-pack documentation
ā† Go home