RustでWebassembly作成、DOM操作の例 #Rust #Webassembly #javascript
■ 概要:
Rust / Webassembly (下記 WASM)を呼び、
DOMを操作するサンプルとなります
■ 関連
https://rustwasm.github.io/wasm-bindgen/examples/dom.html
■ 環境
Rust
rustc 1.46.0
cargo 1.46.0
wasm-pack
■ dom追加
・上記ページのままですが、
・Cargo.toml , web-sys 等追加
[package]
name = "dom"
version = "0.1.0"
authors = ["The wasm-bindgen Developers"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.67"
[dependencies.web-sys]
version = "0.3.4"
features = [
'Document',
'Element',
'HtmlElement',
'Node',
'Window',
]
・Rust , WASM
p要素が、追加される例らしいです。
use wasm_bindgen::prelude::*;
// Called by our JS entry point to run the example
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
// Use `web_sys`'s global `window` function to get a handle on the global
// window object.
let window = web_sys::window().expect("no global `window` exists");
let document = window.document().expect("should have a document on window");
let body = document.body().expect("document should have a body");
// Manufacture the element we're gonna append
let val = document.create_element("p")?;
val.set_inner_html("Hello from Rust!");
body.append_child(&val)?;
Ok(())
}
・jsから、呼び出し
<script src='/pkg/wasm_react_cms.js'></script>
<script>
const { run } = wasm_bindgen;
//
async function wasm_react_cms_run() {
await wasm_bindgen('/pkg/wasm_react_cms_bg.wasm');
}
wasm_react_cms_run();
</script>
■ build
buildは、
wasm-pack build --target no-modules
で、可能でしたが。
webpackは、wasm-pack build
でも可能と思います。
■ 前の関連ページ
https://note.com/knaka0209/n/n0da6740b3c7c