哈囉,世界!

檢視完整原始碼在線上檢視已編譯的範例

這是 `#[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"
  }
}