• Github 中文镜像
Sign inSign up
Watch966
Star102.4k
Fork61.8k
Tag: todo
Switch branches/tags
Branches
Tags
  • master
K / 如何用 Rust 编写 WebAssembly.md
移动浏览 Clone
加载中...
到移动设备上浏览
102 lines 5.67 KB
First commit on 21 Jul 2020

尚未完成: Not completed尚未完成Not completed 随时检查: Check back later随时检查Check back later

    基本流程

    假定你已经安装好 Rust 了。

    1. 首先安装 wasm-pack cargo install wasm-pack
    2. 创建项目 wasm-pack new hello-wasm
      • 如果遇到报错,解决方案见下一节。
    3. 编写代码。
    4. 构建 wasm-pack build,WASM 会被生成至 pkg 文件夹中。
      • 这一步也可能需要手动执行 rustup target add wasm32-unknown-unknown,尽管提示说的是会自动执行。
    5. To publish to npm, run wasm-pack publish. You may need to login to the registry you want to publish to. You can login using wasm-pack login.

    第 2 步报错

    1. 错误一
      • 报错
        wasm-pack new hello-wasm
        
      • 解决 提示找不到 wasm-pack,则可能是 wasm-pack.exe 被安装到了 {CargoHome}/bin/bin,需要将其移动到 {CargoHome}/bin 中,我遇到了这个问题,估计这是一个小 bug。
    2. 错误二
      • 报错
        • 删掉了一些隐私数据,大致如下:
        [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"
        
      • 解决
        1. 通过新建库的方式新建项目也是可以的:
          cargo new --lib hello-wasm
          
        2. 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));
          }
          
        3. 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"
          
        4. 接“基本流程”第 4 步 wasm-pack build

    优化

    参考:optimizing .wsam size

    1. Cargo.toml
      [profile.release]
      lto = true
      opt-level = 'z'
      
    2. wasm-opt
      • 二进制包,提供更强力的压缩。
      • 这个包很大,下载 361M,解压 2.51G,要不要下载自己定。