rust wasm

384 阅读1分钟

安装

cargo install cargo-generate
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

开始

生成模板项目

cargo generate --git https://github.com/rustwasm/wasm-pack-template

目录含义

wasm-game-of-life/
├── Cargo.toml  # 项目依赖和元数据
├── LICENSE_APACHE 
├── LICENSE_MIT
├── README.md
└── src
    ├── lib.rs # 编译wasm的入口
    └── utils.rs

lib.rs

#![allow(unused_variables)]
fn main() {
    mod utils;

    use wasm_bindgen::prelude::*;

    // 开启wee_alloc后wee_alloc作为全局变量分配器
    #[cfg(feature = "wee_alloc")]
    #[global_allocator]
    static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

    // 它使用wasm-bindgen与JavaScript接口交互
    // alert JavaScript函数
    #[wasm_bindgen]
    extern {
        fn alert(s: &str);
    }

    // 导出Rust函数greet,它会发出问候消息。
    #[wasm_bindgen]
    pub fn greet() {
        alert("Hello, wasm-game-of-life!");
    }
}

编译

wasm-pack build

生成web项目

npm init wasm-app www
cd www
npm install
npm run start

引入

修改www/package.json,添加依赖

{
  "dependencies": {
    "wasm-game-of-life": "file:../pkg"
  }
}

修改www/index.js

import * as wasm from "wasm-game-of-life";
wasm.greet();

重新安装依赖,运行

npm install

参考链接

rustwasm game-of-life