You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* Add support for #[wasm_bindgen(inspectable)]
This annotation generates a `toJSON` and `toString` implementation for
generated JavaScript classes which display all readable properties
available via the class or its getters
This is useful because wasm-bindgen classes currently serialize to
display one value named `ptr`, which does not model the properties of
the struct in Rust
This annotation addresses #1857
* Support console.log for inspectable attr in Nodejs
`#[wasm_bindgen(inspectable)]` now generates an implementation of
`[util.inspect.custom]` for the Node.js target only. This implementation
causes `console.log` and friends to yield the same class-style output,
but with all readable fields of the Rust struct displayed
* Reduce duplication in generated methods
Generated `toString` and `[util.inspect.custom]` methods now call
`toJSON` to reduce duplication
* Store module name in variable
By default, structs exported from Rust become JavaScript classes with a single `ptr` property. All other properties are implemented as getters, which are not displayed when calling `toJSON`.
4
+
5
+
The `inspectable` attribute can be used on Rust structs to provide a `toJSON` and `toString` implementation that display all readable fields. For example:
6
+
7
+
```rust
8
+
#[wasm_bindgen(inspectable)]
9
+
pubstructBaz {
10
+
pubfield:i32,
11
+
private:i32,
12
+
}
13
+
14
+
#[wasm_bindgen]
15
+
implBaz {
16
+
#[wasm_bindgen(constructor)]
17
+
pubfnnew(field:i32) ->Baz {
18
+
Baz { field, private:13 }
19
+
}
20
+
}
21
+
```
22
+
23
+
Provides the following behavior as in this JavaScript snippet:
One or both of these implementations can be overridden as desired. Note that the generated `toString` calls `toJSON` internally, so overriding `toJSON` will affect its output as a side effect.
33
+
34
+
```rust
35
+
#[wasm_bindgen]
36
+
implBaz {
37
+
#[wasm_bindgen(js_name = toJSON)]
38
+
pubfnto_json(&self) ->i32 {
39
+
self.field
40
+
}
41
+
42
+
#[wasm_bindgen(js_name = toString)]
43
+
pubfnto_string(&self) ->String {
44
+
format!("Baz: {}", self.field)
45
+
}
46
+
}
47
+
```
48
+
49
+
Note that the output of `console.log` will remain unchanged and display only the `ptr` field in browsers. It is recommended to call `toJSON` or `JSON.stringify` in these situations to aid with logging or debugging. Node.js does not suffer from this limitation, see the section below.
50
+
51
+
## `inspectable` Classes in Node.js
52
+
53
+
When the `nodejs` target is used, an additional `[util.inspect.custom]` implementation is provided which calls `toJSON` internally. This method is used for `console.log` and similar functions to display all readable fields of the Rust struct.
0 commit comments