上一篇文章: WebAssembly 与 Rust 编程系列05 Rust编写wasm模块
我们介绍了最简单的 Rust 导出wasm模块,并在js中加载调用
接下来我们会在此基础上, 更加深入的了解 Rust 与 JavaScript 的交互, 以及 Rust 和 WebAssembly 相关生态工具的应用
wasm-bindgen的核心是提供javascript和Rust之间相互使用wasm进行通信。
它允许开发者直接使用Rust的结构体、javascript的类、字符串等类型,而不仅仅是wasm支持的整数或浮点数;
wasm-bindgen
是一个 cargo 包,只需要在依赖中加入即可
wasm-bindgen = "0.2.64"
wasm-pack
可以把我们的代码编译成 WebAssembly 并制造出正确的 npm 包。
cargo install wasm-pack
cargo new bindgen-hello --lib
[package]
name = "bindgen-hello"
version = "0.1.0"
authors = ["austindev <austinxishou@yahoo.com>"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
wasm-bindgen = "0.2.64"
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern {
pub fn alert(s: &str);
}
#[wasm_bindgen]
pub fn hello(name: &str) {
alert(&format!("Hello, {}!", name));
}
cargo build --release --target wasm32-unknown-unknown
上述cargo编译出模块后,因为集成了wasm-bingen,不能直接使用
wasm-bindgen target/wasm32-unknown-unknown/release/bindgen_hello.wasm --out-dir ./lib
/target
Cargo.lock
/lib
node_modules/
定义一个package.json文件
{
"scripts": {
"build": "webpack",
"serve": "webpack-dev-server"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "1.0.1",
"text-encoding": "^0.7.0",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.29.4",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.0"
}
}
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
plugins: [
new HtmlWebpackPlugin(),
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, "./lib")
}),
// Have this example work in Edge which doesn't ship `TextEncoder` or
// `TextDecoder` at this time.
new webpack.ProvidePlugin({
TextDecoder: ['text-encoding', 'TextDecoder'],
TextEncoder: ['text-encoding', 'TextEncoder']
})
],
mode: 'development'
};
npm install
npm run serve
本篇实现了最简单的 Rust 写 npm模块,并且在模块中与JavaScript代码交互,基本上展现了rust与wasm以及JavaScript三者之间
如何协作的精髓.