假定你已经安装好 Rust 了。
cargo install wasm-pack
。wasm-pack new hello-wasm
。
wasm-pack build
,WASM 会被生成至 pkg
文件夹中。
rustup target add wasm32-unknown-unknown
,尽管提示说的是会自动执行。wasm-pack publish
. You may need to login to the registry you want to publish to. You can login using wasm-pack login
.wasm-pack new hello-wasm
wasm-pack
,则可能是 wasm-pack.exe
被安装到了 {CargoHome}/bin/bin
,需要将其移动到 {CargoHome}/bin
中,我遇到了这个问题,估计这是一个小 bug。[INFO]: Installing cargo-generate...
Updating crates.io index
error: the `--vers` provided, `latest`, is not a valid semver version: cannot parse 'latest' as a semver
Error: Installing cargo-generate with cargo
Caused by: failed to execute `cargo install`: exited with exit code: 101
full command: "cargo" "install" "--force" "cargo-generate" "--version" "latest" "--root" "~/.wasm-pack/.cargo-generate-cargo-install-latest"
cargo new --lib hello-wasm
src/lib.rs
中导入 wasm_bindgen
:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern {
pub fn alert(s: &str);
}
#[wasm_bindgen]
pub fn greet(name: &str) {
alert(&format!("Hello, {}!", name));
}
Cargo.toml
:
[package]
name = "hello-wasm"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]
description = "A sample project with wasm-pack"
license = "MIT/Apache-2.0"
repository = "https://github.com/yourgithubusername/hello-wasm"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
wasm-pack build
。Cargo.toml
[profile.release]
lto = true
opt-level = 'z'
wasm-opt