WebAssembly 与 Rust 编程系列06 Rust模块与JavaScript交互

WebAssembly 与 Rust 编程系列06 Rust模块与JavaScript交互

About: 简介

上一篇文章: WebAssembly 与 Rust 编程系列05 Rust编写wasm模块
我们介绍了最简单的 Rust 导出wasm模块,并在js中加载调用

接下来我们会在此基础上, 更加深入的了解 Rust 与 JavaScript 的交互, 以及 Rust 和 WebAssembly 相关生态工具的应用

wasm-bindgen 使用

wasm-bindgen的核心是提供javascript和Rust之间相互使用wasm进行通信。
它允许开发者直接使用Rust的结构体、javascript的类、字符串等类型,而不仅仅是wasm支持的整数或浮点数;

wasm-bindgen
wasm-bindgen-doc

wasm-bindgen 是一个 cargo 包,只需要在依赖中加入即可

wasm-bindgen = "0.2.64"

wasm-pack 使用

wasm-pack 可以把我们的代码编译成 WebAssembly 并制造出正确的 npm 包。

cargo install wasm-pack

创建工程

  • 创建 bindgen 工程
cargo new bindgen-hello --lib
  • 修改 Cargo.toml
[package]
name = "bindgen-hello"
version = "0.1.0"
authors = ["austindev "]
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"
  • 修改 lib.rs
    实现一个最简单的 rust调用JavaScript的alert
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));
}
  • 编译 wasm
cargo build --release --target wasm32-unknown-unknown

webpack 与 npm 集成使用

上述cargo编译出模块后,因为集成了wasm-bingen,不能直接使用

  • 生成 npm 模块
    需要进一步处理
wasm-bindgen target/wasm32-unknown-unknown/release/bindgen_hello.wasm --out-dir ./lib
  • 修改 .gitignore
    我们编译生成的模块文件是不需要加入版本管理的,记得加入 gitignore
/target
Cargo.lock
/lib
node_modules/
  • 新建 package.json

定义一个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"
  }
}
  • 新建 webpack.config.js
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三者之间
如何协作的精髓.

你可能感兴趣的:(webdesign)