|
| 1 | +//! Usage: cargo run --example ts_to_js path/to/ts |
| 2 | +//! |
| 3 | +//! This program will emit output to stdout. |
| 4 | +
|
| 5 | +use std::{env, path::Path}; |
| 6 | +use swc_common::{ |
| 7 | + self, |
| 8 | + comments::SingleThreadedComments, |
| 9 | + errors::{ColorConfig, Handler}, |
| 10 | + sync::Lrc, |
| 11 | + SourceMap, |
| 12 | +}; |
| 13 | +use swc_ecma_codegen::{text_writer::JsWriter, Emitter}; |
| 14 | +use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax, TsConfig}; |
| 15 | +use swc_ecma_transforms_base::fixer::fixer; |
| 16 | +use swc_ecma_transforms_typescript::strip; |
| 17 | +use swc_ecma_visit::FoldWith; |
| 18 | + |
| 19 | +fn main() { |
| 20 | + let cm: Lrc<SourceMap> = Default::default(); |
| 21 | + let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(cm.clone())); |
| 22 | + |
| 23 | + // Real usage |
| 24 | + // let fm = cm |
| 25 | + // .load_file(Path::new("test.js")) |
| 26 | + // .expect("failed to load test.js"); |
| 27 | + |
| 28 | + let input = env::args() |
| 29 | + .nth(1) |
| 30 | + .expect("please provide the path of input typescript file"); |
| 31 | + |
| 32 | + let fm = cm |
| 33 | + .load_file(Path::new(&input)) |
| 34 | + .expect("failed to load input typescript file"); |
| 35 | + |
| 36 | + let comments = SingleThreadedComments::default(); |
| 37 | + |
| 38 | + let lexer = Lexer::new( |
| 39 | + Syntax::Typescript(TsConfig { |
| 40 | + tsx: input.ends_with(".tsx"), |
| 41 | + dynamic_import: true, |
| 42 | + ..Default::default() |
| 43 | + }), |
| 44 | + Default::default(), |
| 45 | + StringInput::from(&*fm), |
| 46 | + Some(&comments), |
| 47 | + ); |
| 48 | + |
| 49 | + let mut parser = Parser::new_from(lexer); |
| 50 | + |
| 51 | + for e in parser.take_errors() { |
| 52 | + e.into_diagnostic(&handler).emit(); |
| 53 | + } |
| 54 | + |
| 55 | + let module = parser |
| 56 | + .parse_module() |
| 57 | + .map_err(|e| e.into_diagnostic(&handler).emit()) |
| 58 | + .expect("failed to parse module."); |
| 59 | + |
| 60 | + // Remove typescript types |
| 61 | + let module = module.fold_with(&mut strip()); |
| 62 | + |
| 63 | + // Ensure that we have eenough parenthesis. |
| 64 | + let module = module.fold_with(&mut fixer(Some(&comments))); |
| 65 | + |
| 66 | + let mut buf = vec![]; |
| 67 | + { |
| 68 | + let mut emitter = Emitter { |
| 69 | + cfg: swc_ecma_codegen::Config { minify: false }, |
| 70 | + cm: cm.clone(), |
| 71 | + comments: Some(&comments), |
| 72 | + wr: JsWriter::new(cm.clone(), "\n", &mut buf, None), |
| 73 | + }; |
| 74 | + |
| 75 | + emitter.emit_module(&module).unwrap(); |
| 76 | + } |
| 77 | + |
| 78 | + println!("{}", String::from_utf8(buf).expect("non-utf8?")); |
| 79 | +} |
0 commit comments