← Back to Lessons Lesson 9 of 28
Beginner getting-started
Setting Up Your First Project
Prerequisites
Before starting, install these tools:
# Install Rust (includes cargo)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Install wasm-pack
cargo install wasm-pack
# Verify
rustc --version
wasm-pack --versionCreate the Project
# Create a new library project
cargo new --lib my-wasm-app
cd my-wasm-appConfigure Cargo.toml
[package]
name = "my-wasm-app"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
# Add these as needed:
# web-sys = { version = "0.3", features = ["Window", "Document"] }
# js-sys = "0.3"
# wasm-bindgen-futures = "0.4"
[profile.release]
opt-level = "s" # Optimize for small binary size
lto = true # Link-time optimizationWrite Your First Function
Replace src/lib.rs with:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}Build
# Build for use with <script type="module">
wasm-pack build --target web
# Build for bundlers (Vite, Webpack)
wasm-pack build --target bundler
# Build with optimizations
wasm-pack build --target web --releaseThis creates a pkg/ directory with your .wasm binary, JavaScript glue code, and TypeScript types.
Use in HTML
<!DOCTYPE html>
<html>
<body>
<script type="module">
import init, { greet } from './pkg/my_wasm_app.js';
async function run() {
await init();
document.body.textContent = greet("World");
}
run();
</script>
</body>
</html>Use with Vite
npm create vite@latest my-app -- --template vanilla-ts
cd my-app
npm install// src/main.ts
import init, { greet } from '../my-wasm-app/pkg';
async function run() {
await init();
console.log(greet("Vite"));
}
run();Project Structure
my-wasm-app/
├── Cargo.toml # Rust dependencies
├── src/
│ └── lib.rs # Your Rust code
├── pkg/ # Generated by wasm-pack
│ ├── my_wasm_app_bg.wasm
│ ├── my_wasm_app.js
│ ├── my_wasm_app.d.ts
│ └── package.json
└── target/ # Rust build artifactsOptimizing Binary Size
# Cargo.toml
[profile.release]
opt-level = "s" # "s" = small, "z" = smallest
lto = true # Link-time optimization
codegen-units = 1 # Better optimization, slower compile
strip = true # Strip debug symbolsAlso run wasm-opt for further size reduction:
wasm-opt -Oz -o optimized.wasm pkg/my_wasm_app_bg.wasmTry It
Click Run to see the project setup checklist. Then try it on your own machine!
Try It
Chapter Quiz
Pass all questions to complete this lesson