Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / handlebars / node_modules / uglify-js / README.md
1 UglifyJS 2
2 ==========
3 [![Build Status](https://travis-ci.org/mishoo/UglifyJS2.svg)](https://travis-ci.org/mishoo/UglifyJS2)
4
5 UglifyJS is a JavaScript parser, minifier, compressor or beautifier toolkit.
6
7 This page documents the command line utility.  For
8 [API and internals documentation see my website](http://lisperator.net/uglifyjs/).
9 There's also an
10 [in-browser online demo](http://lisperator.net/uglifyjs/#demo) (for Firefox,
11 Chrome and probably Safari).
12
13 Note: release versions of `uglify-js` only support ECMAScript 5 (ES5). If you wish to minify
14 ES2015+ (ES6+) code then please use the [harmony](#harmony) development branch.
15
16 Install
17 -------
18
19 First make sure you have installed the latest version of [node.js](http://nodejs.org/)
20 (You may need to restart your computer after this step).
21
22 From NPM for use as a command line app:
23
24     npm install uglify-js -g
25
26 From NPM for programmatic use:
27
28     npm install uglify-js
29
30 From Git:
31
32     git clone git://github.com/mishoo/UglifyJS2.git
33     cd UglifyJS2
34     npm link .
35
36 Usage
37 -----
38
39     uglifyjs [input files] [options]
40
41 UglifyJS2 can take multiple input files.  It's recommended that you pass the
42 input files first, then pass the options.  UglifyJS will parse input files
43 in sequence and apply any compression options.  The files are parsed in the
44 same global scope, that is, a reference from a file to some
45 variable/function declared in another file will be matched properly.
46
47 If you want to read from STDIN instead, pass a single dash instead of input
48 files.
49
50 If you wish to pass your options before the input files, separate the two with
51 a double dash to prevent input files being used as option arguments:
52
53     uglifyjs --compress --mangle -- input.js
54
55 The available options are:
56
57 ```
58   --source-map                  Specify an output file where to generate source
59                                 map.
60   --source-map-root             The path to the original source to be included
61                                 in the source map.
62   --source-map-url              The path to the source map to be added in //#
63                                 sourceMappingURL.  Defaults to the value passed
64                                 with --source-map.
65   --source-map-include-sources  Pass this flag if you want to include the
66                                 content of source files in the source map as
67                                 sourcesContent property.
68   --source-map-inline           Write base64-encoded source map to the end of js output.
69   --in-source-map               Input source map, useful if you're compressing
70                                 JS that was generated from some other original
71                                 code.
72   --screw-ie8                   Use this flag if you don't wish to support
73                                 Internet Explorer 6/7/8.
74                                 By default UglifyJS will not try to be IE-proof.
75   --support-ie8                 Use this flag to support Internet Explorer 6/7/8.
76                                 Equivalent to setting `screw_ie8: false` in `minify()`
77                                 for `compress`, `mangle` and `output` options.
78   --expr                        Parse a single expression, rather than a
79                                 program (for parsing JSON)
80   -p, --prefix                  Skip prefix for original filenames that appear
81                                 in source maps. For example -p 3 will drop 3
82                                 directories from file names and ensure they are
83                                 relative paths. You can also specify -p
84                                 relative, which will make UglifyJS figure out
85                                 itself the relative paths between original
86                                 sources, the source map and the output file.
87   -o, --output                  Output file (default STDOUT).
88   -b, --beautify                Beautify output/specify output options.
89   -m, --mangle                  Mangle names/pass mangler options.
90   -r, --reserved                Reserved names to exclude from mangling.
91   -c, --compress                Enable compressor/pass compressor options, e.g.
92                                 `-c 'if_return=false,pure_funcs=["Math.pow","console.log"]'`
93                                 Use `-c` with no argument to enable default compression
94                                 options.
95   -d, --define                  Global definitions
96   -e, --enclose                 Embed everything in a big function, with a
97                                 configurable parameter/argument list.
98   --comments                    Preserve copyright comments in the output. By
99                                 default this works like Google Closure, keeping
100                                 JSDoc-style comments that contain "@license" or
101                                 "@preserve". You can optionally pass one of the
102                                 following arguments to this flag:
103                                 - "all" to keep all comments
104                                 - a valid JS RegExp like `/foo/` or `/^!/` to
105                                 keep only matching comments.
106                                 Note that currently not *all* comments can be
107                                 kept when compression is on, because of dead
108                                 code removal or cascading statements into
109                                 sequences.
110   --preamble                    Preamble to prepend to the output.  You can use
111                                 this to insert a comment, for example for
112                                 licensing information.  This will not be
113                                 parsed, but the source map will adjust for its
114                                 presence.
115   --stats                       Display operations run time on STDERR.
116   --acorn                       Use Acorn for parsing.
117   --spidermonkey                Assume input files are SpiderMonkey AST format
118                                 (as JSON).
119   --self                        Build itself (UglifyJS2) as a library (implies
120                                 --wrap=UglifyJS --export-all)
121   --wrap                        Embed everything in a big function, making the
122                                 “exports” and “global” variables available. You
123                                 need to pass an argument to this option to
124                                 specify the name that your module will take
125                                 when included in, say, a browser.
126   --export-all                  Only used when --wrap, this tells UglifyJS to
127                                 add code to automatically export all globals.
128   --lint                        Display some scope warnings
129   -v, --verbose                 Verbose
130   -V, --version                 Print version number and exit.
131   --noerr                       Don't throw an error for unknown options in -c,
132                                 -b or -m.
133   --bare-returns                Allow return outside of functions.  Useful when
134                                 minifying CommonJS modules and Userscripts that
135                                 may be anonymous function wrapped (IIFE) by the
136                                 .user.js engine `caller`.
137   --keep-fnames                 Do not mangle/drop function names.  Useful for
138                                 code relying on Function.prototype.name.
139   --reserved-file               File containing reserved names
140   --reserve-domprops            Make (most?) DOM properties reserved for
141                                 --mangle-props
142   --mangle-props                Mangle property names (default `0`). Set to
143                                 `true` or `1` to mangle all property names. Set
144                                 to `unquoted` or `2` to only mangle unquoted
145                                 property names. Mode `2` also enables the
146                                 `keep_quoted_props` beautifier option to
147                                 preserve the quotes around property names and
148                                 disables the `properties` compressor option to
149                                 prevent rewriting quoted properties with dot
150                                 notation. You can override these by setting
151                                 them explicitly on the command line.
152   --mangle-regex                Only mangle property names matching the regex
153   --name-cache                  File to hold mangled names mappings
154   --pure-funcs                  Functions that can be safely removed if their
155                                 return value is not used, e.g.
156                                 `--pure-funcs Math.floor console.info`
157                                 (requires `--compress`)
158 ```
159
160 Specify `--output` (`-o`) to declare the output file.  Otherwise the output
161 goes to STDOUT.
162
163 ## Source map options
164
165 UglifyJS2 can generate a source map file, which is highly useful for
166 debugging your compressed JavaScript.  To get a source map, pass
167 `--source-map output.js.map` (full path to the file where you want the
168 source map dumped).
169
170 Additionally you might need `--source-map-root` to pass the URL where the
171 original files can be found.  In case you are passing full paths to input
172 files to UglifyJS, you can use `--prefix` (`-p`) to specify the number of
173 directories to drop from the path prefix when declaring files in the source
174 map.
175
176 For example:
177
178     uglifyjs /home/doe/work/foo/src/js/file1.js \
179              /home/doe/work/foo/src/js/file2.js \
180              -o foo.min.js \
181              --source-map foo.min.js.map \
182              --source-map-root http://foo.com/src \
183              -p 5 -c -m
184
185 The above will compress and mangle `file1.js` and `file2.js`, will drop the
186 output in `foo.min.js` and the source map in `foo.min.js.map`.  The source
187 mapping will refer to `http://foo.com/src/js/file1.js` and
188 `http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src`
189 as the source map root, and the original files as `js/file1.js` and
190 `js/file2.js`).
191
192 ### Composed source map
193
194 When you're compressing JS code that was output by a compiler such as
195 CoffeeScript, mapping to the JS code won't be too helpful.  Instead, you'd
196 like to map back to the original code (i.e. CoffeeScript).  UglifyJS has an
197 option to take an input source map.  Assuming you have a mapping from
198 CoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript →
199 compressed JS by mapping every token in the compiled JS to its original
200 location.
201
202 To use this feature you need to pass `--in-source-map
203 /path/to/input/source.map`.  Normally the input source map should also point
204 to the file containing the generated JS, so if that's correct you can omit
205 input files from the command line.
206
207 ## Mangler options
208
209 To enable the mangler you need to pass `--mangle` (`-m`).  The following
210 (comma-separated) options are supported:
211
212 - `toplevel` — mangle names declared in the toplevel scope (disabled by
213   default).
214
215 - `eval` — mangle names visible in scopes where `eval` or `with` are used
216   (disabled by default).
217
218 When mangling is enabled but you want to prevent certain names from being
219 mangled, you can declare those names with `--reserved` (`-r`) — pass a
220 comma-separated list of names.  For example:
221
222     uglifyjs ... -m -r '$,require,exports'
223
224 to prevent the `require`, `exports` and `$` names from being changed.
225
226 ### Mangling property names (`--mangle-props`)
227
228 **Note:** this will probably break your code.  Mangling property names is a
229 separate step, different from variable name mangling.  Pass
230 `--mangle-props`.  It will mangle all properties that are seen in some
231 object literal, or that are assigned to.  For example:
232
233 ```js
234 var x = {
235   foo: 1
236 };
237
238 x.bar = 2;
239 x["baz"] = 3;
240 x[condition ? "moo" : "boo"] = 4;
241 console.log(x.something());
242 ```
243
244 In the above code, `foo`, `bar`, `baz`, `moo` and `boo` will be replaced
245 with single characters, while `something()` will be left as is.
246
247 In order for this to be of any use, we should avoid mangling standard JS
248 names.  For instance, if your code would contain `x.length = 10`, then
249 `length` becomes a candidate for mangling and it will be mangled throughout
250 the code, regardless if it's being used as part of your own objects or
251 accessing an array's length.  To avoid that, you can use `--reserved-file`
252 to pass a filename that should contain the names to be excluded from
253 mangling.  This file can be used both for excluding variable names and
254 property names.  It could look like this, for example:
255
256 ```js
257 {
258   "vars": [ "define", "require", ... ],
259   "props": [ "length", "prototype", ... ]
260 }
261 ```
262
263 `--reserved-file` can be an array of file names (either a single
264 comma-separated argument, or you can pass multiple `--reserved-file`
265 arguments) — in this case it will exclude names from all those files.
266
267 A default exclusion file is provided in `tools/domprops.json` which should
268 cover most standard JS and DOM properties defined in various browsers.  Pass
269 `--reserve-domprops` to read that in.
270
271 You can also use a regular expression to define which property names should be
272 mangled.  For example, `--mangle-regex="/^_/"` will only mangle property names
273 that start with an underscore.
274
275 When you compress multiple files using this option, in order for them to
276 work together in the end we need to ensure somehow that one property gets
277 mangled to the same name in all of them.  For this, pass `--name-cache
278 filename.json` and UglifyJS will maintain these mappings in a file which can
279 then be reused.  It should be initially empty.  Example:
280
281 ```
282 rm -f /tmp/cache.json  # start fresh
283 uglifyjs file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js
284 uglifyjs file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js
285 ```
286
287 Now, `part1.js` and `part2.js` will be consistent with each other in terms
288 of mangled property names.
289
290 Using the name cache is not necessary if you compress all your files in a
291 single call to UglifyJS.
292
293 #### Mangling unquoted names (`--mangle-props=unquoted` or `--mangle-props=2`)
294
295 Using quoted property name (`o["foo"]`) reserves the property name (`foo`)
296 so that it is not mangled throughout the entire script even when used in an
297 unquoted style (`o.foo`). Example:
298
299 ```
300 $ echo 'var o={"foo":1, bar:3}; o.foo += o.bar; console.log(o.foo);' | uglifyjs --mangle-props=2 -mc
301 var o={"foo":1,a:3};o.foo+=o.a,console.log(o.foo);
302 ```
303
304 #### Debugging property name mangling
305
306 You can also pass `--mangle-props-debug` in order to mangle property names
307 without completely obscuring them. For example the property `o.foo`
308 would mangle to `o._$foo$_` with this option. This allows property mangling
309 of a large codebase while still being able to debug the code and identify
310 where mangling is breaking things.
311
312 You can also pass a custom suffix using `--mangle-props-debug=XYZ`. This would then
313 mangle `o.foo` to `o._$foo$XYZ_`. You can change this each time you compile a
314 script to identify how a property got mangled. One technique is to pass a
315 random number on every compile to simulate mangling changing with different
316 inputs (e.g. as you update the input script with new properties), and to help
317 identify mistakes like writing mangled keys to storage.
318
319 ## Compressor options
320
321 You need to pass `--compress` (`-c`) to enable the compressor.  Optionally
322 you can pass a comma-separated list of options.  Options are in the form
323 `foo=bar`, or just `foo` (the latter implies a boolean option that you want
324 to set `true`; it's effectively a shortcut for `foo=true`).
325
326 - `sequences` (default: true) -- join consecutive simple statements using the
327   comma operator.  May be set to a positive integer to specify the maximum number
328   of consecutive comma sequences that will be generated. If this option is set to
329   `true` then the default `sequences` limit is `200`. Set option to `false` or `0`
330   to disable. The smallest `sequences` length is `2`. A `sequences` value of `1`
331   is grandfathered to be equivalent to `true` and as such means `200`. On rare
332   occasions the default sequences limit leads to very slow compress times in which
333   case a value of `20` or less is recommended.
334
335 - `properties` -- rewrite property access using the dot notation, for
336   example `foo["bar"] → foo.bar`
337
338 - `dead_code` -- remove unreachable code
339
340 - `drop_debugger` -- remove `debugger;` statements
341
342 - `unsafe` (default: false) -- apply "unsafe" transformations (discussion below)
343
344 - `unsafe_comps` (default: false) -- Reverse `<` and `<=` to `>` and `>=` to
345   allow improved compression. This might be unsafe when an at least one of two
346   operands is an object with computed values due the use of methods like `get`,
347   or `valueOf`. This could cause change in execution order after operands in the
348   comparison are switching. Compression only works if both `comparisons` and
349   `unsafe_comps` are both set to true.
350
351 - `unsafe_math` (default: false) -- optimize numerical expressions like
352   `2 * x * 3` into `6 * x`, which may give imprecise floating point results.
353
354 - `unsafe_proto` (default: false) -- optimize expressions like
355   `Array.prototype.slice.call(a)` into `[].slice.call(a)`
356
357 - `conditionals` -- apply optimizations for `if`-s and conditional
358   expressions
359
360 - `comparisons` -- apply certain optimizations to binary nodes, for example:
361   `!(a <= b) → a > b` (only when `unsafe_comps`), attempts to negate binary
362   nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc.
363
364 - `evaluate` -- attempt to evaluate constant expressions
365
366 - `booleans` -- various optimizations for boolean context, for example `!!a
367   ? b : c → a ? b : c`
368
369 - `loops` -- optimizations for `do`, `while` and `for` loops when we can
370   statically determine the condition
371
372 - `unused` -- drop unreferenced functions and variables (simple direct variable
373   assignments do not count as references unless set to `"keep_assign"`)
374
375 - `toplevel` -- drop unreferenced functions (`"funcs"`) and/or variables (`"vars"`)
376   in the toplevel scope (`false` by default, `true` to drop both unreferenced
377   functions and variables)
378
379 - `top_retain` -- prevent specific toplevel functions and variables from `unused`
380   removal (can be array, comma-separated, RegExp or function. Implies `toplevel`)
381
382 - `hoist_funs` -- hoist function declarations
383
384 - `hoist_vars` (default: false) -- hoist `var` declarations (this is `false`
385   by default because it seems to increase the size of the output in general)
386
387 - `if_return` -- optimizations for if/return and if/continue
388
389 - `join_vars` -- join consecutive `var` statements
390
391 - `cascade` -- small optimization for sequences, transform `x, x` into `x`
392   and `x = something(), x` into `x = something()`
393
394 - `collapse_vars` -- default `false`. Collapse single-use `var` and `const`
395   definitions when possible.
396
397 - `reduce_vars` -- default `false`. Improve optimization on variables assigned
398   with and used as constant values.
399
400 - `warnings` -- display warnings when dropping unreachable code or unused
401   declarations etc.
402
403 - `negate_iife` -- negate "Immediately-Called Function Expressions"
404   where the return value is discarded, to avoid the parens that the
405   code generator would insert.
406
407 - `pure_getters` -- the default is `false`.  If you pass `true` for
408   this, UglifyJS will assume that object property access
409   (e.g. `foo.bar` or `foo["bar"]`) doesn't have any side effects.
410
411 - `pure_funcs` -- default `null`.  You can pass an array of names and
412   UglifyJS will assume that those functions do not produce side
413   effects.  DANGER: will not check if the name is redefined in scope.
414   An example case here, for instance `var q = Math.floor(a/b)`.  If
415   variable `q` is not used elsewhere, UglifyJS will drop it, but will
416   still keep the `Math.floor(a/b)`, not knowing what it does.  You can
417   pass `pure_funcs: [ 'Math.floor' ]` to let it know that this
418   function won't produce any side effect, in which case the whole
419   statement would get discarded.  The current implementation adds some
420   overhead (compression will be slower).
421
422 - `drop_console` -- default `false`.  Pass `true` to discard calls to
423   `console.*` functions. If you wish to drop a specific function call
424   such as `console.info` and/or retain side effects from function arguments
425   after dropping the function call then use `pure_funcs` instead.
426
427 - `expression` -- default `false`.  Pass `true` to preserve completion values
428   from terminal statements without `return`, e.g. in bookmarklets.
429
430 - `keep_fargs` -- default `true`.  Prevents the
431   compressor from discarding unused function arguments.  You need this
432   for code which relies on `Function.length`.
433
434 - `keep_fnames` -- default `false`.  Pass `true` to prevent the
435   compressor from discarding function names.  Useful for code relying on
436   `Function.prototype.name`. See also: the `keep_fnames` [mangle option](#mangle).
437
438 - `passes` -- default `1`. Number of times to run compress. Use an
439   integer argument larger than 1 to further reduce code size in some cases.
440   Note: raising the number of passes will increase uglify compress time.
441
442 ### The `unsafe` option
443
444 It enables some transformations that *might* break code logic in certain
445 contrived cases, but should be fine for most code.  You might want to try it
446 on your own code, it should reduce the minified size.  Here's what happens
447 when this flag is on:
448
449 - `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[ 1, 2, 3 ]`
450 - `new Object()` → `{}`
451 - `String(exp)` or `exp.toString()` → `"" + exp`
452 - `new Object/RegExp/Function/Error/Array (...)` → we discard the `new`
453 - `typeof foo == "undefined"` → `foo === void 0`
454 - `void 0` → `undefined` (if there is a variable named "undefined" in
455   scope; we do it because the variable name will be mangled, typically
456   reduced to a single character)
457
458 ### Conditional compilation
459
460 You can use the `--define` (`-d`) switch in order to declare global
461 variables that UglifyJS will assume to be constants (unless defined in
462 scope).  For example if you pass `--define DEBUG=false` then, coupled with
463 dead code removal UglifyJS will discard the following from the output:
464 ```javascript
465 if (DEBUG) {
466         console.log("debug stuff");
467 }
468 ```
469
470 You can specify nested constants in the form of `--define env.DEBUG=false`.
471
472 UglifyJS will warn about the condition being always false and about dropping
473 unreachable code; for now there is no option to turn off only this specific
474 warning, you can pass `warnings=false` to turn off *all* warnings.
475
476 Another way of doing that is to declare your globals as constants in a
477 separate file and include it into the build.  For example you can have a
478 `build/defines.js` file with the following:
479 ```javascript
480 const DEBUG = false;
481 const PRODUCTION = true;
482 // etc.
483 ```
484
485 and build your code like this:
486
487     uglifyjs build/defines.js js/foo.js js/bar.js... -c
488
489 UglifyJS will notice the constants and, since they cannot be altered, it
490 will evaluate references to them to the value itself and drop unreachable
491 code as usual.  The build will contain the `const` declarations if you use
492 them. If you are targeting < ES6 environments which does not support `const`,
493 using `var` with `reduce_vars` (enabled by default) should suffice.
494
495 <a name="codegen-options"></a>
496
497 #### Conditional compilation, API
498 You can also use conditional compilation via the programmatic API. With the difference that the
499 property name is `global_defs` and is a compressor property:
500
501 ```js
502 uglifyJS.minify([ "input.js"], {
503     compress: {
504         dead_code: true,
505         global_defs: {
506             DEBUG: false
507         }
508     }
509 });
510 ```
511
512 ## Beautifier options
513
514 The code generator tries to output shortest code possible by default.  In
515 case you want beautified output, pass `--beautify` (`-b`).  Optionally you
516 can pass additional arguments that control the code output:
517
518 - `beautify` (default `true`) -- whether to actually beautify the output.
519   Passing `-b` will set this to true, but you might need to pass `-b` even
520   when you want to generate minified code, in order to specify additional
521   arguments, so you can use `-b beautify=false` to override it.
522 - `indent-level` (default 4)
523 - `indent-start` (default 0) -- prefix all lines by that many spaces
524 - `quote-keys` (default `false`) -- pass `true` to quote all keys in literal
525   objects
526 - `space-colon` (default `true`) -- insert a space after the colon signs
527 - `ascii-only` (default `false`) -- escape Unicode characters in strings and
528   regexps (affects directives with non-ascii characters becoming invalid)
529 - `inline-script` (default `false`) -- escape the slash in occurrences of
530   `</script` in strings
531 - `width` (default 80) -- only takes effect when beautification is on, this
532   specifies an (orientative) line width that the beautifier will try to
533   obey.  It refers to the width of the line text (excluding indentation).
534   It doesn't work very well currently, but it does make the code generated
535   by UglifyJS more readable.
536 - `max-line-len` (default 32000) -- maximum line length (for uglified code)
537 - `bracketize` (default `false`) -- always insert brackets in `if`, `for`,
538   `do`, `while` or `with` statements, even if their body is a single
539   statement.
540 - `semicolons` (default `true`) -- separate statements with semicolons.  If
541   you pass `false` then whenever possible we will use a newline instead of a
542   semicolon, leading to more readable output of uglified code (size before
543   gzip could be smaller; size after gzip insignificantly larger).
544 - `preamble` (default `null`) -- when passed it must be a string and
545   it will be prepended to the output literally.  The source map will
546   adjust for this text.  Can be used to insert a comment containing
547   licensing information, for example.
548 - `quote_style` (default `0`) -- preferred quote style for strings (affects
549   quoted property names and directives as well):
550   - `0` -- prefers double quotes, switches to single quotes when there are
551     more double quotes in the string itself.
552   - `1` -- always use single quotes
553   - `2` -- always use double quotes
554   - `3` -- always use the original quotes
555 - `keep_quoted_props` (default `false`) -- when turned on, prevents stripping
556   quotes from property names in object literals.
557
558 ### Keeping copyright notices or other comments
559
560 You can pass `--comments` to retain certain comments in the output.  By
561 default it will keep JSDoc-style comments that contain "@preserve",
562 "@license" or "@cc_on" (conditional compilation for IE).  You can pass
563 `--comments all` to keep all the comments, or a valid JavaScript regexp to
564 keep only comments that match this regexp.  For example `--comments
565 '/foo|bar/'` will keep only comments that contain "foo" or "bar".
566
567 Note, however, that there might be situations where comments are lost.  For
568 example:
569 ```javascript
570 function f() {
571         /** @preserve Foo Bar */
572         function g() {
573           // this function is never called
574         }
575         return something();
576 }
577 ```
578
579 Even though it has "@preserve", the comment will be lost because the inner
580 function `g` (which is the AST node to which the comment is attached to) is
581 discarded by the compressor as not referenced.
582
583 The safest comments where to place copyright information (or other info that
584 needs to be kept in the output) are comments attached to toplevel nodes.
585
586 ## Support for the SpiderMonkey AST
587
588 UglifyJS2 has its own abstract syntax tree format; for
589 [practical reasons](http://lisperator.net/blog/uglifyjs-why-not-switching-to-spidermonkey-ast/)
590 we can't easily change to using the SpiderMonkey AST internally.  However,
591 UglifyJS now has a converter which can import a SpiderMonkey AST.
592
593 For example [Acorn][acorn] is a super-fast parser that produces a
594 SpiderMonkey AST.  It has a small CLI utility that parses one file and dumps
595 the AST in JSON on the standard output.  To use UglifyJS to mangle and
596 compress that:
597
598     acorn file.js | uglifyjs --spidermonkey -m -c
599
600 The `--spidermonkey` option tells UglifyJS that all input files are not
601 JavaScript, but JS code described in SpiderMonkey AST in JSON.  Therefore we
602 don't use our own parser in this case, but just transform that AST into our
603 internal AST.
604
605 ### Use Acorn for parsing
606
607 More for fun, I added the `--acorn` option which will use Acorn to do all
608 the parsing.  If you pass this option, UglifyJS will `require("acorn")`.
609
610 Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but
611 converting the SpiderMonkey tree that Acorn produces takes another 150ms so
612 in total it's a bit more than just using UglifyJS's own parser.
613
614 ### Using UglifyJS to transform SpiderMonkey AST
615
616 Now you can use UglifyJS as any other intermediate tool for transforming
617 JavaScript ASTs in SpiderMonkey format.
618
619 Example:
620
621 ```javascript
622 function uglify(ast, options, mangle) {
623   // Conversion from SpiderMonkey AST to internal format
624   var uAST = UglifyJS.AST_Node.from_mozilla_ast(ast);
625
626   // Compression
627   uAST.figure_out_scope();
628   uAST = UglifyJS.Compressor(options).compress(uAST);
629
630   // Mangling (optional)
631   if (mangle) {
632     uAST.figure_out_scope();
633     uAST.compute_char_frequency();
634     uAST.mangle_names();
635   }
636
637   // Back-conversion to SpiderMonkey AST
638   return uAST.to_mozilla_ast();
639 }
640 ```
641
642 Check out
643 [original blog post](http://rreverser.com/using-mozilla-ast-with-uglifyjs/)
644 for details.
645
646 API Reference
647 -------------
648
649 Assuming installation via NPM, you can load UglifyJS in your application
650 like this:
651 ```javascript
652 var UglifyJS = require("uglify-js");
653 ```
654
655 It exports a lot of names, but I'll discuss here the basics that are needed
656 for parsing, mangling and compressing a piece of code.  The sequence is (1)
657 parse, (2) compress, (3) mangle, (4) generate output code.
658
659 ### The simple way
660
661 There's a single toplevel function which combines all the steps.  If you
662 don't need additional customization, you might want to go with `minify`.
663 Example:
664 ```javascript
665 var result = UglifyJS.minify("/path/to/file.js");
666 console.log(result.code); // minified output
667 // if you need to pass code instead of file name
668 var result = UglifyJS.minify("var b = function () {};", {fromString: true});
669 ```
670
671 You can also compress multiple files:
672 ```javascript
673 var result = UglifyJS.minify([ "file1.js", "file2.js", "file3.js" ]);
674 console.log(result.code);
675 ```
676
677 To generate a source map:
678 ```javascript
679 var result = UglifyJS.minify([ "file1.js", "file2.js", "file3.js" ], {
680         outSourceMap: "out.js.map"
681 });
682 console.log(result.code); // minified output
683 console.log(result.map);
684 ```
685
686 To generate a source map with the fromString option, you can also use an object:
687 ```javascript
688 var result = UglifyJS.minify({"file1.js": "var a = function () {};"}, {
689   outSourceMap: "out.js.map",
690   outFileName: "out.js",
691   fromString: true
692 });
693 ```
694
695 Note that the source map is not saved in a file, it's just returned in
696 `result.map`.  The value passed for `outSourceMap` is only used to set
697 `//# sourceMappingURL=out.js.map` in `result.code`. The value of
698 `outFileName` is only used to set `file` attribute in source map file.
699
700 The `file` attribute in the source map (see [the spec][sm-spec]) will
701 use `outFileName` firstly, if it's falsy, then will be deduced from
702 `outSourceMap` (by removing `'.map'`).
703
704 You can set option `sourceMapInline` to be `true` and source map will
705 be appended to code.
706
707 You can also specify sourceRoot property to be included in source map:
708 ```javascript
709 var result = UglifyJS.minify([ "file1.js", "file2.js", "file3.js" ], {
710         outSourceMap: "out.js.map",
711         sourceRoot: "http://example.com/src"
712 });
713 ```
714
715 If you're compressing compiled JavaScript and have a source map for it, you
716 can use the `inSourceMap` argument:
717 ```javascript
718 var result = UglifyJS.minify("compiled.js", {
719         inSourceMap: "compiled.js.map",
720         outSourceMap: "minified.js.map"
721 });
722 // same as before, it returns `code` and `map`
723 ```
724
725 If your input source map is not in a file, you can pass it in as an object
726 using the `inSourceMap` argument:
727
728 ```javascript
729 var result = UglifyJS.minify("compiled.js", {
730         inSourceMap: JSON.parse(my_source_map_string),
731         outSourceMap: "minified.js.map"
732 });
733 ```
734
735 The `inSourceMap` is only used if you also request `outSourceMap` (it makes
736 no sense otherwise).
737
738 To set the source map url, use the `sourceMapUrl` option.
739 If you're using the X-SourceMap header instead, you can just set the `sourceMapUrl` option to false.
740 Defaults to outSourceMap:
741
742 ```javascript
743 var result = UglifyJS.minify([ "file1.js" ], {
744   outSourceMap: "out.js.map",
745   sourceMapUrl: "localhost/out.js.map"
746 });
747 ```
748
749 Other options:
750
751 - `warnings` (default `false`) — pass `true` to display compressor warnings.
752
753 - `fromString` (default `false`) — if you pass `true` then you can pass
754   JavaScript source code, rather than file names.
755
756 - `mangle` (default `true`) — pass `false` to skip mangling names, or pass
757   an object to specify mangling options (see below).
758
759 - `mangleProperties` (default `false`) — pass an object to specify custom
760   mangle property options.
761
762 - `output` (default `null`) — pass an object if you wish to specify
763   additional [output options][codegen].  The defaults are optimized
764   for best compression.
765
766 - `compress` (default `{}`) — pass `false` to skip compressing entirely.
767   Pass an object to specify custom [compressor options][compressor].
768
769 - `parse` (default {}) — pass an object if you wish to specify some
770   additional [parser options][parser]. (not all options available... see below)
771
772 ##### mangle
773
774  - `except` - pass an array of identifiers that should be excluded from mangling
775
776  - `toplevel` — mangle names declared in the toplevel scope (disabled by
777   default).
778
779  - `eval` — mangle names visible in scopes where eval or with are used
780   (disabled by default).
781
782  - `keep_fnames` -- default `false`.  Pass `true` to not mangle
783   function names.  Useful for code relying on `Function.prototype.name`.
784   See also: the `keep_fnames` [compress option](#compressor-options).
785
786   Examples:
787
788   ```javascript
789   //tst.js
790   var globalVar;
791   function funcName(firstLongName, anotherLongName)
792   {
793     var myVariable = firstLongName +  anotherLongName;
794   }
795
796   UglifyJS.minify("tst.js").code;
797   // 'function funcName(a,n){}var globalVar;'
798
799   UglifyJS.minify("tst.js", { mangle: { except: ['firstLongName'] } }).code;
800   // 'function funcName(firstLongName,a){}var globalVar;'
801
802   UglifyJS.minify("tst.js", { mangle: { toplevel: true } }).code;
803   // 'function n(n,a){}var a;'
804   ```
805
806 ##### mangleProperties options
807
808  - `regex` — Pass a RegExp to only mangle certain names (maps to the `--mangle-regex` CLI arguments option)
809  - `ignore_quoted` – Only mangle unquoted property names (maps to the `--mangle-props 2` CLI arguments option)
810  - `debug` – Mangle names with the original name still present (maps to the `--mangle-props-debug` CLI arguments option). Defaults to `false`. Pass an empty string to enable, or a non-empty string to set the suffix.
811
812 We could add more options to `UglifyJS.minify` — if you need additional
813 functionality please suggest!
814
815 ### The hard way
816
817 Following there's more detailed API info, in case the `minify` function is
818 too simple for your needs.
819
820 #### The parser
821 ```javascript
822 var toplevel_ast = UglifyJS.parse(code, options);
823 ```
824
825 `options` is optional and if present it must be an object.  The following
826 properties are available:
827
828 - `strict` — disable automatic semicolon insertion and support for trailing
829   comma in arrays and objects
830 - `bare_returns` — Allow return outside of functions. (maps to the
831   `--bare-returns` CLI arguments option and available to `minify` `parse`
832   other options object)
833 - `filename` — the name of the file where this code is coming from
834 - `toplevel` — a `toplevel` node (as returned by a previous invocation of
835   `parse`)
836
837 The last two options are useful when you'd like to minify multiple files and
838 get a single file as the output and a proper source map.  Our CLI tool does
839 something like this:
840 ```javascript
841 var toplevel = null;
842 files.forEach(function(file){
843         var code = fs.readFileSync(file, "utf8");
844         toplevel = UglifyJS.parse(code, {
845                 filename: file,
846                 toplevel: toplevel
847         });
848 });
849 ```
850
851 After this, we have in `toplevel` a big AST containing all our files, with
852 each token having proper information about where it came from.
853
854 #### Scope information
855
856 UglifyJS contains a scope analyzer that you need to call manually before
857 compressing or mangling.  Basically it augments various nodes in the AST
858 with information about where is a name defined, how many times is a name
859 referenced, if it is a global or not, if a function is using `eval` or the
860 `with` statement etc.  I will discuss this some place else, for now what's
861 important to know is that you need to call the following before doing
862 anything with the tree:
863 ```javascript
864 toplevel.figure_out_scope()
865 ```
866
867 #### Compression
868
869 Like this:
870 ```javascript
871 var compressor = UglifyJS.Compressor(options);
872 var compressed_ast = compressor.compress(toplevel);
873 ```
874
875 The `options` can be missing.  Available options are discussed above in
876 “Compressor options”.  Defaults should lead to best compression in most
877 scripts.
878
879 The compressor is destructive, so don't rely that `toplevel` remains the
880 original tree.
881
882 #### Mangling
883
884 After compression it is a good idea to call again `figure_out_scope` (since
885 the compressor might drop unused variables / unreachable code and this might
886 change the number of identifiers or their position).  Optionally, you can
887 call a trick that helps after Gzip (counting character frequency in
888 non-mangleable words).  Example:
889 ```javascript
890 compressed_ast.figure_out_scope();
891 compressed_ast.compute_char_frequency();
892 compressed_ast.mangle_names();
893 ```
894
895 #### Generating output
896
897 AST nodes have a `print` method that takes an output stream.  Essentially,
898 to generate code you do this:
899 ```javascript
900 var stream = UglifyJS.OutputStream(options);
901 compressed_ast.print(stream);
902 var code = stream.toString(); // this is your minified code
903 ```
904
905 or, for a shortcut you can do:
906 ```javascript
907 var code = compressed_ast.print_to_string(options);
908 ```
909
910 As usual, `options` is optional.  The output stream accepts a lot of options,
911 most of them documented above in section “Beautifier options”.  The two
912 which we care about here are `source_map` and `comments`.
913
914 #### Keeping comments in the output
915
916 In order to keep certain comments in the output you need to pass the
917 `comments` option.  Pass a RegExp (as string starting and closing with `/`
918 or pass a RegExp object), a boolean or a function.  Stringified options
919 `all` and `some` can be passed too, where `some` behaves like it's cli
920 equivalent `--comments` without passing a value. If you pass a RegExp,
921 only those comments whose body matches the RegExp will be kept.  Note that body
922 means without the initial `//` or `/*`.  If you pass a function, it will be
923 called for every comment in the tree and will receive two arguments: the
924 node that the comment is attached to, and the comment token itself.
925
926 The comment token has these properties:
927
928 - `type`: "comment1" for single-line comments or "comment2" for multi-line
929   comments
930 - `value`: the comment body
931 - `pos` and `endpos`: the start/end positions (zero-based indexes) in the
932   original code where this comment appears
933 - `line` and `col`: the line and column where this comment appears in the
934   original code
935 - `file` — the file name of the original file
936 - `nlb` — true if there was a newline before this comment in the original
937   code, or if this comment contains a newline.
938
939 Your function should return `true` to keep the comment, or a falsy value
940 otherwise.
941
942 #### Generating a source mapping
943
944 You need to pass the `source_map` argument when calling `print`.  It needs
945 to be a `SourceMap` object (which is a thin wrapper on top of the
946 [source-map][source-map] library).
947
948 Example:
949 ```javascript
950 var source_map = UglifyJS.SourceMap(source_map_options);
951 var stream = UglifyJS.OutputStream({
952         ...
953         source_map: source_map
954 });
955 compressed_ast.print(stream);
956
957 var code = stream.toString();
958 var map = source_map.toString(); // json output for your source map
959 ```
960
961 The `source_map_options` (optional) can contain the following properties:
962
963 - `file`: the name of the JavaScript output file that this mapping refers to
964 - `root`: the `sourceRoot` property (see the [spec][sm-spec])
965 - `orig`: the "original source map", handy when you compress generated JS
966   and want to map the minified output back to the original code where it
967   came from.  It can be simply a string in JSON, or a JSON object containing
968   the original source map.
969
970   [acorn]: https://github.com/ternjs/acorn
971   [source-map]: https://github.com/mozilla/source-map
972   [sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
973   [codegen]: http://lisperator.net/uglifyjs/codegen
974   [compressor]: http://lisperator.net/uglifyjs/compress
975   [parser]: http://lisperator.net/uglifyjs/parser
976
977 #### Harmony
978
979 If you wish to use the experimental [harmony](https://github.com/mishoo/UglifyJS2/commits/harmony)
980 branch to minify ES2015+ (ES6+) code please use the following in your `package.json` file:
981
982 ```
983 "uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
984 ```
985
986 or to directly install the experimental harmony version of uglify:
987
988 ```
989 npm install --save-dev uglify-js@github:mishoo/UglifyJS2#harmony
990 ```
991
992 See [#448](https://github.com/mishoo/UglifyJS2/issues/448) for additional details.