WebAssembly是什么?
通俗讲WebAssembly是一种在web浏览器中运行的新型代码,可以编译C/C++、C#和Rust等语言以便它们可以在web上运行。WebAssembly具备更高的运行速度,并且可以与js一起运行、互相调用。
手把手起步
前置条件
1.Git
2.CMake。在 Linux 和 OS X系统中,你可以使用包管理工具 apt-get 或 brew 来安装。如果是 Windows 系统,你可以点击这里。
从Rust编译到WebAssembly
此处我以rust为例,在座的大哥有其他熟练的编程语言技能也是可以选择,参考文档点击这里,当然作为像我一样的前端开发其实都不熟悉。
安装rust
安装地址点击这里,看不懂英文?没事,好心的rust官网最下方有语言选择下拉框。如果默认安装则不需要配置环境变量,否则需手动配置。安装成功后可使用 rustc --version 来检测是否安装成功。
wasm-pack
在终端执行以下命令,下载并安装wasm-pack,用于编译构建可执行在web端的工具。
cargo install wasm-pack
创建项目
在任意目录终端(比如桌面)执行以下命令,创建一个hello-wasm的项目
cargo new --lib hello-wasm
此时可见项目目录如下,其中Cargo.toml为配置文件,lib.rs为编译入口文件
+-- Cargo.toml
+-- src
+-- lib.rs
将以下代码复制并覆盖lib.rs文件中的原有代码。如果你稍微了解前端代码,那大概率可以盲猜以下代码的执行结果是弹窗Hello, xxx!
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"
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
打包并引用
执行以下命令,打包lib.rs代码。第一次执行可能会非常慢。
wasm-pack build --target web
新建index.html,并引入打包后的文件。
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>hello-wasm example</title>
</head>
<body>
<script type="module">
import init, { greet } from "./pkg/hello_wasm.js";
init().then(() => {
greet("WebAssembly");
});
</script>
</body>
</html>
可利用python、node等创建并启动本地服务,然后打开index.html。即可见证Hello, WebAssembly!
打包至本地npm,此处不做阐述,如有兴趣可参考这里