Appearance
Rust编译为wasm教程
详细教程参考WebAssembly
Rust 和 WebAssembly 用例
Rust 和 WebAssembly 有两大主要用例:
- 构建完整应用——整个 Web 应用都基于 Rust 开发!
- 构建应用的组成部分——在现存的 JavaScript 前端中使用 Rust。
我们将使用 Rust 的 npm 包构建工具 wasm-pack 来构建一个 npm 包。这个包只包含 WebAssembly 和 JavaScript 代码,以便包的用户无需安装 Rust 就能使用。他们甚至不需要知道这里包含 WebAssembly!
安装Rust环境
安装Rust
前往Rust官网下载安装Rust
安装wasm-pack
bash
cargo install wasm-pack生成WebAssembly模块包
新建项目目录,生成Rust程序包
bash
cargo new --lib hello-wasm这里会在名为 hello-wasm 的子目录里创建一个新的库,里面有下一步之前你所需要的一切:
text
+-- Cargo.toml
+-- src
+-- lib.rs将src/lib.rs下的代码替换为
rust
extern crate 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));
}修改toml配置文件
toml
[package]
name = "hello-wasm"
version = "0.1.0"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"构建包
bash
wasm-pack build构建完成后就会生成pkg文件夹,这是一个nodejs模块包,可以直接作为模块依赖使用
在web中使用
我们在hello-wasm项目下新建html文件 写入脚本
javascript
<script type="module">
const js = import("./pkg/hello_wasm.js");
js.then((js) => {
js.greet("WebAssembly");
});
</script>注意:wasm不能在本地环境直接运行,需要启动本地服务 然后你会发现浏览器报错(Failed to load module script: The server responded with a non-JavaScript MIME type of "application/wasm". Strict MIME type checking is enforced for module scripts per HTML spec.),没错,因为wasm-pack build构建的为nodejs环境使用的模块包,并不能直接在web上使用,需要在web端直接使用要加上参数 使用命令编译target到web
bash
wasm-pack build --release --target web然后修改html脚本
javascript
<script type="module">
import init , { greet } from '/pkg/hello_wasm.js';
init().then(() => {
greet("WebAssembly");
});
</script>然后你就会发现,很神奇,程序成功运行
