js_name = Blah

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

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


# #![allow(unused_variables)]
#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_variables)]
#fn main() {
#[wasm_bindgen(js_name = Foo)]
pub struct JsFoo {
    // ..
}
#}

以便像這樣存取

import { Foo } from './my_module';

// ...

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


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

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

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


# #![allow(unused_variables)]
#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) {
        // ...
    }
}