1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-05-23 10:50:18 +02:00

load-wasm-module

This commit is contained in:
sakex 2023-07-21 14:32:36 +02:00
parent b989324e95
commit b0ce243f86
3 changed files with 35 additions and 33 deletions

View File

@ -300,6 +300,7 @@
# WebAssembly
----
- [WebAssembly basics](webassembly.md)
- [Load a WASM module](webassembly/load-wasm-module.md)
# Final Words

View File

@ -6,37 +6,6 @@ Rust is often considered as one of the best languages to compile to WebAssembly
# Setting up the environment
There are multiple frameworks to create WASM libraries from Rust. We will focus on [wasm-pack](https://rustwasm.github.io/docs/wasm-pack/introduction.html) and [wasm-bindgen](https://rustwasm.github.io/wasm-bindgen/).
WebAssembly needs to be run in a Browser or a VM, therefore we will use a different set up for this class. Please navigate to [rust-wasm-template](https://github.com/google/comprehensive-rust/tree/main/src/rust-wasm-template) to view the installation instructions. Feel free to either clone the repository to run it locally, or open a new [Codespace on Github](https://codespaces.new/google/comprehensive-rust)
## Install wasm-pack
Recommended:
```shell
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
```
Alternatively, see the [installation page](https://rustwasm.github.io/wasm-pack/installer/).
## Run the local server
WebAssembly cannot be loaded from the `files://` protocol yet, so we need to spawn a Web server to serve the different files.
```shell
cd server
cargo run
```
- On a devcontainer, go to `PORTS` and open the link under `Local Address` for Port `8080`
- Locally, visit http://localhost:8080
## Build WASM and copy target to the correct path
This command needs to be re-run to view your latest changes.
```shell
cd project
wasm-pack build --target web && cp -r pkg ../server
```

View File

@ -0,0 +1,32 @@
# Load a WASM module
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`
import init, {add} from '/wasm/project.js'; // A typescript version is also generated
// Async IIFE
(async () => {
// Run the init method to initiate the WebAssembly module.
await init();
console.log('WASM output', add(1, 2));
})();
```
Adding the Javascript module to an HTML file:
```html
<script type="module" src="/path/to/module.mjs"></script>
```
<details>
* This loads the compiled WebAssembly
* `init` installs the bytecode and compiles it
* `add` is an exported method
* For this class, we are compiling `wasm-pack` with the `--web` flag, complex applications will want to use a bundler,
see more information about build options on the [official documentation](https://rustwasm.github.io/docs/wasm-pack/commands/build.html)
</details>