你好,世界!
这是 #[wasm_bindgen]
的“你好,世界!”示例,展示了如何设置项目、将函数导出到 JS、从 JS 调用它,然后在 Rust 中调用 alert
函数。
Cargo.toml
Cargo.toml
将 wasm-bindgen
crate 列为依赖项。
值得注意的是 crate-type = ["cdylib"]
,它在当今的 wasm 最终制品中被广泛使用。
[package]
name = "hello_world"
version = "0.1.0"
authors = ["The wasm-bindgen Developers"]
edition = "2018"
rust-version = "1.57"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.92"
src/lib.rs
这里我们定义了 Rust 的入口点,并调用了 alert
函数。
#![allow(unused)] fn main() { use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn alert(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("Hello, {}!", name)); } }
index.js
我们的 JS 入口点非常小!
import { greet } from './pkg';
greet('World');
Webpack 特定文件
注意:此示例需要 Webpack,如果您对不使用 JS 打包工具的选项感兴趣,请查看其他示例。
最后,这是此项目的 Webpack 配置和 package.json
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, ".")
}),
// 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',
experiments: {
asyncWebAssembly: true
}
};
package.json
{
"scripts": {
"build": "webpack",
"serve": "webpack serve"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "1.5.0",
"html-webpack-plugin": "^5.3.2",
"text-encoding": "^0.7.0",
"webpack": "^5.49.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^4.15.1"
}
}