wasm创建和基础使用rust

访问 Rust 官网:https://www.rust-lang.org/tools/install
  1. 下载 rustup-init:
  • Windows: 下载 rustup-init.exe
  • macOS/Linux: 运行 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  1. 运行安装程序:
  • Windows: 双击运行 rustup-init.exe
  • 按照提示完成安装
1. 安装 wasm-pack
cargo install wasm-pack
创建 WASM 项目
wasm-pack new my-wasm-project
方法二:在现有 Rust 项目中添加 WASM 支持
# 进入现有项目目录
cd my-rust-project
# 初始化 WASM 支持
wasm-pack init
3. 项目结构
WASM 项目会包含以下文件:
my-wasm-project/
├── Cargo.toml          # Rust 项目配置
├── src/
│   └── lib.rs          # WASM 模块代码
├── tests/
│   └── web.rs          # 浏览器测试
├── www/                # 前端文件(可选)
│   ├── index.html
│   ├── index.js
│   └── style.css
└── pkg/                # 构建输出目录(自动生成)
4. 配置 Cargo.toml
确保 Cargo.toml 包含必要的配置:
[package]
name = "my-wasm-project"
version = "0.1.0"
edition = "2021"

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

[dependencies]
wasm-bindgen = "0.2"

[dev-dependencies]
wasm-bindgen-test = "0.3"

[dependencies]
cargo.toml文件内容
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = [
    "Window",
    "Document",
    "Element",
    "HtmlCanvasElement",
    "WebGlRenderingContext",
    "WebGl2RenderingContext",
    "WebGlProgram",
    "WebGlShader",
    "WebGlBuffer",
    "WebGlUniformLocation",
    "Performance",
    "PerformanceTiming",
    "console"
]}
js-sys = "0.3"
5. 编写 WASM 代码
在 src/lib.rs 中编写你的 WASM 代码:
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
6. 构建 WASM
# 或者指定目标
wasm-pack build --target web      # 用于 web
wasm-pack build --target nodejs   # 用于 Node.js
wasm-pack build --target bundler  # 用于打包工具(webpack, rollup 等)
7. 在浏览器中使用
创建 www/index.html:
<script type="module">
    import init, { greet, add } from './pkg/my_wasm_project.js';

    async function run() {
        await init();
       
        document.getElementById('greet').addEventListener('click', () => {
            const result = greet('World');
            document.getElementById('output').textContent = result;
        });
    }

    run();
</script>
8. 运行开发服务器
# 启动开发服务器
wasm-pack build --target web
python -m http.server 8000  #
9. 测试 WASM
wasm-pack test --headless --firefox
wasm-pack test --headless --chrome
//常用命令总结
wasm-pack new project_name - 创建新 WASM 项目
wasm-pack build - 构建 WASM 模块
wasm-pack test - 运行测试
wasm-pack publish - 发布到 npm
wasm-pack build --target web - 构建用于 web 的版本
10. 发布到 npm(可选)
# 发布到 npm
wasm-pack publish
posted @ 2025-08-01 17:35  青苔下的  阅读(77)  评论(0)    收藏  举报