% wasm-pack new hello_world
[INFO]: Installing cargo-generate...
Generating a new rustwasm project with name 'hello_world'...
Renaming project called `hello_world` to `hello-world`...
Creating project called `hello-world`...
Done! New project created /Users/chikoski/talks/20220216-wasm/samples/hello-world
[INFO]: Generated new project at /hello_world
% cd hello_world
% ls
Cargo.toml LICENSE_APACHE LICENSE_MIT README.md src tests
エキスポートする関数の定義
src/lib.rs に関数を定義する
wasm-bindgen プラグマをつける
pub キーワードをつける
#[wasm_bindgen]pubfnadd(a: u32, b: u32) -> u32 {
a + b
}
ビルドと npm パッケージの作成
wasm-pack build でビルド
ビルドアーティファクトは pkg フォルダに作成される
Wasm ファイル以外に js, d.ts, package.json も作成される
wasm-pack pack で npm パッケージを作成
% wasm-pack build -t web
% wasm-pack pack
% ls pkg/*.tgz
pkg/hello-world-0.1.0.tgz
#[wasm_bindgen]pubfngreet() -> Result<(), JsValue> {
let window = web_sys::window().ok_or("No Window object found")?;
let document = window.document().ok_or("No Document object found")?;
let body = document.body().ok_or("document.body does not exist")?;
let message = document.create_element("div")?;
message.set_text_content(Some("Hello, world!"));
body.append_child(&message)?;
Ok(())
}
DOM 操作は JS の方が簡潔に書ける
greet 関数を JS で書くと次のように簡潔に書ける
Wasm に DOM 操作をさせない方が良い?
JS と Wasm との役割分担は課題
変更可能性と(人員を含めた)メンテナンス性
コードサイズとロードパフォーマンス
val message = document.createElement("div");
div.text = "Hello, world!";
document.body.appendChild(message);