cargo new --lib hello-wasm
- extern crate wasm_bindgen;
- use wasm_bindgen::prelude::*;
- #[wasm_bindgen]
- extern {
- //在 Rust 中调用来自 JavaScript 的外部函数
- pub fn alert(s: &str);
- }
- //提供外面调用方法
- #[wasm_bindgen]
- pub fn greet(name: &str) {
- alert(&format!("Hello, {}!", name));
- }
- 直接调用方式
- wasm-pack build --target web
- 打包并推送node仓库
- wasm-pack build --scope 仓库名称
- npm publish --access=public
- module.exports = {
- //...
- experiments: {
- asyncWebAssembly: true,
- },
- resolve: {
- extensions: ['.wasm'...]
- }
- //...
- }
- import init, { greet } from './is_button-wasm/is_button_wasm'
- export async function run_wasm(str) {
- await init()
- greet(str)
- }
1.推送npm仓库
编译 Rust 为 WebAssembly - WebAssembly | MDN
2.代码示例