A simple example demonstrating how to create a Rust library that can be used in JavaScript/TypeScript via WebAssembly (WASM), specifically designed for Deno.
This project showcases:
- Writing a Rust library with exported functions
- Compiling Rust to WebAssembly using
wasm-pack - Using the WASM module in Deno with TypeScript
.
├── Cargo.toml # Rust project configuration
├── src/
│ └── lib.rs # Rust source code with exported functions
├── pkg/ # Generated WASM package (after build)
│ ├── javascript_library_in_rust_example.js
│ ├── javascript_library_in_rust_example.d.ts
│ └── javascript_library_in_rust_example_bg.wasm
└── examples/
└── deno/
├── deno.json # Deno configuration
└── example.ts # Deno example using the WASM library
# Install Rust (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Install wasm-pack
cargo install wasm-pack
# Install Deno
curl -fsSL https://deno.land/x/install/install.sh | shBuild the Rust library to WebAssembly:
wasm-pack build --target denoThis will:
- Compile the Rust code to WebAssembly
- Generate JavaScript bindings
- Generate TypeScript definitions
- Place everything in the
pkg/directory
The library exports three simple functions:
hello(): Returns a "Hello, World!" messagegreet(name: string): Returns a personalized greetingadd(a: number, b: number): Adds two numbers together
After building the WASM library, run the example:
cd examples/deno
deno run --allow-read example.tsOr using the Deno task:
cd examples/deno
deno task dev=== Rust WASM Library Demo in Deno ===
1. Calling hello():
Hello, World from Rust WASM!
2. Calling greet('Deno'):
Hello, Deno! Welcome to Rust WASM in Deno!
3. Calling add(5, 7):
Result: 12
4. More examples:
greet('World') = Hello, World! Welcome to Rust WASM in Deno!
add(10, 20) = 30
add(-5, 5) = 0
✅ All examples completed successfully!
Test the Rust code:
cargo test- Edit
src/lib.rsto add or modify functions - Rebuild with
wasm-pack build --target deno - The changes will be available in the
pkg/directory
- Rust Code: Functions in
src/lib.rsare marked with#[wasm_bindgen]to export them to JavaScript - Compilation:
wasm-packcompiles Rust to WASM and generates JavaScript/TypeScript bindings - Import: Deno imports the generated JavaScript module which loads and interfaces with the WASM binary
- Execution: JavaScript/TypeScript code can call the exported Rust functions naturally
The generated package includes TypeScript definitions (.d.ts files), providing full type safety and IDE autocompletion when using the library in TypeScript.
This is an example project for educational purposes.