一、什么是 WebAssembly?

WebAssembly(Wasm) 是一种适用于堆栈虚拟机的二进制指令格式,设计目标是在 Web 平台上高效、安全地运行编译后的代码。它支持多种高级语言(如 C、C++、Rust)作为编译目标,既可用于前端 Web,也可在服务器端运行。

WebAssembly 的优势

  • 高性能:接近原生的运行速度,适合计算密集型任务。
  • 可移植:Wasm 的二进制格式可在不同平台运行,具有良好的跨平台特性。
  • 安全性:在沙盒环境中运行,限制了对系统资源的访问。
  • 良好的互操作性:可与 JavaScript 紧密集成,互相调用函数。

二、为什么选择 Rust 编写 WebAssembly?

Rust 是一门系统级语言,兼顾了性能和内存安全。其良好的工具链和官方对 WebAssembly 的支持,使其成为开发 Wasm 模块的首选语言。


三、开发准备

安装必要工具

# 安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 安装 wasm-pack:用于将 Rust 编译为 WebAssembly 模块并生成 JS 包装
cargo install wasm-pack

四、创建 Rust WebAssembly 项目

1. 初始化项目

cargo new hello-wasm --lib
cd hello-wasm

2. 添加依赖

编辑 Cargo.toml 文件:

[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["console"] }

3. 编写核心逻辑

编辑 src/lib.rs

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);

    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}

#[wasm_bindgen]
pub fn hello(value: &str) {
    alert(&format!("Hello, {}!", value));
    log("这是通过 log 打印的信息");
}

五、构建 WebAssembly 模块

使用 wasm-pack 进行构建:

wasm-pack build --target web --scope dwyl

构建成功后会生成 pkg/ 目录,包含 .wasm 文件及 JavaScript 包装代码。


六、本地测试 HTML 页面

创建一个 index.html 文件用于快速测试:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>Hello WebAssembly</title>
  <script type="module">
    import init, { hello } from './pkg/hello_wasm.js';

    async function run() {
      await init();
      hello("世界");
    }

    run();
  </script>
</head>
<body>
  <h1>WebAssembly 调用测试</h1>
</body>
</html>

启动本地服务器:

python -m http.server 8000

打开浏览器访问 http://localhost:8000


七、集成到 Vite + Vue 项目

1. 创建 Vite 项目

npm create vite@latest hello-wasm-app -- --template vue
cd hello-wasm-app

2. 安装依赖

pnpm add vue
pnpm add -D vite-plugin-wasm-esm vite-plugin-top-level-await

3. 配置 Vite

编辑 vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import wasm from 'vite-plugin-wasm-esm'
import topLevelAwait from 'vite-plugin-top-level-await'

export default defineConfig({
  plugins: [
    vue(),
    wasm(['@dwyl/hello-wasm']),
    topLevelAwait()
  ],
  server: {
    port: 5155
  }
})

4. 添加依赖包路径

package.json 中添加本地依赖:

"dependencies": {
  "@dwyl/hello-wasm": "file:../hello-wasm/pkg"
}

然后执行:

pnpm install

八、Vue 中调用 WebAssembly 模块

在任意组件中调用,例如:

<template>
  <el-button @click="sayHello">点我</el-button>
</template>

<script setup lang="ts">
import { hello } from '@dwyl/hello-wasm';

const sayHello = () => {
  hello('你好');
}
</script>

使用了 vite-plugin-wasm-esm 插件后,不需要 init(),可直接调用 Wasm 暴露的方法。


九、发布到 NPM

确保你已登录 NPM 并设置好 Cargo.toml 中的元信息(如包名、作者、描述等):

wasm-pack publish
[package]
name = "new-wasm"
version = "0.1.0"
authors = ["岩冰 <1493001032@qq.com>"]
edition = "2018"
description = "一个用 Rust 编写并编译为 WebAssembly 的测试库"
license = "MIT OR Apache-2.0"
repository = "https://github.com/yourusername/new-wasm"
readme = "README.md" 

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐