版博士V2.0程序
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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