ts-bindgen: automatically generate rust wasm-bindgen bindings for typescript definitions to easily interact with javascript libraries from rust compiled to wasm.
Head to ts-bindgen.ratchetdesigns.com to try ts-bindgen in your browser now by copy/pasting typescript definitions to see the rust bindings it generates.
ts-bindgen is currently alpha software and it should be expected that any or all of the following might change significantly from version to version:
There are currently known issues that will prevent generation of reasonable bindings for some typescript idioms.
We welcome contributions and issues!
Head over to ts-bindgen.ratchetdesigns.com to generate rust bindings by copy/pasting typescript definitions in your browser.
To start generating bindings in your rust projects, you have a few options:
cargo run ts-bindgen -- --output src/bindings.rs your-ts-module
to generate src/bindings.rs
from your-ts-module
where your-ts-module
is a ./path/to/defs.d.ts
, /path/to/defs.d.ts
, or module-in-node_modules
.cargo run ts-bindgen -- --output src/bindings.rs --rerun-if-changed your-ts-module
in your build.rs
.ts-bindgen = { version = "0.5.0", default-features = false }
to your cargo.toml
dependencies and invoke ts_bindgen::generate_rust_string_for_typescript(ts_bindgen::StdFs, "your-module")
in your build.rs
. Note: while the ts-bindgen executable will rustfmt the generated bindings, generate_rust_string_for_typescript
does not.The generated bindings depend on the ts-bindgen runtime: ts-bindgen-rt, wasm-bindgen, serde, and (optionally) js-sys and web-sys so add the following to your Cargo.toml
:
[dependencies]
ts-bindgen-rt = "0.5.0"
wasm-bindgen = "0.2.87"
serde = { version = "1.0", features = ["derive"] }
js-sys = "0.3.64" # optional, depending on your input typescript
web-sys = { version = "0.3.53", features = ["Window"] } # optional, update with features for any types your bindings use
ts-bindgen seeks reasonable rust ergonomics and frequently wraps wasm-bindgen bindings to present a (hopefully) more "rust-y" interface. For example, functions and methods are wrapped to convert their arguments and return values to/from javascript/rust representations, javascript classes are wrapped in newtype structs, and traits are generated for javscript class inheritance hierarcies. To more faithfully preserve javascript semantics of null/undefined, functions, etc., we implement a custom (de)serializer similar to serde-wasm-bindgen to marshall between JsValues and generated bindings. We expect that there are many opportunities for performance improvement that have not yet been explored.
ts-bindgen consists of a few crates:
Copyright 2022 Adam Berger, Ratchet Designs.
ts-bindgen is licensed under either of the MIT or Apache licenses, at your option.
ts-bindgen is crafted thoughtfully by Ratchet Designs