minify_js/lib.rs
1use emit::emit_js;
2use minify::minify_js;
3use parse_js::ast::Node;
4use parse_js::parse;
5
6mod emit;
7mod minify;
8
9pub use parse_js::error::SyntaxError;
10pub use parse_js::parse::toplevel::TopLevelMode;
11pub use parse_js::session::Session;
12
13/// Emits UTF-8 JavaScript code from a parsed AST in a minified way. This allows custom introspections and transforms on the tree before emitting it to code.
14///
15/// # Arguments
16///
17/// * `node` - The root node from the parsed AST.
18/// * `output` - Destination to write output JavaScript code.
19pub fn emit<'a>(node: Node<'a>, output: &mut Vec<u8>) -> () {
20 emit_js(output, node);
21}
22
23/// Minifies UTF-8 JavaScript code, represented as an array of bytes.
24///
25/// # Arguments
26///
27/// * `session` - Session to use as backing arena memory. Can be reused across calls and cleared at any time allowed by the Rust lifetime checker.
28/// * `top_level_mode` - How to parse the provided code.
29/// * `source` - A vector of bytes representing the source code to minify.
30/// * `output` - Destination to write minified output JavaScript code.
31///
32/// # Examples
33///
34/// ```
35/// use minify_js::{Session, TopLevelMode, minify};
36///
37/// let mut code: &[u8] = b"const main = () => { let my_first_variable = 1; };";
38/// let session = Session::new();
39/// let mut out = Vec::new();
40/// minify(&session, TopLevelMode::Global, code, &mut out).unwrap();
41/// assert_eq!(out.as_slice(), b"const main=()=>{let a=1}");
42/// ```
43pub fn minify<'a>(
44 session: &'a Session,
45 top_level_mode: TopLevelMode,
46 source: &'a [u8],
47 output: &mut Vec<u8>,
48) -> Result<(), SyntaxError<'a>> {
49 let parsed = parse(session, source, top_level_mode)?;
50 minify_js(session, parsed);
51 emit(parsed, output);
52 Ok(())
53}