Precompile JavaScript scripts to bytecode
mainYou can precompile JavaScript scripts into runtime-specific bytecode to improve loading performance or to ship scripts as binary artifacts. This is achieved using a two-step process:
- Compile: Use
Session::compile_scriptto transform a JavaScript string into bytecode. - Load: Use
Session::create_script_from_bytesto load that bytecode back into a session for execution.
Important: Runtime Compatibility
Bytecode is runtime-specific. If you compile a script using ScriptRuntime::QJS, the resulting bytecode can only be loaded by a session using the QJS runtime. A blob produced for QJS will not work under V8 or other runtimes.
// Conceptual workflow based on the example:
// 1. Compile the script to bytecode
let bytecode = session.compile_script("console.log('Hello!');", ScriptRuntime::QJS)?;
// 2. (Optional) Save bytecode to a file
// std::fs::write("compiled.bin", &bytecode)?;
// 3. Load the bytecode back from bytes
let script = session.create_script_from_bytes(bytecode, ScriptRuntime::QJS)?;
// 4. Run the script
script.load()?;