...

/

Sharing Classes from JavaScript with Rust

Sharing Classes from JavaScript with Rust

Learn how to use JavaScript classes in the Rust project.

We'll cover the following...

Sharing JavaScript classes with Rust is also made easy with #[wasm_bindgen]. Let’s look at how to achieve it.

JavaScript classes are objects with some methods. Rust is a strictly typed language. This means the Rust compiler needs to have concrete bindings. Without them, the compiler complains, because it needs to know about the lifetime of an object. We need a way to ensure the compiler has this API available at runtime.

The extern C function block helps out here. The extern C makes a function name available in Rust.

Getting started with the project

In this example, let’s see how to share a class from JavaScript with Rust:

  1. Let’s create a new project:

Press + to interact
cargo new --lib class_from_js_world
  1. Define the wasm-bindgen dependency for the project. Open the cargo.toml file and add the following content:

Press + to interact
[package]
name = "class_from_js_world"
version = "0.1.0"
authors = ["Educative"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.68"

Please copy over package.json, index.js, and webpack-config.js from the previous section. Then, run npm install.

Note: We have already copied the package.json, index.js and ...