rustwasm / wasm-bindgen

Facilitating high-level interactions between Wasm modules and JavaScript
https://rustwasm.github.io/docs/wasm-bindgen/
Apache License 2.0
7.84k stars 1.08k forks source link

Method of struct missing with js_name #4154

Open b-zee opened 1 month ago

b-zee commented 1 month ago

Describe the Bug

When using the js_name on an enum, a method does not get exported.

Steps to Reproduce

Consider this snippet:

#[wasm_bindgen(js_name = Data)]
pub struct JsData(u8);

#[wasm_bindgen]
impl JsData {
    #[wasm_bindgen(js_name = toString)]
    pub fn to_string(&self) -> String {
        self.0.to_string()
    }
}

Compiled with wasm-pack build --dev --target=web.

Expected Behavior

The Data class to include the toString method.

// In the `.d.ts` file
export class Data {
  free(): void;
/**
* @returns {string}
*/
  toString(): string;
}

Actual Behavior

// In the `.d.ts` file
export class Data {
  free(): void;
}

Additional Context

When the js_name attribute is not used, e.g.:

-#[wasm_bindgen(js_name = Data)]
+#[wasm_bindgen()]
pub struct JsData(u8);

The .d.ts file will include the method:

export class JsData {
  free(): void;
/**
* @returns {string}
*/
  toString(): string;
}
RunDevelopment commented 1 month ago

I think you can use js_class to fix this.

That said, wasm bindgen should still be better here IMO.

b-zee commented 1 month ago

I tried adding it both to the method and struct:

warning: unused variable: `js_class`

But I forgot trying to add it to the impl, that works!

So, in short, this works:


#[wasm_bindgen(js_name = Data)]
pub struct JsData(u8);

#[wasm_bindgen(js_class = Data)]
impl JsData {
    #[wasm_bindgen(js_name = toString)]
    pub fn to_string(&self) -> String {
        self.0.to_string()
    }
}