JavaScript parser / mangler / compressor / beautifier toolkit
UglifyJS is a JavaScript parser, minifier, compressor and beautifier toolkit.
uglify-js supports JavaScript and most language features in ECMAScript.uglify-js.uglify-js@3 has a simplified API and CLI
that is not backwards compatible with uglify-js@2.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
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
…
Specify --output (-o) to declare the output file. Otherwise the output
goes to STDOUT.
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:
--source-map "filename='<NAME>'" to specify the name of the source map. The value of
filename is only used to set file attribute (see [the spec][sm-spec])
in source map file.
--source-map "root='<URL>'" to pass the URL where the original files can be found.
--source-map "names=false" to omit symbol names if you want to reduce size
of the source map file.
--source-map "url='<URL>'" to specify the URL where the source map can be found.
Otherwise UglifyJS assumes HTTP X-SourceMap is being used and will omit the
//# sourceMappingURL= directive.
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).
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.
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
To enable the mangler you need to pass --mangle (-m). The following
(comma-separated) options are supported:
eval (default: false) — mangle names visible in scopes where eval or
with are used.
reserved (default: []) — when mangling is enabled but you want to
prevent certain names from being mangled, you can declare those names with
--mangle reserved — pass a comma-separated list of names. For example:
uglifyjs ... -m reserved=['$','require','exports']
to prevent the require, exports and $ names from being changed.
--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.
--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);
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.
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:
…
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); // runt