oxc/crates/oxc_codegen/examples/codegen.rs
Andrew McClenaghan e6d536cb9b
feat(codegen): configurable typescript codegen (#2443)
- Adds option to `CodegenOptions` - `enable_typescript` to enable output
of TS.
- Stops skipping output that is TS when `enable_typescript` is enabled
- Adds TS support to 
    - Function
    - FormalParameter
    - BindingPattern
 - Adds basic tests for TS generation

---------

Co-authored-by: Boshen <boshenc@gmail.com>
2024-02-20 12:09:28 +08:00

40 lines
1.3 KiB
Rust

use std::{env, path::Path};
use oxc_allocator::Allocator;
use oxc_codegen::{Codegen, CodegenOptions};
use oxc_parser::Parser;
use oxc_span::SourceType;
// Instruction:
// 1. create a `test.js`
// 2. run `cargo run -p oxc_codegen --example codegen` or `just example codegen`
fn main() {
let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
let path = Path::new(&name);
let source_text = std::fs::read_to_string(path).unwrap_or_else(|_| panic!("{name} not found"));
let source_type = SourceType::from_path(path).unwrap();
let allocator = Allocator::default();
let ret = Parser::new(&allocator, &source_text, source_type).parse();
if !ret.errors.is_empty() {
for error in ret.errors {
let error = error.with_source_code(source_text.clone());
println!("{error:?}");
}
return;
}
println!("Original:");
println!("{source_text}");
let codegen_options = CodegenOptions::default();
let printed = Codegen::<false>::new(source_text.len(), codegen_options).build(&ret.program);
println!("Printed:");
println!("{printed}");
let ret = Parser::new(&allocator, &printed, source_type).parse();
let minified = Codegen::<true>::new(source_text.len(), codegen_options).build(&ret.program);
println!("Minified:");
println!("{minified}");
}