viewpoint-js
Compile-time validated JavaScript macro for Viewpoint.
This crate provides a js! macro that validates JavaScript syntax at compile time,
similar to how serde_json::json! validates JSON. This catches JavaScript syntax
errors early, before they reach the browser.
Features
- Compile-time validation: JavaScript syntax errors are caught during compilation
- Rust variable interpolation: Embed Rust expressions using
#{expr}syntax - Zero runtime overhead: Static strings when no interpolation is used
- Clear error messages: Points to the exact location of syntax errors
Usage
Add to your Cargo.toml:
[]
= "0.2"
= "0.2" # Required for interpolation
Simple Expressions
use js;
// Returns &'static str
let code = js!;
let code = js!;
let code = js!;
Interpolation
Use #{expr} to embed Rust expressions into JavaScript:
use js;
use ToJsValue;
let selector = ".my-class";
let code = js!;
// Produces: format!(...) that results in "document.querySelector(\".my-class\")"
let count = 42;
let code = js!;
// Produces: "Array(42).fill(0)"
Compile-Time Errors
Invalid JavaScript produces compile-time errors:
use js;
// This won't compile!
let code = js!
Supported Types for Interpolation
The following types implement ToJsValue:
- Integers:
i8,i16,i32,i64,i128,isize,u8,u16,u32,u64,u128,usize - Floats:
f32,f64(handlesNaN,Infinity,-Infinity) - Boolean:
bool - Strings:
String,&str(properly escaped) - Option:
Option<T>whereT: ToJsValue(produces value ornull) - JSON:
serde_json::Value(withjsonfeature)
Features
json- Enableserde_json::Valuesupport for interpolation
License
MIT