Crate tauri_specta
source ·Expand description
Typesafe Tauri commands
Install
cargo add specta
cargo add tauri-specta --features javascript,typescript
Adding Specta to custom types
use specta::Type;
use serde::{Deserialize, Serialize};
// The `specta::Type` macro allows us to understand your types
// We implement `specta::Type` on primitive types for you.
// If you want to use a type from an external crate you may need to enable the feature on Specta.
#[derive(Serialize, Type)]
pub struct MyCustomReturnType {
pub some_field: String,
}
#[derive(Deserialize, Type)]
pub struct MyCustomArgumentType {
pub foo: String,
pub bar: i32,
}
Annotate your Tauri commands with Specta
#[tauri::command]
#[specta::specta] // <-- This bit here
fn greet3() -> MyCustomReturnType {
MyCustomReturnType {
some_field: "Hello World".into(),
}
}
#[tauri::command]
#[specta::specta] // <-- This bit here
fn greet(name: String) -> String {
format!("Hello {name}!")
}
Export your bindings
#[tauri::command]
#[specta::specta]
fn greet() {}
#[tauri::command]
#[specta::specta]
fn greet2() {}
#[tauri::command]
#[specta::specta]
fn greet3() {}
use tauri_specta::*;
// this example exports your types on startup when in debug mode or in a unit test. You can do whatever.
fn main() {
#[cfg(debug_assertions)]
ts::builder()
.commands(collect_commands![greet, greet2, greet3])
.path("../src/bindings.ts")
.export()
.unwrap();
// or export to JS with JSDoc
#[cfg(debug_assertions)]
js::builder()
.commands(collect_commands![greet, greet2, greet3])
.path("../src/bindings.js")
.export()
.unwrap();
}
#[test]
fn export_bindings() {
ts::builder()
.commands(collect_commands![greet, greet2, greet3])
.path("../src/bindings.ts")
.export()
.unwrap();
js::builder()
.commands(collect_commands![greet, greet2, greet3])
.path("../src/bindings.js")
.export()
.unwrap();
}
Usage on frontend
import { commands } from "./bindings"; // This should point to the file we export from Rust
await commands.greet("Brendan");
Modules
- js
javascript
The exporter for Javascript. - ts
typescript
The exporter for TypeScript.
Macros
Structs
- The configuration for the generator
- General exporter, takes a generic for the specific language that is being exported to.
Traits
- A set of functions that produce language-specific code