一、开发环境搭建
1. 基础工具安装
# 安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 安装 wasm-pack
cargo install wasm-pack
# 安装开发服务器
cargo install basic-http-server
# 安装文件监听工具
cargo install cargo-watch
2. VSCode 插件安装
- rust-analyzer: Rust 语言支持
- CodeLLDB: 调试支持
- WebAssembly: WASM 代码高亮
二、项目设置
1. 项目初始化
cd /Users/xubai/workspace/xubai/rust-demo
cargo new --lib wasm-demo
cd wasm-demo
2. 配置 Cargo.toml
[package]
name = "wasm-demo"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["console"] }
console_error_panic_hook = "0.1"
3. 配置开发环境
创建 .gitignore
文件:
/target
/pkg
Cargo.lock
三、开发工作流配置
1. 自动构建设置
打开一个终端,运行以下命令来启动自动构建:
cargo watch -i .gitignore -i "pkg/*" -s "wasm-pack build --target web --dev"
2. 开发服务器
在另一个终端窗口运行:
basic-http-server .
现在,当你修改任何源代码文件时,项目会自动重新构建,并且可以通过 http://localhost:4000
访问。
四、基础示例实现
1. 简单计数器
use wasm_bindgen::prelude::*;
use web_sys::console;
#[wasm_bindgen]
pub struct Counter {
count: i32,
}
#[wasm_bindgen]
impl Counter {
pub fn new() -> Counter {
Counter { count: 0 }
}
pub fn increment(&mut self) -> i32 {
self.count += 1;
self.count
}
}
2. 前端集成
创建 www/index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WASM Demo</title>
</head>
<body>
<h1>WASM 计数器示例</h1>
<button id="increment">增加</button>
<p>当前计数:<span id="count">0</span></p>
<script type="module" src="./index.js"></script>
</body>
</html>
创建 www/index.js
:
import init, { Counter } from '../pkg/wasm_demo.js';
async function main() {
await init();
const counter = Counter.new();
const button = document.getElementById('increment');
const countDisplay = document.getElementById('count');
button.onclick = () => {
const count = counter.increment();
countDisplay.textContent = count;
};
}
main().catch(console.error);
五、调试技巧
1. Rust 代码调试
// 在 Rust 代码中打印日志
console::log_1(&JsValue::from_str("调试信息"));
// 使用 console_error_panic_hook
#[wasm_bindgen(start)]
pub fn main() -> Result<(), JsValue> {
console_error_panic_hook::set_once();
Ok(())
}
2. Chrome DevTools 调试
- 打开 DevTools(Command + Option + I)
- 在 Sources 面板中找到生成的 .wasm 文件
- 使用 Console 面板查看日志输出
- 在 JavaScript 代码中设置断点
3. 实时开发体验
- 修改 Rust 代码会自动触发重新构建
- 刷新浏览器即可看到最新变化
- 控制台会显示构建状态和错误信息
六、常见问题解决
1. 构建失败
- 检查 Cargo.toml 依赖是否正确
- 确保 wasm-pack 版本最新
- 查看 Rust 编译错误信息
2. 加载失败
// 添加错误处理
init().catch(err => {
console.error("WASM 加载失败:", err);
// 显示用户友好的错误信息
document.body.innerHTML = `
<div style="color: red;">
加载失败,请刷新页面重试
</div>
`;
});
3. 开发服务器问题
- 确保端口 4000 未被占用
- 检查文件权限
- 验证构建输出目录 (pkg) 是否存在
七、开发建议
-
工作流程
- 保持两个终端窗口:一个运行 watch,一个运行服务器
- 使用 VSCode 的集成终端可以方便地管理多个窗口
- 定期清理 pkg 目录避免缓存问题
-
调试效率
- 善用 console.log
- 保持 DevTools 网络面板打开以监控资源加载
- 使用 Chrome 的 Performance 面板分析性能问题
-
最佳实践
- 模块化组织代码
- 添加适当的错误处理
- 保持构建脚本的清晰和可维护性