specta-rs / tauri-specta

Completely typesafe Tauri commands
MIT License
368 stars 40 forks source link

Allow for exporting constants #95

Closed Isaac-Leonard closed 5 months ago

Isaac-Leonard commented 5 months ago

Would it be possible to add a way to export constants as well as types? This would be quite useful when using static data on both the backend and frontend such as names of things without having to define them seperately and risk bugs from mispelling things such as arrays of enum names generated from the strum crate or list of driver names from gdal. It would probably be simple enough to do this manually however integrating with existing code generation would be cleaner and allow for configuring it all in one place.

oscartbeaumont commented 5 months ago

This will be supported in the next release using the following syntax:

let builder = ts::builder()
    // < your commands and events are probaly here
    .types(StaticCollection::default().register("myConstant", 42)); // < call `register` as much as you want.

It requires that the value (42 in the example above) implements serde::Serialize and it puts it into the Tauri Specta bindings like the following:

export const myConstant = 42 as const; // `as const` will be applied Tauri Specta detects it's valid.

Let me know how this goes for your usecase as I would be open to refining the feature if you run into any issues!

kareemmahlees commented 3 months ago

Just for future reference, the example mentioned here and in the readme are wrong, it should be:

let builder = ts::builder()
    // < your commands and events are probaly here
    .statics(StaticCollection::default().register("myConstant", 42)); // < call `register` as much as you want.
oscartbeaumont commented 3 months ago

Fixed. Thanks for pointing it out.