你好,世界!
这是 `#[wasm_bindgen]` 的“你好,世界!”示例,展示了如何设置项目、将函数导出到 JS、从 JS 调用它,然后在 Rust 中调用 `alert` 函数。
Cargo.toml
`Cargo.toml` 将 `wasm-bindgen` crate 列为依赖项。
另外值得注意的是 `crate-type = ["cdylib"]`,它主要用于今天的 wasm 最终工件。
[package]
authors = ["The wasm-bindgen Developers"]
edition = "2021"
name = "hello_world"
publish = false
version = "0.0.0"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = { path = "../../" }
[lints]
workspace = true
src/lib.rs
这里我们定义了 Rust 入口点以及调用 `alert` 函数。
# #![allow(unused_variables)] #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, ".")
}),
],
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.6.0",
"webpack": "^5.97.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
}
}