JS compressor of world fame.

Open demo

Latest blog entries tagged "uglifyjs"

/** May the source-map be with you! **/

UglifyJS — the parser

The parser creates a custom abstract syntax tree given a piece of JavaScript code. Perhaps you should read about the AST first.


// it takes the source code to parse as first argument:
var ast = UglifyJS.parse("function sum(x, y){ return x + y }");

// optionally you can pass another argument with options:
var ast = UglifyJS.parse(code, {
    strict   : true,              // default is false
    filename : "Input file name", // default is null
    toplevel : ast                // also null

When no toplevel argument is given, the parser will create an AST_Toplevel node and place into its body all statements from the code. However, to generate a proper source map it was useful to have the ability to parse multiple files into a single toplevel node. To do this you would say:

var ast = UglifyJS.parse(file1_content, { filename: "file1.js" });
ast = UglifyJS.parse(file2_content, { filename: "file2.js", toplevel: ast });
ast = UglifyJS.parse(file3_content, { filename: "file3.js", toplevel: ast });

// or in general, if in `files` array you have the list of files:
var ast = null;
    var code = fs.readFileSync(file, "utf8");
    ast = UglifyJS.parse(code, { filename: file, ast: ast });

Read more about the AST structures.

Fork me on Github