Skip to main content

2 posts tagged with "rust"

View All Tags

· One min read
Moazzem Hossen
  • Install Rust and WebAssembly
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup update
cargo install cargo-generate
rustup target add wasm32-unknown-unknown
cargo install wasm-pack
  • Create a new project
cargo new rust-wasm-helloworld --lib
cd rust-wasm-helloworld
  • Add dependencies by updating Cargo.toml
[package]
name = "rust-wasm-helloworld"
version = "0.1.0"
edition = "2021"

[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["console"] }

[lib]
crate-type = ["cdylib", "rlib"]
  • Add the following code to src/lib.rs
use wasm_bindgen::prelude::*;

// Function to be called from JavaScript, prints "Hello, world!" to the console
#[wasm_bindgen]
pub fn print_hello() {
web_sys::console::log_1(&"Hello, world!".into());
}
  • Build the project
wasm-pack build --target web
  • Create an index.html and include the generated JavaScript file, rust_wasm_helloworld.js
<!DOCTYPE html>
<html>
<head>
<title>Wasm Test</title>
<script type="module">
import init, { print_hello } from './pkg/rust_wasm_helloworld.js';

async function run() {
await init();
print_hello();
}

run();
</script>
</head>
<body>
<h1>Check the console for a message</h1>
</body>
</html>