mishoo / UglifyJS

JavaScript parser / mangler / compressor / beautifier toolkit
http://lisperator.net/uglifyjs/
Other
13.09k stars 1.25k forks source link

UglifyJS 3

UglifyJS is a JavaScript parser, minifier, compressor and beautifier toolkit.

Note:

Install

First make sure you have installed the latest version of node.js (You may need to restart your computer after this step).

From NPM for use as a command line app:

npm install uglify-js -g

From NPM for programmatic use:

npm install uglify-js

Command line usage

uglifyjs [input files] [options]

UglifyJS can take multiple input files. It's recommended that you pass the input files first, then pass the options. UglifyJS will parse input files in sequence and apply any compression options. The files are parsed in the same global scope, that is, a reference from a file to some variable/function declared in another file will be matched properly.

If no input file is specified, UglifyJS will read from STDIN.

If you wish to pass your options before the input files, separate the two with a double dash to prevent input files being used as option arguments:

uglifyjs --compress --mangle -- input.js

Command line options

    -h, --help                  Print usage information.
                                `--help options` for details on available options.
    -V, --version               Print version number.
    -p, --parse <options>       Specify parser options:
                                `acorn`  Use Acorn for parsing.
                                `bare_returns`  Allow return outside of functions.
                                                Useful when minifying CommonJS
                                                modules and Userscripts that may
                                                be anonymous function wrapped (IIFE)
                                                by the .user.js engine `caller`.
                                `spidermonkey`  Assume input files are SpiderMonkey
                                                AST format (as JSON).
    -c, --compress [options]    Enable compressor/specify compressor options:
                                `pure_funcs`  List of functions that can be safely
                                              removed when their return values are
                                              not used.
    -m, --mangle [options]      Mangle names/specify mangler options:
                                `reserved`  List of names that should not be mangled.
    --mangle-props [options]    Mangle properties/specify mangler options:
                                `builtins`  Mangle property names that overlaps
                                            with standard JavaScript globals.
                                `debug`  Add debug prefix and suffix.
                                `domprops`  Mangle property names that overlaps
                                            with DOM properties.
                                `globals`  Mangle variable access via global object.
                                `keep_quoted`  Only mangle unquoted properties.
                                `regex`  Only mangle matched property names.
                                `reserved`  List of names that should not be mangled.
    -b, --beautify [options]    Beautify output/specify output options:
                                `beautify`  Enabled with `--beautify` by default.
                                `preamble`  Preamble to prepend to the output. You
                                            can use this to insert a comment, for
                                            example for licensing information.
                                            This will not be parsed, but the source
                                            map will adjust for its presence.
                                `quote_style`  Quote style:
                                               0 - auto
                                               1 - single
                                               2 - double
                                               3 - original
                                `wrap_iife`  Wrap IIFEs in parentheses. Note: you may
                                             want to disable `negate_iife` under
                                             compressor options.
    -O, --output-opts [options] Specify output options (`beautify` disabled by default).
    -o, --output <file>         Output file path (default STDOUT). Specify `ast` or
                                `spidermonkey` to write UglifyJS or SpiderMonkey AST
                                as JSON to STDOUT respectively.
    --annotations               Process and preserve comment annotations.
                                (`/*@__PURE__*/` or `/*#__PURE__*/`)
    --no-annotations            Ignore and discard comment annotations.
    --comments [filter]         Preserve copyright comments in the output. By
                                default this works like Google Closure, keeping
                                JSDoc-style comments that contain "@license" or
                                "@preserve". You can optionally pass one of the
                                following arguments to this flag:
                                - "all" to keep all comments
                                - a valid JS RegExp like `/foo/` or `/^!/` to
                                keep only matching comments.
                                Note that currently not *all* comments can be
                                kept when compression is on, because of dead
                                code removal or cascading statements into
                                sequences.
    --config-file <file>        Read `minify()` options from JSON file.
    -d, --define <expr>[=value] Global definitions.
    -e, --enclose [arg[:value]] Embed everything in a big function, with configurable
                                argument(s) & value(s).
    --expression                Parse a single expression, rather than a program
                                (for parsing JSON).
    --ie                        Support non-standard Internet Explorer.
                                Equivalent to setting `ie: true` in `minify()`
                                for `compress`, `mangle` and `output` options.
                                By default UglifyJS will not try to be IE-proof.
    --keep-fargs                Do not mangle/drop function arguments.
    --keep-fnames               Do not mangle/drop function names.  Useful for
                                code relying on Function.prototype.name.
    --module                    Process input as ES module (implies --toplevel)
    --no-module                 Avoid optimizations which may alter runtime behavior
                                under prior versions of JavaScript.
    --name-cache <file>         File to hold mangled name mappings.
    --self                      Build UglifyJS as a library (implies --wrap UglifyJS)
    --source-map [options]      Enable source map/specify source map options:
                                `base`  Path to compute relative paths from input files.
                                `content`  Input source map, useful if you're compressing
                                           JS that was generated from some other original
                                           code. Specify "inline" if the source map is
                                           included within the sources.
                                `filename`  Filename and/or location of the output source
                                            (sets `file` attribute in source map).
                                `includeSources`  Pass this flag if you want to include
                                                  the content of source files in the
                                                  source map as sourcesContent property.
                                `names` Include symbol names in the source map.
                                `root`  Path to the original source to be included in
                                        the source map.
                                `url`  If specified, path to the source map to append in
                                       `//# sourceMappingURL`.
    --timings                   Display operations run time on STDERR.
    --toplevel                  Compress and/or mangle variables in top level scope.
    --v8                        Support non-standard Chrome & Node.js
                                Equivalent to setting `v8: true` in `minify()`
                                for `mangle` and `output` options.
                                By default UglifyJS will not try to be v8-proof.
    --verbose                   Print diagnostic messages.
    --warn                      Print warning messages.
    --webkit                    Support non-standard Safari/Webkit.
                                Equivalent to setting `webkit: true` in `minify()`
                                for `compress`, `mangle` and `output` options.
                                By default UglifyJS will not try to be Safari-proof.
    --wrap <name>               Embed everything in a big function, making the
                                “exports” and “global” variables available. You
                                need to pass an argument to this option to
                                specify the name that your module will take
                                when included in, say, a browser.

Specify --output (-o) to declare the output file. Otherwise the output goes to STDOUT.

CLI source map options

UglifyJS can generate a source map file, which is highly useful for debugging your compressed JavaScript. To get a source map, pass --source-map --output output.js (source map will be written out to output.js.map).

Additional options:

For example:

uglifyjs js/file1.js js/file2.js \
         -o foo.min.js -c -m \
         --source-map "root='http://foo.com/src',url='foo.min.js.map'"

The above will compress and mangle file1.js and file2.js, will drop the output in foo.min.js and the source map in foo.min.js.map. The source mapping will refer to http://foo.com/src/js/file1.js and http://foo.com/src/js/file2.js (in fact it will list http://foo.com/src as the source map root, and the original files as js/file1.js and js/file2.js).

Composed source map

When you're compressing JS code that was output by a compiler such as CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd like to map back to the original code (i.e. CoffeeScript). UglifyJS has an option to take an input source map. Assuming you have a mapping from CoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript → compressed JS by mapping every token in the compiled JS to its original location.

To use this feature pass --source-map "content='/path/to/input/source.map'" or --source-map "content=inline" if the source map is included inline with the sources.

CLI compress options

You need to pass --compress (-c) to enable the compressor. Optionally you can pass a comma-separated list of compress options.

Options are in the form foo=bar, or just foo (the latter implies a boolean option that you want to set true; it's effectively a shortcut for foo=true).

Example:

uglifyjs file.js -c toplevel,sequences=false

CLI mangle options

To enable the mangler you need to pass --mangle (-m). The following (comma-separated) options are supported:

CLI mangling property names (--mangle-props)

Note: THIS WILL PROBABLY BREAK YOUR CODE. Mangling property names is a separate step, different from variable name mangling. Pass --mangle-props to enable it. It will mangle all properties in the input code with the exception of built in DOM properties and properties in core JavaScript classes. For example:

// example.js
var x = {
    baz_: 0,
    foo_: 1,
    calc: function() {
        return this.foo_ + this.baz_;
    }
};
x.bar_ = 2;
x["baz_"] = 3;
console.log(x.calc());

Mangle all properties (except for JavaScript builtins):

$ uglifyjs example.js -c -m --mangle-props
var x={o:0,_:1,l:function(){return this._+this.o}};x.t=2,x.o=3,console.log(x.l());

Mangle all properties except for reserved properties:

$ uglifyjs example.js -c -m --mangle-props reserved=[foo_,bar_]
var x={o:0,foo_:1,_:function(){return this.foo_+this.o}};x.bar_=2,x.o=3,console.log(x._());

Mangle all properties matching a regex:

$ uglifyjs example.js -c -m --mangle-props regex=/_$/
var x={o:0,_:1,calc:function(){return this._+this.o}};x.l=2,x.o=3,console.log(x.calc());

Combining mangle properties options:

$ uglifyjs example.js -c -m --mangle-props regex=/_$/,reserved=[bar_]
var x={o:0,_:1,calc:function(){return this._+this.o}};x.bar_=2,x.o=3,console.log(x.calc());

In order for this to be of any use, we avoid mangling standard JS names by default (--mangle-props builtins to override).

Specify --mangle-props globals to mangle property names of global object (e.g. self.foo) as global variables.

A default exclusion file is provided in tools/domprops.json which should cover most standard JS and DOM properties defined in various browsers. Pass --mangle-props domprops to disable this feature.

A regular expression can be used to define which property names should be mangled. For example, --mangle-props regex=/^_/ will only mangle property names that start with an underscore.

When you compress multiple files using this option, in order for them to work together in the end we need to ensure somehow that one property gets mangled to the same name in all of them. For this, pass --name-cache filename.json and UglifyJS will maintain these mappings in a file which can then be reused. It should be initially empty. Example:

$ rm -f /tmp/cache.json  # start fresh
$ uglifyjs file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js
$ uglifyjs file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js

Now, part1.js and part2.js will be consistent with each other in terms of mangled property names.

Using the name cache is not necessary if you compress all your files in a single call to UglifyJS.

Mangling unquoted names (--mangle-props keep_quoted)

Using quoted property name (o["foo"]) reserves the property name (foo) so that it is not mangled throughout the entire script even when used in an unquoted style (o.foo). Example:

// stuff.js
var o = {
    "foo": 1,
    bar: 3,
};
o.foo += o.bar;
console.log(o.foo);
$ uglifyjs stuff.js --mangle-props keep_quoted -c -m
var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo);

If the minified output will be processed again by UglifyJS, consider specifying keep_quoted_props so the same property names are preserved:

$ uglifyjs stuff.js --mangle-props keep_quoted -c -m -O keep_quoted_props
var o={"foo":1,o:3};o.foo+=o.o,console.log(o.foo);

Debugging property name mangling

You can also pass --mangle-props debug in order to mangle property names without completely obscuring them. For example the property o.foo would mangle to o._$foo$_ with this option. This allows property mangling of a large codebase while still being able to debug the code and identify where mangling is breaking things.

$ uglifyjs stuff.js --mangle-props debug -c -m
var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_);

You can also pass a custom suffix using --mangle-props debug=XYZ. This would then mangle o.foo to o._$foo$XYZ_. You can change this each time you compile a script to identify how a property got mangled. One technique is to pass a random number on every compile to simulate mangling changing with different inputs (e.g. as you update the input script with new properties), and to help identify mistakes like writing mangled keys to storage.

API Reference

Assuming installation via NPM, you can load UglifyJS in your application like this:

var UglifyJS = require("uglify-js");

There is a single high level function, minify(code, options), which will perform all minification phases in a configurable manner. By default minify() will enable the options compress and mangle. Example:

var code = "function add(first, second) { return first + second; }";
var result = UglifyJS.minify(code);
console.log(result.error); // runtime error, or `undefined` if no error
console.log(result.code);  // minified output: function add(n,d){return n+d}

You can minify more than one JavaScript file at a time by using an object for the first argument where the keys are file names and the values are source code:

var code = {
    "file1.js": "function add(first, second) { return first + second; }",
    "file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var result = UglifyJS.minify(code);
console.log(result.code);
// function add(d,n){return d+n}console.log(add(3,7));

The toplevel option:

var code = {
    "file1.js": "function add(first, second) { return first + second; }",
    "file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var options = { toplevel: true };
var result = UglifyJS.minify(code, options);
console.log(result.code);
// console.log(3+7);

The nameCache option:

var options = {
    mangle: {
        toplevel: true,
    },
    nameCache: {}
};
var result1 = UglifyJS.minify({
    "file1.js": "function add(first, second) { return first + second; }"
}, options);
var result2 = UglifyJS.minify({
    "file2.js": "console.log(add(1 + 2, 3 + 4));"
}, options);
console.log(result1.code);
// function n(n,r){return n+r}
console.log(result2.code);
// console.log(n(3,7));

You may persist the name cache to the file system in the following way:

var cacheFileName = "/tmp/cache.json";
var options = {
    mangle: {
        properties: true,
    },
    nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8"))
};
fs.writeFileSync("part1.js", UglifyJS.minify({
    "file1.js": fs.readFileSync("file1.js", "utf8"),
    "file2.js": fs.readFileSync("file2.js", "utf8")
}, options).code, "utf8");
fs.writeFileSync("part2.js", UglifyJS.minify({
    "file3.js": fs.readFileSync("file3.js", "utf8"),
    "file4.js": fs.readFileSync("file4.js", "utf8")
}, options).code, "utf8");
fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8");

An example of a combination of minify() options:

var code = {
    "file1.js": "function add(first, second) { return first + second; }",
    "file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var options = {
    toplevel: true,
    compress: {
        global_defs: {
            "@console.log": "alert"
        },
        passes: 2
    },
    output: {
        beautify: false,
        preamble: "/* uglified */"
    }
};
var result = UglifyJS.minify(code, options);
console.log(result.code);
// /* uglified */
// alert(10);"

To produce warnings:

var code = "function f(){ var u; return 2 + 3; }";
var options = { warnings: true };
var result = UglifyJS.minify(code, options);
console.log(result.error);    // runtime error, `undefined` in this case
console.log(result.warnings); // [ 'Dropping unused variable u [0:1,18]' ]
console.log(result.code);     // function f(){return 5}

An error example:

var result = UglifyJS.minify({"foo.js" : "if (0) else console.log(1);"});
console.log(JSON.stringify(result.error));
// {"message":"Unexpected token: keyword (else)","filename":"foo.js","line":1,"col":7,"pos":7}

Note: unlike uglify-js@2.x, the 3.x API does not throw errors. To achieve a similar effect one could do the following:

var result = UglifyJS.minify(code, options);
if (result.error) throw result.error;

Minify options

Minify options structure

{
    parse: {
        // parse options
    },
    compress: {
        // compress options
    },
    mangle: {
        // mangle options

        properties: {
            // mangle property options
        }
    },
    output: {
        // output options
    },
    sourceMap: {
        // source map options
    },
    nameCache: null, // or specify a name cache object
    toplevel: false,
    warnings: false,
}

Source map options

To generate a source map:

var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, {
    sourceMap: {
        filename: "out.js",
        url: "out.js.map"
    }
});
console.log(result.code); // minified output
console.log(result.map);  // source map

Note that the source map is not saved in a file, it's just returned in result.map. The value passed for sourceMap.url is only used to set //# sourceMappingURL=out.js.map in result.code. The value of filename is only used to set file attribute (see the spec) in source map file.

You can set option sourceMap.url to be "inline" and source map will be appended to code.

You can also specify sourceRoot property to be included in source map:

var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, {
    sourceMap: {
        root: "http://example.com/src",
        url: "out.js.map"
    }
});

If you're compressing compiled JavaScript and have a source map for it, you can use sourceMap.content:

var result = UglifyJS.minify({"compiled.js": "compiled code"}, {
    sourceMap: {
        content: "content from compiled.js.map",
        url: "minified.js.map"
    }
});
// same as before, it returns `code` and `map`

If you're using the X-SourceMap header instead, you can just omit sourceMap.url.

If you wish to reduce file size of the source map, set option sourceMap.names to be false and all symbol names will be omitted.

Parse options

Compress options

Mangle options

Examples:

// test.js
var globalVar;
function funcName(firstLongName, anotherLongName) {
    var myVariable = firstLongName +  anotherLongName;
}
var code = fs.readFileSync("test.js", "utf8");

UglifyJS.minify(code).code;
// 'function funcName(a,n){}var globalVar;'

UglifyJS.minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
// 'function funcName(firstLongName,a){}var globalVar;'

UglifyJS.minify(code, { mangle: { toplevel: true } }).code;
// 'function n(n,a){}var a;'

Mangle properties options

Output options

The code generator tries to output shortest code possible by default. In case you want beautified output, pass --beautify (-b). Optionally you can pass additional arguments that control the code output:

Miscellaneous

Keeping copyright notices or other comments

You can pass --comments to retain certain comments in the output. By default it will keep JSDoc-style comments that contain "@preserve", "@license" or "@cc_on" (conditional compilation for IE). You can pass --comments all to keep all the comments, or a valid JavaScript regexp to keep only comments that match this regexp. For example --comments /^!/ will keep comments like /*! Copyright Notice */.

Note, however, that there might be situations where comments are lost. For example:

function f() {
    /** @preserve Foo Bar */
    function g() {
        // this function is never called
    }
    return something();
}

Even though it has "@preserve", the comment will be lost because the inner function g (which is the AST node to which the comment is attached to) is discarded by the compressor as not referenced.

The safest comments where to place copyright information (or other info that needs to be kept in the output) are comments attached to toplevel nodes.

The unsafe compress option

It enables some transformations that might break code logic in certain contrived cases, but should be fine for most code. You might want to try it on your own code, it should reduce the minified size. Here's what happens when this flag is on:

Conditional compilation

You can use the --define (-d) switch in order to declare global variables that UglifyJS will assume to be constants (unless defined in scope). For example if you pass --define DEBUG=false then, coupled with dead code removal UglifyJS will discard the following from the output:

if (DEBUG) {
    console.log("debug stuff");
}

You can specify nested constants in the form of --define env.DEBUG=false.

UglifyJS will warn about the condition being always false and about dropping unreachable code; for now there is no option to turn off only this specific warning, you can pass warnings=false to turn off all warnings.

Another way of doing that is to declare your globals as constants in a separate file and include it into the build. For example you can have a build/defines.js file with the following:

var DEBUG = false;
var PRODUCTION = true;
// etc.

and build your code like this:

uglifyjs build/defines.js js/foo.js js/bar.js... -c

UglifyJS will notice the constants and, since they cannot be altered, it will evaluate references to them to the value itself and drop unreachable code as usual. The build will contain the const declarations if you use them. If you are targeting < ES6 environments which does not support const, using var with reduce_vars (enabled by default) should suffice.

Conditional compilation API

You can also use conditional compilation via the programmatic API. With the difference that the property name is global_defs and is a compressor property:

var result = UglifyJS.minify(fs.readFileSync("input.js", "utf8"), {
    compress: {
        dead_code: true,
        global_defs: {
            DEBUG: false
        }
    }
});

To replace an identifier with an arbitrary non-constant expression it is necessary to prefix the global_defs key with "@" to instruct UglifyJS to parse the value as an expression:

UglifyJS.minify("alert('hello');", {
    compress: {
        global_defs: {
            "@alert": "console.log"
        }
    }
}).code;
// returns: 'console.log("hello");'

Otherwise it would be replaced as string literal:

UglifyJS.minify("alert('hello');", {
    compress: {
        global_defs: {
            "alert": "console.log"
        }
    }
}).code;
// returns: '"console.log"("hello");'

Using native Uglify AST with minify()

// example: parse only, produce native Uglify AST

var result = UglifyJS.minify(code, {
    parse: {},
    compress: false,
    mangle: false,
    output: {
        ast: true,
        code: false  // optional - faster if false
    }
});

// result.ast contains native Uglify AST
// example: accept native Uglify AST input and then compress and mangle
//          to produce both code and native AST.

var result = UglifyJS.minify(ast, {
    compress: {},
    mangle: {},
    output: {
        ast: true,
        code: true  // optional - faster if false
    }
});

// result.ast contains native Uglify AST
// result.code contains the minified code in string form.

Working with Uglify AST

Transversal and transformation of the native AST can be performed through TreeWalker and TreeTransformer respectively.

ESTree / SpiderMonkey AST

UglifyJS has its own abstract syntax tree format; for practical reasons we can't easily change to using the SpiderMonkey AST internally. However, UglifyJS now has a converter which can import a SpiderMonkey AST.

For example Acorn is a super-fast parser that produces a SpiderMonkey AST. It has a small CLI utility that parses one file and dumps the AST in JSON on the standard output. To use UglifyJS to mangle and compress that:

acorn file.js | uglifyjs -p spidermonkey -m -c

The -p spidermonkey option tells UglifyJS that all input files are not JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we don't use our own parser in this case, but just transform that AST into our internal AST.

Use Acorn for parsing

More for fun, I added the -p acorn option which will use Acorn to do all the parsing. If you pass this option, UglifyJS will require("acorn").

Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but converting the SpiderMonkey tree that Acorn produces takes another 150ms so in total it's a bit more than just using UglifyJS's own parser.

Uglify Fast Minify Mode

It's not well known, but whitespace removal and symbol mangling accounts for 95% of the size reduction in minified code for most JavaScript - not elaborate code transforms. One can simply disable compress to speed up Uglify builds by 3 to 5 times.

d3.js minify size gzip size minify time (seconds)
original 511,371 119,932 -
uglify-js@3.13.0 mangle=false, compress=false 363,988 95,695 0.56
uglify-js@3.13.0 mangle=true, compress=false 253,305 81,281 0.99
uglify-js@3.13.0 mangle=true, compress=true 244,436 79,854 5.30

To enable fast minify mode from the CLI use:

uglifyjs file.js -m

To enable fast minify mode with the API use:

UglifyJS.minify(code, { compress: false, mangle: true });

Source maps and debugging

Various compress transforms that simplify, rearrange, inline and remove code are known to have an adverse effect on debugging with source maps. This is expected as code is optimized and mappings are often simply not possible as some code no longer exists. For highest fidelity in source map debugging disable the Uglify compress option and just use mangle.

Compiler assumptions

To allow for better optimizations, the compiler makes various assumptions: