WebAssembly工程化指南-Rust篇

前面我们介绍了用C++如何构建wasm供前段使用,这里我们再来拓展最流行的rust语言。

Install Rust

curl https://sh.rustup.rs -sSf | sh

Install wasm_bindgen

cargo install wasm_bindgen

新建wasm项目

cargo new --lib hello-wasm
├── Cargo.lock
├── Cargo.toml
├── src
|  └── lib.rs
├── target
|  └── rls
|     └── debug
└── web
   ├── index.html
   └── index.js

directory: 5 file: 5

web以及下面的文件是手动创建的:

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>WASM Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <h1>WASM Demo</h1>
    <script src="./index.js"></script>
  </body>
</html>

index.js

let squarer;

function loadWebAssembly(fileName) {
  return fetch(fileName)
    .then((response) => response.arrayBuffer())
    .then((buffer) => WebAssembly.compile(buffer))
    .then((module) => {
      return new WebAssembly.Instance(module);
    });
}

loadWebAssembly("../pkg/hello_wasm_bg.wasm").then((instance) => {
  squarer = instance.exports.fib(12);
  console.log("Finished compiling! Ready when you are...", squarer);
});

编码和配置

lib.rs

extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn fib(i: u32) -> u32 {
    match i {
        0 => 0,
        1 => 1,
        _ => fib(i-1) + fib(i-2)
    }
}

Cargo.toml

[package]
name = "hello-wasm"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
wasm-bindgen = "0.2"

构建

wasm-pack build

会生成pkg目录,wasm就在这里:

├── hello_wasm.d.ts
├── hello_wasm.js
├── hello_wasm_bg.d.ts
├── hello_wasm_bg.js
├── hello_wasm_bg.wasm
└── package.json

测试

http-server

// open http://localhost:8080