ViteJS配合Rust快速搭建WebAssembly开发环境

292 阅读2分钟

安装Rust

Rust官网下载相关的安装程序即可安装, 下载 ,安装后可使用rustup --version查看版本。

常见命令

  1. rustc 编译命令
  2. cargo rust商店库,类似于JS的NPM
  3. rustup工具命令,一般用于设置编译目标环境,如rustup target list,rustup target add myName

添加对WebAssembly的编译支持

  1. 使用rustup target list查看当前可编译的目标平台列表。
  2. 使用rustup target add wasm32-unknown-unknown添加对wasm平台的编译支持。

安装配套脚手架

一般使用RUST开发库文件,并不是完整的项目。 这里有两个官网提供的脚手架和模板。

wasm-pack

用于构建,测试,发布到npm等一站式工具库

安装

cargo install wasm-pack

cargo-generate

模板,用于快速建立项目。

安装

cargo install cargo-generate

创建项目

 cargo generate --git https://github.com/damiduo/wasm-vite-template.git --name hello-vite-wasm

--name 是要创建的项目名称与文件夹名称

执行后会创建一个Rust示例项目。

也可以不使用脚手架创建,如:`cargo new --lib rust-wasm-adder`

其他模板地址:cargo generate --git <github.com/rustwasm/wa…> --name hello-rust-wasm

初始化项目

进入已创建目录,执行属性的npm命令

npm install

编译项目

wasm-pack build

执行编译命令后,可以项目pkg找到输出的内容,其实会产生两个文件夹,一个是target,一个是pkg。 关羽target我们使用的WAMS,暂时不需要关心。

编译后PKG

pkg/
├── package.json
├── README.md
├── .gitignore
├── hello_rust_wasm_bg.js // 定义引入WASM模块的JS文件
├── hello_rust_wasm_bg.wasm // 定义RUST与WASM的二进制模块
├── hello_rust_wasm_bg.wasm.d.ts // 可使用的定义接口
├── hello_rust_wasm.d.ts // 对外可使用的接口
└── hello_rust_wasm.js // 索引文件,引入了hello_rust_wasm_bg.js与hello_rust_wasm_bg.wasm

也可以不适用wasm-pack编译,直接使用cargo build --release --target wasm32-unknown-unknown

运行项目

每次.rs的文件变更都需要执行wasm-pack build进行编译。 想看在Web中的效果,可以运行

npm run dev