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 | 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
name = "rust-wasm-helloworld"
version = "0.1.0"
edition = "2021"

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

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

// Function to be called from JavaScript, prints "Hello, world!" to the console
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>
<title>Wasm Test</title>
<script type="module">
import init, { print_hello } from './pkg/rust_wasm_helloworld.js';

async function run() {
await init();

<h1>Check the console for a message</h1>