You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 46KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. UglifyJS 3
  2. ==========
  3. UglifyJS is a JavaScript parser, minifier, compressor and beautifier toolkit.
  4. #### Note:
  5. - **`uglify-js@3` has a simplified [API](#api-reference) and [CLI](#command-line-usage) that is not backwards compatible with [`uglify-js@2`](https://github.com/mishoo/UglifyJS/tree/v2.x)**.
  6. - **Documentation for UglifyJS `2.x` releases can be found [here](https://github.com/mishoo/UglifyJS/tree/v2.x)**.
  7. - `uglify-js` only supports JavaScript (ECMAScript 5).
  8. - To minify ECMAScript 2015 or above, transpile using tools like [Babel](https://babeljs.io/).
  9. Install
  10. -------
  11. First make sure you have installed the latest version of [node.js](http://nodejs.org/)
  12. (You may need to restart your computer after this step).
  13. From NPM for use as a command line app:
  14. npm install uglify-js -g
  15. From NPM for programmatic use:
  16. npm install uglify-js
  17. # Command line usage
  18. uglifyjs [input files] [options]
  19. UglifyJS can take multiple input files. It's recommended that you pass the
  20. input files first, then pass the options. UglifyJS will parse input files
  21. in sequence and apply any compression options. The files are parsed in the
  22. same global scope, that is, a reference from a file to some
  23. variable/function declared in another file will be matched properly.
  24. If no input file is specified, UglifyJS will read from STDIN.
  25. If you wish to pass your options before the input files, separate the two with
  26. a double dash to prevent input files being used as option arguments:
  27. uglifyjs --compress --mangle -- input.js
  28. ### Command line options
  29. ```
  30. -h, --help Print usage information.
  31. `--help options` for details on available options.
  32. -V, --version Print version number.
  33. -p, --parse <options> Specify parser options:
  34. `acorn` Use Acorn for parsing.
  35. `bare_returns` Allow return outside of functions.
  36. Useful when minifying CommonJS
  37. modules and Userscripts that may
  38. be anonymous function wrapped (IIFE)
  39. by the .user.js engine `caller`.
  40. `expression` Parse a single expression, rather than
  41. a program (for parsing JSON).
  42. `spidermonkey` Assume input files are SpiderMonkey
  43. AST format (as JSON).
  44. -c, --compress [options] Enable compressor/specify compressor options:
  45. `pure_funcs` List of functions that can be safely
  46. removed when their return values are
  47. not used.
  48. -m, --mangle [options] Mangle names/specify mangler options:
  49. `reserved` List of names that should not be mangled.
  50. --mangle-props [options] Mangle properties/specify mangler options:
  51. `builtins` Mangle property names that overlaps
  52. with standard JavaScript globals.
  53. `debug` Add debug prefix and suffix.
  54. `domprops` Mangle property names that overlaps
  55. with DOM properties.
  56. `keep_quoted` Only mangle unquoted properties.
  57. `regex` Only mangle matched property names.
  58. `reserved` List of names that should not be mangled.
  59. -b, --beautify [options] Beautify output/specify output options:
  60. `beautify` Enabled with `--beautify` by default.
  61. `preamble` Preamble to prepend to the output. You
  62. can use this to insert a comment, for
  63. example for licensing information.
  64. This will not be parsed, but the source
  65. map will adjust for its presence.
  66. `quote_style` Quote style:
  67. 0 - auto
  68. 1 - single
  69. 2 - double
  70. 3 - original
  71. `wrap_iife` Wrap IIFEs in parenthesis. Note: you may
  72. want to disable `negate_iife` under
  73. compressor options.
  74. -O, --output-opts [options] Specify output options (`beautify` disabled by default).
  75. -o, --output <file> Output file path (default STDOUT). Specify `ast` or
  76. `spidermonkey` to write UglifyJS or SpiderMonkey AST
  77. as JSON to STDOUT respectively.
  78. --comments [filter] Preserve copyright comments in the output. By
  79. default this works like Google Closure, keeping
  80. JSDoc-style comments that contain "@license" or
  81. "@preserve". You can optionally pass one of the
  82. following arguments to this flag:
  83. - "all" to keep all comments
  84. - a valid JS RegExp like `/foo/` or `/^!/` to
  85. keep only matching comments.
  86. Note that currently not *all* comments can be
  87. kept when compression is on, because of dead
  88. code removal or cascading statements into
  89. sequences.
  90. --config-file <file> Read `minify()` options from JSON file.
  91. -d, --define <expr>[=value] Global definitions.
  92. -e, --enclose [arg[:value]] Embed everything in a big function, with configurable
  93. argument(s) & value(s).
  94. --ie8 Support non-standard Internet Explorer 8.
  95. Equivalent to setting `ie8: true` in `minify()`
  96. for `compress`, `mangle` and `output` options.
  97. By default UglifyJS will not try to be IE-proof.
  98. --keep-fnames Do not mangle/drop function names. Useful for
  99. code relying on Function.prototype.name.
  100. --name-cache <file> File to hold mangled name mappings.
  101. --self Build UglifyJS as a library (implies --wrap UglifyJS)
  102. --source-map [options] Enable source map/specify source map options:
  103. `base` Path to compute relative paths from input files.
  104. `content` Input source map, useful if you're compressing
  105. JS that was generated from some other original
  106. code. Specify "inline" if the source map is
  107. included within the sources.
  108. `filename` Filename and/or location of the output source
  109. (sets `file` attribute in source map).
  110. `includeSources` Pass this flag if you want to include
  111. the content of source files in the
  112. source map as sourcesContent property.
  113. `names` Include symbol names in the source map.
  114. `root` Path to the original source to be included in
  115. the source map.
  116. `url` If specified, path to the source map to append in
  117. `//# sourceMappingURL`.
  118. --timings Display operations run time on STDERR.
  119. --toplevel Compress and/or mangle variables in top level scope.
  120. --verbose Print diagnostic messages.
  121. --warn Print warning messages.
  122. --wrap <name> Embed everything in a big function, making the
  123. “exports” and “global” variables available. You
  124. need to pass an argument to this option to
  125. specify the name that your module will take
  126. when included in, say, a browser.
  127. ```
  128. Specify `--output` (`-o`) to declare the output file. Otherwise the output
  129. goes to STDOUT.
  130. ## CLI source map options
  131. UglifyJS can generate a source map file, which is highly useful for
  132. debugging your compressed JavaScript. To get a source map, pass
  133. `--source-map --output output.js` (source map will be written out to
  134. `output.js.map`).
  135. Additional options:
  136. - `--source-map "filename='<NAME>'"` to specify the name of the source map. The value of
  137. `filename` is only used to set `file` attribute (see [the spec][sm-spec])
  138. in source map file.
  139. - `--source-map "root='<URL>'"` to pass the URL where the original files can be found.
  140. - `--source-map "names=false"` to omit symbol names if you want to reduce size
  141. of the source map file.
  142. - `--source-map "url='<URL>'"` to specify the URL where the source map can be found.
  143. Otherwise UglifyJS assumes HTTP `X-SourceMap` is being used and will omit the
  144. `//# sourceMappingURL=` directive.
  145. For example:
  146. uglifyjs js/file1.js js/file2.js \
  147. -o foo.min.js -c -m \
  148. --source-map "root='http://foo.com/src',url='foo.min.js.map'"
  149. The above will compress and mangle `file1.js` and `file2.js`, will drop the
  150. output in `foo.min.js` and the source map in `foo.min.js.map`. The source
  151. mapping will refer to `http://foo.com/src/js/file1.js` and
  152. `http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src`
  153. as the source map root, and the original files as `js/file1.js` and
  154. `js/file2.js`).
  155. ### Composed source map
  156. When you're compressing JS code that was output by a compiler such as
  157. CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd
  158. like to map back to the original code (i.e. CoffeeScript). UglifyJS has an
  159. option to take an input source map. Assuming you have a mapping from
  160. CoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript →
  161. compressed JS by mapping every token in the compiled JS to its original
  162. location.
  163. To use this feature pass `--source-map "content='/path/to/input/source.map'"`
  164. or `--source-map "content=inline"` if the source map is included inline with
  165. the sources.
  166. ## CLI compress options
  167. You need to pass `--compress` (`-c`) to enable the compressor. Optionally
  168. you can pass a comma-separated list of [compress options](#compress-options).
  169. Options are in the form `foo=bar`, or just `foo` (the latter implies
  170. a boolean option that you want to set `true`; it's effectively a
  171. shortcut for `foo=true`).
  172. Example:
  173. uglifyjs file.js -c toplevel,sequences=false
  174. ## CLI mangle options
  175. To enable the mangler you need to pass `--mangle` (`-m`). The following
  176. (comma-separated) options are supported:
  177. - `toplevel` (default `false`) -- mangle names declared in the top level scope.
  178. - `eval` (default `false`) -- mangle names visible in scopes where `eval` or `with` are used.
  179. When mangling is enabled but you want to prevent certain names from being
  180. mangled, you can declare those names with `--mangle reserved` — pass a
  181. comma-separated list of names. For example:
  182. uglifyjs ... -m reserved=['$','require','exports']
  183. to prevent the `require`, `exports` and `$` names from being changed.
  184. ### CLI mangling property names (`--mangle-props`)
  185. **Note:** THIS WILL PROBABLY BREAK YOUR CODE. Mangling property names
  186. is a separate step, different from variable name mangling. Pass
  187. `--mangle-props` to enable it. It will mangle all properties in the
  188. input code with the exception of built in DOM properties and properties
  189. in core JavaScript classes. For example:
  190. ```javascript
  191. // example.js
  192. var x = {
  193. baz_: 0,
  194. foo_: 1,
  195. calc: function() {
  196. return this.foo_ + this.baz_;
  197. }
  198. };
  199. x.bar_ = 2;
  200. x["baz_"] = 3;
  201. console.log(x.calc());
  202. ```
  203. Mangle all properties (except for JavaScript `builtins`):
  204. ```bash
  205. $ uglifyjs example.js -c -m --mangle-props
  206. ```
  207. ```javascript
  208. var x={o:0,_:1,l:function(){return this._+this.o}};x.t=2,x.o=3,console.log(x.l());
  209. ```
  210. Mangle all properties except for `reserved` properties:
  211. ```bash
  212. $ uglifyjs example.js -c -m --mangle-props reserved=[foo_,bar_]
  213. ```
  214. ```javascript
  215. var x={o:0,foo_:1,_:function(){return this.foo_+this.o}};x.bar_=2,x.o=3,console.log(x._());
  216. ```
  217. Mangle all properties matching a `regex`:
  218. ```bash
  219. $ uglifyjs example.js -c -m --mangle-props regex=/_$/
  220. ```
  221. ```javascript
  222. var x={o:0,_:1,calc:function(){return this._+this.o}};x.l=2,x.o=3,console.log(x.calc());
  223. ```
  224. Combining mangle properties options:
  225. ```bash
  226. $ uglifyjs example.js -c -m --mangle-props regex=/_$/,reserved=[bar_]
  227. ```
  228. ```javascript
  229. var x={o:0,_:1,calc:function(){return this._+this.o}};x.bar_=2,x.o=3,console.log(x.calc());
  230. ```
  231. In order for this to be of any use, we avoid mangling standard JS names by
  232. default (`--mangle-props builtins` to override).
  233. A default exclusion file is provided in `tools/domprops.json` which should
  234. cover most standard JS and DOM properties defined in various browsers. Pass
  235. `--mangle-props domprops` to disable this feature.
  236. A regular expression can be used to define which property names should be
  237. mangled. For example, `--mangle-props regex=/^_/` will only mangle property
  238. names that start with an underscore.
  239. When you compress multiple files using this option, in order for them to
  240. work together in the end we need to ensure somehow that one property gets
  241. mangled to the same name in all of them. For this, pass `--name-cache filename.json`
  242. and UglifyJS will maintain these mappings in a file which can then be reused.
  243. It should be initially empty. Example:
  244. ```bash
  245. $ rm -f /tmp/cache.json # start fresh
  246. $ uglifyjs file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js
  247. $ uglifyjs file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js
  248. ```
  249. Now, `part1.js` and `part2.js` will be consistent with each other in terms
  250. of mangled property names.
  251. Using the name cache is not necessary if you compress all your files in a
  252. single call to UglifyJS.
  253. ### Mangling unquoted names (`--mangle-props keep_quoted`)
  254. Using quoted property name (`o["foo"]`) reserves the property name (`foo`)
  255. so that it is not mangled throughout the entire script even when used in an
  256. unquoted style (`o.foo`). Example:
  257. ```javascript
  258. // stuff.js
  259. var o = {
  260. "foo": 1,
  261. bar: 3
  262. };
  263. o.foo += o.bar;
  264. console.log(o.foo);
  265. ```
  266. ```bash
  267. $ uglifyjs stuff.js --mangle-props keep_quoted -c -m
  268. ```
  269. ```javascript
  270. var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo);
  271. ```
  272. ### Debugging property name mangling
  273. You can also pass `--mangle-props debug` in order to mangle property names
  274. without completely obscuring them. For example the property `o.foo`
  275. would mangle to `o._$foo$_` with this option. This allows property mangling
  276. of a large codebase while still being able to debug the code and identify
  277. where mangling is breaking things.
  278. ```bash
  279. $ uglifyjs stuff.js --mangle-props debug -c -m
  280. ```
  281. ```javascript
  282. var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_);
  283. ```
  284. You can also pass a custom suffix using `--mangle-props debug=XYZ`. This would then
  285. mangle `o.foo` to `o._$foo$XYZ_`. You can change this each time you compile a
  286. script to identify how a property got mangled. One technique is to pass a
  287. random number on every compile to simulate mangling changing with different
  288. inputs (e.g. as you update the input script with new properties), and to help
  289. identify mistakes like writing mangled keys to storage.
  290. # API Reference
  291. Assuming installation via NPM, you can load UglifyJS in your application
  292. like this:
  293. ```javascript
  294. var UglifyJS = require("uglify-js");
  295. ```
  296. There is a single high level function, **`minify(code, options)`**,
  297. which will perform all minification [phases](#minify-options) in a configurable
  298. manner. By default `minify()` will enable the options [`compress`](#compress-options)
  299. and [`mangle`](#mangle-options). Example:
  300. ```javascript
  301. var code = "function add(first, second) { return first + second; }";
  302. var result = UglifyJS.minify(code);
  303. console.log(result.error); // runtime error, or `undefined` if no error
  304. console.log(result.code); // minified output: function add(n,d){return n+d}
  305. ```
  306. You can `minify` more than one JavaScript file at a time by using an object
  307. for the first argument where the keys are file names and the values are source
  308. code:
  309. ```javascript
  310. var code = {
  311. "file1.js": "function add(first, second) { return first + second; }",
  312. "file2.js": "console.log(add(1 + 2, 3 + 4));"
  313. };
  314. var result = UglifyJS.minify(code);
  315. console.log(result.code);
  316. // function add(d,n){return d+n}console.log(add(3,7));
  317. ```
  318. The `toplevel` option:
  319. ```javascript
  320. var code = {
  321. "file1.js": "function add(first, second) { return first + second; }",
  322. "file2.js": "console.log(add(1 + 2, 3 + 4));"
  323. };
  324. var options = { toplevel: true };
  325. var result = UglifyJS.minify(code, options);
  326. console.log(result.code);
  327. // console.log(3+7);
  328. ```
  329. The `nameCache` option:
  330. ```javascript
  331. var options = {
  332. mangle: {
  333. toplevel: true,
  334. },
  335. nameCache: {}
  336. };
  337. var result1 = UglifyJS.minify({
  338. "file1.js": "function add(first, second) { return first + second; }"
  339. }, options);
  340. var result2 = UglifyJS.minify({
  341. "file2.js": "console.log(add(1 + 2, 3 + 4));"
  342. }, options);
  343. console.log(result1.code);
  344. // function n(n,r){return n+r}
  345. console.log(result2.code);
  346. // console.log(n(3,7));
  347. ```
  348. You may persist the name cache to the file system in the following way:
  349. ```javascript
  350. var cacheFileName = "/tmp/cache.json";
  351. var options = {
  352. mangle: {
  353. properties: true,
  354. },
  355. nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8"))
  356. };
  357. fs.writeFileSync("part1.js", UglifyJS.minify({
  358. "file1.js": fs.readFileSync("file1.js", "utf8"),
  359. "file2.js": fs.readFileSync("file2.js", "utf8")
  360. }, options).code, "utf8");
  361. fs.writeFileSync("part2.js", UglifyJS.minify({
  362. "file3.js": fs.readFileSync("file3.js", "utf8"),
  363. "file4.js": fs.readFileSync("file4.js", "utf8")
  364. }, options).code, "utf8");
  365. fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8");
  366. ```
  367. An example of a combination of `minify()` options:
  368. ```javascript
  369. var code = {
  370. "file1.js": "function add(first, second) { return first + second; }",
  371. "file2.js": "console.log(add(1 + 2, 3 + 4));"
  372. };
  373. var options = {
  374. toplevel: true,
  375. compress: {
  376. global_defs: {
  377. "@console.log": "alert"
  378. },
  379. passes: 2
  380. },
  381. output: {
  382. beautify: false,
  383. preamble: "/* uglified */"
  384. }
  385. };
  386. var result = UglifyJS.minify(code, options);
  387. console.log(result.code);
  388. // /* uglified */
  389. // alert(10);"
  390. ```
  391. To produce warnings:
  392. ```javascript
  393. var code = "function f(){ var u; return 2 + 3; }";
  394. var options = { warnings: true };
  395. var result = UglifyJS.minify(code, options);
  396. console.log(result.error); // runtime error, `undefined` in this case
  397. console.log(result.warnings); // [ 'Dropping unused variable u [0:1,18]' ]
  398. console.log(result.code); // function f(){return 5}
  399. ```
  400. An error example:
  401. ```javascript
  402. var result = UglifyJS.minify({"foo.js" : "if (0) else console.log(1);"});
  403. console.log(JSON.stringify(result.error));
  404. // {"message":"Unexpected token: keyword (else)","filename":"foo.js","line":1,"col":7,"pos":7}
  405. ```
  406. Note: unlike `uglify-js@2.x`, the `3.x` API does not throw errors. To
  407. achieve a similar effect one could do the following:
  408. ```javascript
  409. var result = UglifyJS.minify(code, options);
  410. if (result.error) throw result.error;
  411. ```
  412. ## Minify options
  413. - `compress` (default `{}`) — pass `false` to skip compressing entirely.
  414. Pass an object to specify custom [compress options](#compress-options).
  415. - `ie8` (default `false`) -- set to `true` to support IE8.
  416. - `keep_fnames` (default: `false`) -- pass `true` to prevent discarding or mangling
  417. of function names. Useful for code relying on `Function.prototype.name`.
  418. - `mangle` (default `true`) — pass `false` to skip mangling names, or pass
  419. an object to specify [mangle options](#mangle-options) (see below).
  420. - `mangle.properties` (default `false`) — a subcategory of the mangle option.
  421. Pass an object to specify custom [mangle property options](#mangle-properties-options).
  422. - `nameCache` (default `null`) -- pass an empty object `{}` or a previously
  423. used `nameCache` object if you wish to cache mangled variable and
  424. property names across multiple invocations of `minify()`. Note: this is
  425. a read/write property. `minify()` will read the name cache state of this
  426. object and update it during minification so that it may be
  427. reused or externally persisted by the user.
  428. - `output` (default `null`) — pass an object if you wish to specify
  429. additional [output options](#output-options). The defaults are optimized
  430. for best compression.
  431. - `parse` (default `{}`) — pass an object if you wish to specify some
  432. additional [parse options](#parse-options).
  433. - `sourceMap` (default `false`) -- pass an object if you wish to specify
  434. [source map options](#source-map-options).
  435. - `toplevel` (default `false`) -- set to `true` if you wish to enable top level
  436. variable and function name mangling and to drop unused variables and functions.
  437. - `warnings` (default `false`) — pass `true` to return compressor warnings
  438. in `result.warnings`. Use the value `"verbose"` for more detailed warnings.
  439. ## Minify options structure
  440. ```javascript
  441. {
  442. parse: {
  443. // parse options
  444. },
  445. compress: {
  446. // compress options
  447. },
  448. mangle: {
  449. // mangle options
  450. properties: {
  451. // mangle property options
  452. }
  453. },
  454. output: {
  455. // output options
  456. },
  457. sourceMap: {
  458. // source map options
  459. },
  460. nameCache: null, // or specify a name cache object
  461. toplevel: false,
  462. ie8: false,
  463. warnings: false,
  464. }
  465. ```
  466. ### Source map options
  467. To generate a source map:
  468. ```javascript
  469. var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, {
  470. sourceMap: {
  471. filename: "out.js",
  472. url: "out.js.map"
  473. }
  474. });
  475. console.log(result.code); // minified output
  476. console.log(result.map); // source map
  477. ```
  478. Note that the source map is not saved in a file, it's just returned in
  479. `result.map`. The value passed for `sourceMap.url` is only used to set
  480. `//# sourceMappingURL=out.js.map` in `result.code`. The value of
  481. `filename` is only used to set `file` attribute (see [the spec][sm-spec])
  482. in source map file.
  483. You can set option `sourceMap.url` to be `"inline"` and source map will
  484. be appended to code.
  485. You can also specify sourceRoot property to be included in source map:
  486. ```javascript
  487. var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, {
  488. sourceMap: {
  489. root: "http://example.com/src",
  490. url: "out.js.map"
  491. }
  492. });
  493. ```
  494. If you're compressing compiled JavaScript and have a source map for it, you
  495. can use `sourceMap.content`:
  496. ```javascript
  497. var result = UglifyJS.minify({"compiled.js": "compiled code"}, {
  498. sourceMap: {
  499. content: "content from compiled.js.map",
  500. url: "minified.js.map"
  501. }
  502. });
  503. // same as before, it returns `code` and `map`
  504. ```
  505. If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.url`.
  506. If you wish to reduce file size of the source map, set option `sourceMap.names`
  507. to be `false` and all symbol names will be omitted.
  508. ## Parse options
  509. - `bare_returns` (default `false`) -- support top level `return` statements
  510. - `html5_comments` (default `true`)
  511. - `shebang` (default `true`) -- support `#!command` as the first line
  512. ## Compress options
  513. - `arguments` (default: `true`) -- replace `arguments[index]` with function
  514. parameter name whenever possible.
  515. - `assignments` (default: `true`) -- apply optimizations to assignment expressions.
  516. - `booleans` (default: `true`) -- various optimizations for boolean context,
  517. for example `!!a ? b : c → a ? b : c`
  518. - `collapse_vars` (default: `true`) -- Collapse single-use non-constant variables,
  519. side effects permitting.
  520. - `comparisons` (default: `true`) -- apply certain optimizations to binary nodes,
  521. e.g. `!(a <= b) → a > b`, attempts to negate binary nodes, e.g.
  522. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc.
  523. - `conditionals` (default: `true`) -- apply optimizations for `if`-s and conditional
  524. expressions
  525. - `dead_code` (default: `true`) -- remove unreachable code
  526. - `directives` (default: `true`) -- remove redundant or non-standard directives
  527. - `drop_console` (default: `false`) -- Pass `true` to discard calls to
  528. `console.*` functions. If you wish to drop a specific function call
  529. such as `console.info` and/or retain side effects from function arguments
  530. after dropping the function call then use `pure_funcs` instead.
  531. - `drop_debugger` (default: `true`) -- remove `debugger;` statements
  532. - `evaluate` (default: `true`) -- Evaluate expression for shorter constant
  533. representation. Pass `"eager"` to always replace function calls whenever
  534. possible, or a positive integer to specify an upper bound for each individual
  535. evaluation in number of characters.
  536. - `expression` (default: `false`) -- Pass `true` to preserve completion values
  537. from terminal statements without `return`, e.g. in bookmarklets.
  538. - `functions` (default: `true`) -- convert declarations from `var`to `function`
  539. whenever possible.
  540. - `global_defs` (default: `{}`) -- see [conditional compilation](#conditional-compilation)
  541. - `hoist_funs` (default: `false`) -- hoist function declarations
  542. - `hoist_props` (default: `true`) -- hoist properties from constant object and
  543. array literals into regular variables subject to a set of constraints. For example:
  544. `var o={p:1, q:2}; f(o.p, o.q);` is converted to `f(1, 2);`. Note: `hoist_props`
  545. works best with `mangle` enabled, the `compress` option `passes` set to `2` or higher,
  546. and the `compress` option `toplevel` enabled.
  547. - `hoist_vars` (default: `false`) -- hoist `var` declarations (this is `false`
  548. by default because it seems to increase the size of the output in general)
  549. - `if_return` (default: `true`) -- optimizations for if/return and if/continue
  550. - `inline` (default: `true`) -- inline calls to function with simple/`return` statement:
  551. - `false` -- same as `0`
  552. - `0` -- disabled inlining
  553. - `1` -- inline simple functions
  554. - `2` -- inline functions with arguments
  555. - `3` -- inline functions with arguments and variables
  556. - `true` -- same as `3`
  557. - `join_vars` (default: `true`) -- join consecutive `var` statements
  558. - `keep_fargs` (default: `strict`) -- Discard unused function arguments. Code
  559. which relies on `Function.length` will break if this is done indiscriminately,
  560. i.e. when passing `true`. Pass `false` to always retain function arguments.
  561. - `keep_fnames` (default: `false`) -- Pass `true` to prevent the
  562. compressor from discarding function names. Useful for code relying on
  563. `Function.prototype.name`. See also: the `keep_fnames` [mangle option](#mangle-options).
  564. - `keep_infinity` (default: `false`) -- Pass `true` to prevent `Infinity` from
  565. being compressed into `1/0`, which may cause performance issues on Chrome.
  566. - `loops` (default: `true`) -- optimizations for `do`, `while` and `for` loops
  567. when we can statically determine the condition.
  568. - `negate_iife` (default: `true`) -- negate "Immediately-Called Function Expressions"
  569. where the return value is discarded, to avoid the parens that the
  570. code generator would insert.
  571. - `objects` (default: `true`) -- compact duplicate keys in object literals.
  572. - `passes` (default: `1`) -- The maximum number of times to run compress.
  573. In some cases more than one pass leads to further compressed code. Keep in
  574. mind more passes will take more time.
  575. - `properties` (default: `true`) -- rewrite property access using the dot notation, for
  576. example `foo["bar"] → foo.bar`
  577. - `pure_funcs` (default: `null`) -- You can pass an array of names and
  578. UglifyJS will assume that those functions do not produce side
  579. effects. DANGER: will not check if the name is redefined in scope.
  580. An example case here, for instance `var q = Math.floor(a/b)`. If
  581. variable `q` is not used elsewhere, UglifyJS will drop it, but will
  582. still keep the `Math.floor(a/b)`, not knowing what it does. You can
  583. pass `pure_funcs: [ 'Math.floor' ]` to let it know that this
  584. function won't produce any side effect, in which case the whole
  585. statement would get discarded. The current implementation adds some
  586. overhead (compression will be slower). Make sure symbols under `pure_funcs`
  587. are also under `mangle.reserved` to avoid mangling.
  588. - `pure_getters` (default: `"strict"`) -- If you pass `true` for
  589. this, UglifyJS will assume that object property access
  590. (e.g. `foo.bar` or `foo["bar"]`) doesn't have any side effects.
  591. Specify `"strict"` to treat `foo.bar` as side-effect-free only when
  592. `foo` is certain to not throw, i.e. not `null` or `undefined`.
  593. - `reduce_funcs` (default: `true`) -- Allows single-use functions to be
  594. inlined as function expressions when permissible allowing further
  595. optimization. Enabled by default. Option depends on `reduce_vars`
  596. being enabled. Some code runs faster in the Chrome V8 engine if this
  597. option is disabled. Does not negatively impact other major browsers.
  598. - `reduce_vars` (default: `true`) -- Improve optimization on variables assigned with and
  599. used as constant values.
  600. - `sequences` (default: `true`) -- join consecutive simple statements using the
  601. comma operator. May be set to a positive integer to specify the maximum number
  602. of consecutive comma sequences that will be generated. If this option is set to
  603. `true` then the default `sequences` limit is `200`. Set option to `false` or `0`
  604. to disable. The smallest `sequences` length is `2`. A `sequences` value of `1`
  605. is grandfathered to be equivalent to `true` and as such means `200`. On rare
  606. occasions the default sequences limit leads to very slow compress times in which
  607. case a value of `20` or less is recommended.
  608. - `side_effects` (default: `true`) -- Pass `false` to disable potentially dropping
  609. functions marked as "pure". A function call is marked as "pure" if a comment
  610. annotation `/*@__PURE__*/` or `/*#__PURE__*/` immediately precedes the call. For
  611. example: `/*@__PURE__*/foo();`
  612. - `strings` (default: `true`) -- compact string concatenations.
  613. - `switches` (default: `true`) -- de-duplicate and remove unreachable `switch` branches
  614. - `toplevel` (default: `false`) -- drop unreferenced functions (`"funcs"`) and/or
  615. variables (`"vars"`) in the top level scope (`false` by default, `true` to drop
  616. both unreferenced functions and variables)
  617. - `top_retain` (default: `null`) -- prevent specific toplevel functions and
  618. variables from `unused` removal (can be array, comma-separated, RegExp or
  619. function. Implies `toplevel`)
  620. - `typeofs` (default: `true`) -- Transforms `typeof foo == "undefined"` into
  621. `foo === void 0`. Note: recommend to set this value to `false` for IE10 and
  622. earlier versions due to known issues.
  623. - `unsafe` (default: `false`) -- apply "unsafe" transformations (discussion below)
  624. - `unsafe_comps` (default: `false`) -- compress expressions like `a <= b` assuming
  625. none of the operands can be (coerced to) `NaN`.
  626. - `unsafe_Function` (default: `false`) -- compress and mangle `Function(args, code)`
  627. when both `args` and `code` are string literals.
  628. - `unsafe_math` (default: `false`) -- optimize numerical expressions like
  629. `2 * x * 3` into `6 * x`, which may give imprecise floating point results.
  630. - `unsafe_proto` (default: `false`) -- optimize expressions like
  631. `Array.prototype.slice.call(a)` into `[].slice.call(a)`
  632. - `unsafe_regexp` (default: `false`) -- enable substitutions of variables with
  633. `RegExp` values the same way as if they are constants.
  634. - `unsafe_undefined` (default: `false`) -- substitute `void 0` if there is a
  635. variable named `undefined` in scope (variable name will be mangled, typically
  636. reduced to a single character)
  637. - `unused` (default: `true`) -- drop unreferenced functions and variables (simple
  638. direct variable assignments do not count as references unless set to `"keep_assign"`)
  639. ## Mangle options
  640. - `eval` (default `false`) -- Pass `true` to mangle names visible in scopes
  641. where `eval` or `with` are used.
  642. - `keep_fnames` (default `false`) -- Pass `true` to not mangle function names.
  643. Useful for code relying on `Function.prototype.name`. See also: the `keep_fnames`
  644. [compress option](#compress-options).
  645. - `reserved` (default `[]`) -- Pass an array of identifiers that should be
  646. excluded from mangling. Example: `["foo", "bar"]`.
  647. - `toplevel` (default `false`) -- Pass `true` to mangle names declared in the
  648. top level scope.
  649. Examples:
  650. ```javascript
  651. // test.js
  652. var globalVar;
  653. function funcName(firstLongName, anotherLongName) {
  654. var myVariable = firstLongName + anotherLongName;
  655. }
  656. ```
  657. ```javascript
  658. var code = fs.readFileSync("test.js", "utf8");
  659. UglifyJS.minify(code).code;
  660. // 'function funcName(a,n){}var globalVar;'
  661. UglifyJS.minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
  662. // 'function funcName(firstLongName,a){}var globalVar;'
  663. UglifyJS.minify(code, { mangle: { toplevel: true } }).code;
  664. // 'function n(n,a){}var a;'
  665. ```
  666. ### Mangle properties options
  667. - `builtins` (default: `false`) -- Use `true` to allow the mangling of builtin
  668. DOM properties. Not recommended to override this setting.
  669. - `debug` (default: `false`) -— Mangle names with the original name still present.
  670. Pass an empty string `""` to enable, or a non-empty string to set the debug suffix.
  671. - `keep_quoted` (default: `false`) -— Only mangle unquoted property names.
  672. - `regex` (default: `null`) -— Pass a RegExp literal to only mangle property
  673. names matching the regular expression.
  674. - `reserved` (default: `[]`) -- Do not mangle property names listed in the
  675. `reserved` array.
  676. ## Output options
  677. The code generator tries to output shortest code possible by default. In
  678. case you want beautified output, pass `--beautify` (`-b`). Optionally you
  679. can pass additional arguments that control the code output:
  680. - `ascii_only` (default `false`) -- escape Unicode characters in strings and
  681. regexps (affects directives with non-ascii characters becoming invalid)
  682. - `beautify` (default `true`) -- whether to actually beautify the output.
  683. Passing `-b` will set this to true, but you might need to pass `-b` even
  684. when you want to generate minified code, in order to specify additional
  685. arguments, so you can use `-b beautify=false` to override it.
  686. - `braces` (default `false`) -- always insert braces in `if`, `for`,
  687. `do`, `while` or `with` statements, even if their body is a single
  688. statement.
  689. - `comments` (default `false`) -- pass `true` or `"all"` to preserve all
  690. comments, `"some"` to preserve multi-line comments that contain `@cc_on`,
  691. `@license`, or `@preserve` (case-insensitive), a regular expression string
  692. (e.g. `/^!/`), or a function which returns `boolean`, e.g.
  693. ```js
  694. function(node, comment) {
  695. return comment.value.indexOf("@type " + node.TYPE) >= 0;
  696. }
  697. ```
  698. - `indent_level` (default `4`)
  699. - `indent_start` (default `0`) -- prefix all lines by that many spaces
  700. - `inline_script` (default `true`) -- escape HTML comments and the slash in
  701. occurrences of `</script>` in strings
  702. - `keep_quoted_props` (default `false`) -- when turned on, prevents stripping
  703. quotes from property names in object literals.
  704. - `max_line_len` (default `false`) -- maximum line length (for uglified code)
  705. - `preamble` (default `null`) -- when passed it must be a string and
  706. it will be prepended to the output literally. The source map will
  707. adjust for this text. Can be used to insert a comment containing
  708. licensing information, for example.
  709. - `preserve_line` (default `false`) -- pass `true` to retain line numbering on
  710. a best effort basis.
  711. - `quote_keys` (default `false`) -- pass `true` to quote all keys in literal
  712. objects
  713. - `quote_style` (default `0`) -- preferred quote style for strings (affects
  714. quoted property names and directives as well):
  715. - `0` -- prefers double quotes, switches to single quotes when there are
  716. more double quotes in the string itself. `0` is best for gzip size.
  717. - `1` -- always use single quotes
  718. - `2` -- always use double quotes
  719. - `3` -- always use the original quotes
  720. - `semicolons` (default `true`) -- separate statements with semicolons. If
  721. you pass `false` then whenever possible we will use a newline instead of a
  722. semicolon, leading to more readable output of uglified code (size before
  723. gzip could be smaller; size after gzip insignificantly larger).
  724. - `shebang` (default `true`) -- preserve shebang `#!` in preamble (bash scripts)
  725. - `webkit` (default `false`) -- enable workarounds for WebKit bugs.
  726. PhantomJS users should set this option to `true`.
  727. - `width` (default `80`) -- only takes effect when beautification is on, this
  728. specifies an (orientative) line width that the beautifier will try to
  729. obey. It refers to the width of the line text (excluding indentation).
  730. It doesn't work very well currently, but it does make the code generated
  731. by UglifyJS more readable.
  732. - `wrap_iife` (default `false`) -- pass `true` to wrap immediately invoked
  733. function expressions. See
  734. [#640](https://github.com/mishoo/UglifyJS/issues/640) for more details.
  735. # Miscellaneous
  736. ### Keeping copyright notices or other comments
  737. You can pass `--comments` to retain certain comments in the output. By
  738. default it will keep JSDoc-style comments that contain "@preserve",
  739. "@license" or "@cc_on" (conditional compilation for IE). You can pass
  740. `--comments all` to keep all the comments, or a valid JavaScript regexp to
  741. keep only comments that match this regexp. For example `--comments /^!/`
  742. will keep comments like `/*! Copyright Notice */`.
  743. Note, however, that there might be situations where comments are lost. For
  744. example:
  745. ```javascript
  746. function f() {
  747. /** @preserve Foo Bar */
  748. function g() {
  749. // this function is never called
  750. }
  751. return something();
  752. }
  753. ```
  754. Even though it has "@preserve", the comment will be lost because the inner
  755. function `g` (which is the AST node to which the comment is attached to) is
  756. discarded by the compressor as not referenced.
  757. The safest comments where to place copyright information (or other info that
  758. needs to be kept in the output) are comments attached to toplevel nodes.
  759. ### The `unsafe` `compress` option
  760. It enables some transformations that *might* break code logic in certain
  761. contrived cases, but should be fine for most code. You might want to try it
  762. on your own code, it should reduce the minified size. Here's what happens
  763. when this flag is on:
  764. - `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[ 1, 2, 3 ]`
  765. - `new Object()` → `{}`
  766. - `String(exp)` or `exp.toString()` → `"" + exp`
  767. - `new Object/RegExp/Function/Error/Array (...)` → we discard the `new`
  768. ### Conditional compilation
  769. You can use the `--define` (`-d`) switch in order to declare global
  770. variables that UglifyJS will assume to be constants (unless defined in
  771. scope). For example if you pass `--define DEBUG=false` then, coupled with
  772. dead code removal UglifyJS will discard the following from the output:
  773. ```javascript
  774. if (DEBUG) {
  775. console.log("debug stuff");
  776. }
  777. ```
  778. You can specify nested constants in the form of `--define env.DEBUG=false`.
  779. UglifyJS will warn about the condition being always false and about dropping
  780. unreachable code; for now there is no option to turn off only this specific
  781. warning, you can pass `warnings=false` to turn off *all* warnings.
  782. Another way of doing that is to declare your globals as constants in a
  783. separate file and include it into the build. For example you can have a
  784. `build/defines.js` file with the following:
  785. ```javascript
  786. var DEBUG = false;
  787. var PRODUCTION = true;
  788. // etc.
  789. ```
  790. and build your code like this:
  791. uglifyjs build/defines.js js/foo.js js/bar.js... -c
  792. UglifyJS will notice the constants and, since they cannot be altered, it
  793. will evaluate references to them to the value itself and drop unreachable
  794. code as usual. The build will contain the `const` declarations if you use
  795. them. If you are targeting < ES6 environments which does not support `const`,
  796. using `var` with `reduce_vars` (enabled by default) should suffice.
  797. ### Conditional compilation API
  798. You can also use conditional compilation via the programmatic API. With the difference that the
  799. property name is `global_defs` and is a compressor property:
  800. ```javascript
  801. var result = UglifyJS.minify(fs.readFileSync("input.js", "utf8"), {
  802. compress: {
  803. dead_code: true,
  804. global_defs: {
  805. DEBUG: false
  806. }
  807. }
  808. });
  809. ```
  810. To replace an identifier with an arbitrary non-constant expression it is
  811. necessary to prefix the `global_defs` key with `"@"` to instruct UglifyJS
  812. to parse the value as an expression:
  813. ```javascript
  814. UglifyJS.minify("alert('hello');", {
  815. compress: {
  816. global_defs: {
  817. "@alert": "console.log"
  818. }
  819. }
  820. }).code;
  821. // returns: 'console.log("hello");'
  822. ```
  823. Otherwise it would be replaced as string literal:
  824. ```javascript
  825. UglifyJS.minify("alert('hello');", {
  826. compress: {
  827. global_defs: {
  828. "alert": "console.log"
  829. }
  830. }
  831. }).code;
  832. // returns: '"console.log"("hello");'
  833. ```
  834. ### Using native Uglify AST with `minify()`
  835. ```javascript
  836. // example: parse only, produce native Uglify AST
  837. var result = UglifyJS.minify(code, {
  838. parse: {},
  839. compress: false,
  840. mangle: false,
  841. output: {
  842. ast: true,
  843. code: false // optional - faster if false
  844. }
  845. });
  846. // result.ast contains native Uglify AST
  847. ```
  848. ```javascript
  849. // example: accept native Uglify AST input and then compress and mangle
  850. // to produce both code and native AST.
  851. var result = UglifyJS.minify(ast, {
  852. compress: {},
  853. mangle: {},
  854. output: {
  855. ast: true,
  856. code: true // optional - faster if false
  857. }
  858. });
  859. // result.ast contains native Uglify AST
  860. // result.code contains the minified code in string form.
  861. ```
  862. ### Working with Uglify AST
  863. Transversal and transformation of the native AST can be performed through
  864. [`TreeWalker`](https://github.com/mishoo/UglifyJS/blob/master/lib/ast.js) and
  865. [`TreeTransformer`](https://github.com/mishoo/UglifyJS/blob/master/lib/transform.js)
  866. respectively.
  867. ### ESTree / SpiderMonkey AST
  868. UglifyJS has its own abstract syntax tree format; for
  869. [practical reasons](http://lisperator.net/blog/uglifyjs-why-not-switching-to-spidermonkey-ast/)
  870. we can't easily change to using the SpiderMonkey AST internally. However,
  871. UglifyJS now has a converter which can import a SpiderMonkey AST.
  872. For example [Acorn][acorn] is a super-fast parser that produces a
  873. SpiderMonkey AST. It has a small CLI utility that parses one file and dumps
  874. the AST in JSON on the standard output. To use UglifyJS to mangle and
  875. compress that:
  876. acorn file.js | uglifyjs -p spidermonkey -m -c
  877. The `-p spidermonkey` option tells UglifyJS that all input files are not
  878. JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we
  879. don't use our own parser in this case, but just transform that AST into our
  880. internal AST.
  881. ### Use Acorn for parsing
  882. More for fun, I added the `-p acorn` option which will use Acorn to do all
  883. the parsing. If you pass this option, UglifyJS will `require("acorn")`.
  884. Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but
  885. converting the SpiderMonkey tree that Acorn produces takes another 150ms so
  886. in total it's a bit more than just using UglifyJS's own parser.
  887. [acorn]: https://github.com/ternjs/acorn
  888. [sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k
  889. ### Uglify Fast Minify Mode
  890. It's not well known, but whitespace removal and symbol mangling accounts
  891. for 95% of the size reduction in minified code for most JavaScript - not
  892. elaborate code transforms. One can simply disable `compress` to speed up
  893. Uglify builds by 3 to 4 times. In this fast `mangle`-only mode Uglify has
  894. comparable minify speeds and gzip sizes to
  895. [`butternut`](https://www.npmjs.com/package/butternut):
  896. | d3.js | minify size | gzip size | minify time (seconds) |
  897. | --- | ---: | ---: | ---: |
  898. | original | 451,131 | 108,733 | - |
  899. | uglify-js@3.0.24 mangle=false, compress=false | 316,600 | 85,245 | 0.70 |
  900. | uglify-js@3.0.24 mangle=true, compress=false | 220,216 | 72,730 | 1.13 |
  901. | butternut@0.4.6 | 217,568 | 72,738 | 1.41 |
  902. | uglify-js@3.0.24 mangle=true, compress=true | 212,511 | 71,560 | 3.36 |
  903. | babili@0.1.4 | 210,713 | 72,140 | 12.64 |
  904. To enable fast minify mode from the CLI use:
  905. ```
  906. uglifyjs file.js -m
  907. ```
  908. To enable fast minify mode with the API use:
  909. ```js
  910. UglifyJS.minify(code, { compress: false, mangle: true });
  911. ```
  912. #### Source maps and debugging
  913. Various `compress` transforms that simplify, rearrange, inline and remove code
  914. are known to have an adverse effect on debugging with source maps. This is
  915. expected as code is optimized and mappings are often simply not possible as
  916. some code no longer exists. For highest fidelity in source map debugging
  917. disable the Uglify `compress` option and just use `mangle`.
  918. ### Compiler assumptions
  919. To allow for better optimizations, the compiler makes various assumptions:
  920. - `.toString()` and `.valueOf()` don't have side effects, and for built-in
  921. objects they have not been overridden.
  922. - `undefined`, `NaN` and `Infinity` have not been externally redefined.
  923. - `arguments.callee`, `arguments.caller` and `Function.prototype.caller` are not used.
  924. - The code doesn't expect the contents of `Function.prototype.toString()` or
  925. `Error.prototype.stack` to be anything in particular.
  926. - Getting and setting properties on a plain object does not cause other side effects
  927. (using `.watch()` or `Proxy`).
  928. - Object properties can be added, removed and modified (not prevented with
  929. `Object.defineProperty()`, `Object.defineProperties()`, `Object.freeze()`,
  930. `Object.preventExtensions()` or `Object.seal()`).