js_name = Blah

js_name 屬性可以用來在 JS 中導出與 Rust 中不同的名稱。它可以應用於導出的 Rust 函數和類型。

例如,這通常用於將 Rust 的蛇式命名法識別符號轉換為 JavaScript 的駝峰式命名法識別符號

#![allow(unused)]
fn main() {
#[wasm_bindgen(js_name = doTheThing)]
pub fn do_the_thing() -> u32 {
    42
}
}

這可以在 JavaScript 中使用為

import { doTheThing } from './my_module';

const x = doTheThing();
console.log(x);

與導入類似,js_name 也可以用來重新命名導出到 JS 的類型

#![allow(unused)]
fn main() {
#[wasm_bindgen(js_name = Foo)]
pub struct JsFoo {
    // ..
}
}

以便像這樣訪問

import { Foo } from './my_module';

// ...

請注意,將方法附加到 JS 類別 Foo 應該透過 js_class 屬性 完成

#![allow(unused)]
fn main() {
#[wasm_bindgen(js_name = Foo)]
pub struct JsFoo { /* ... */ }

#[wasm_bindgen(js_class = Foo)]
impl JsFoo {
    // ...
}
}

它也可以用來重新命名導出函數和方法的參數

#![allow(unused)]
fn main() {
#[wasm_bindgen]
pub fn foo(
    #[wasm_bindgen(js_name = "firstArg")]
    arg1: String,
) {
    // function body
}

#[wasm_bindgen]
pub struct Foo {
    // properties
}

#[wasm_bindgen]
impl Foo {
    pub fn foo(
        &self,
        #[wasm_bindgen(js_name = "firstArg")]
        arg1: u32,
    ) {
        // function body
    }
}
}

這將會產生以下 JS 綁定

/**
 * @param {string} firstArg
 */
export function foo(firstArg) {
    // ...
}

export class Foo {
    /**
     * @param {number} firstArg
     */
    foo(firstArg) {
        // ...
    }
}