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.

1135 lines
44 KiB

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