diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 75e3e96e..2c578e9a 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -301,6 +301,7 @@ ---- - [WebAssembly basics](webassembly.md) - [Load a WASM module](webassembly/load-wasm-module.md) + - [Expose a method](webassembly/expose-method.md) # Final Words diff --git a/src/rust-wasm-template/server/files/index.html b/src/rust-wasm-template/server/files/index.html index f9e9f161..1876111d 100644 --- a/src/rust-wasm-template/server/files/index.html +++ b/src/rust-wasm-template/server/files/index.html @@ -87,7 +87,7 @@ This repository contains the minimum amount of code needed to experiment with WebAssembly. Including a web server to serve the HTML and WASM as well as the javascript boilerplate needed to load WASM.
- Edit server/files/index.mjs to edit the Javascript. + Edit server/files/index.mjs to edit the Javascript.
WASM output: diff --git a/src/webassembly/expose-method.md b/src/webassembly/expose-method.md new file mode 100644 index 00000000..5bd354dc --- /dev/null +++ b/src/webassembly/expose-method.md @@ -0,0 +1,23 @@ +# Expose a method + +The first thing you will want to do with WebAssembly is expose your methods to Javascript. +This is straightforward using the `#[wasm_bindgen]` procedural macro. + +```rust +use wasm_bindgen::prelude::*; + +#[wasm_bindgen] +pub fn set_panic_hook() { + // Generates better error messages if our code ever panics. + // + // For more details see + // https://github.com/rustwasm/console_error_panic_hook#readme + console_error_panic_hook::set_once(); +} + +// Exposes the `add` method from the previous slide +#[wasm_bindgen] +pub fn add(a: i32, b: i32) -> i32 { + a + b +} +``` diff --git a/src/webassembly/load-wasm-module.md b/src/webassembly/load-wasm-module.md index 63bdb2fd..ac2e2502 100644 --- a/src/webassembly/load-wasm-module.md +++ b/src/webassembly/load-wasm-module.md @@ -1,7 +1,29 @@ # Load a WASM module +## Commands to run: + +You can compile the basic WASM library provided in [rust-wasm-template](https://github.com/google/comprehensive-rust/tree/main/src/rust-wasm-template) with this command: + +```shell +cd src/rust-wasm-template/project + +wasm-pack build --target web && cp -r pkg ../server +``` + +You can start the web server provided in [rust-wasm-template](https://github.com/google/comprehensive-rust/tree/main/src/rust-wasm-template) with this command: + + +```shell +cd src/rust-wasm-template/server + +cargo run +``` + +Open the web page on port `8080`. HTML and JS files are provided at [rust-wasm-template/server](https://github.com/google/comprehensive-rust/tree/main/src/rust-wasm-template/server/files). + +## Javascript + Once you have compiled your WebAssembly module, you want to call it from your Web application. -This chapter will cover minimum amount of Javascript required to load a WASM module into a Web application. ```javascript // Import the module and the exported method `add`