List of tutorials/projects experiencing OCaml and Rust mixed code running together in the browser.
Before starting, read the section about setting up the environment.
The general idea is to compile Rust into wasm and exporting some functions in JavaScript as a ES module.
On the OCaml side, js_of_ocaml is used to compile OCaml code to JavaScript. The
Caml code uses usual require
function to use functions from the ES module
generated by wasm-bindgen, and then get access to the Rust code.
Exchanging values between OCaml and Rust must be performed very carefully. TODO: add link to the tutorials playing with values
Most of the tutorials will be focused on Caml calling Rust, and not the opposite. Webpack is then used to bundle the JavaScript generated by Caml and the ES module generated by wasm-binding, and potentially additional npm packages.
wasm-pack build --target nodejs
will build a ES module than can be used in NodeJS. Imagine you have a
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn return_zero() -> u64 {
0
}
built with wasm-pack build --target nodejs
. You can after that use
node --experimental-modules --experimental-wasm-modules
> var t = require("./pkg/js_of_ruml.js")
> t.return_zero()
The default build target is bundler
which requires a bundler (like webpack) afterwards.
- It looks like there are some issues related to
wasm-opt
(WASM optimizer) while building withwasm-pack
. Adding these build options in the toml fix temporarily the issue
# https://github.com/rustwasm/wasm-pack/issues/886
[package.metadata.wasm-pack.profile.release]
wasm-opt = ["-O2", "--enable-mutable-globals"]
- wasm-pack: tools to get a workflow to build wasm code from Rust.
- rustwasm: book about Rust and WASM
- Awesome Rust/WASM: list of projects related to Rust/WASM interop
Install wasm-pack
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
To build the Rust code and use it in Node, install node using nvm, and install
the latest Node version (nvm install 12.18.3
followed by nvm use 12.18.3
).