e0c16f55f93dc3825a0780873276a837070f8fc5fa2893e6c4f2e70b0e6141325a451e2ef29b75ea420c8972eac91e3cce41ff67e19b2b22eddc0c984f0c0e 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. <h1><img src="https://terser.org/img/terser-banner-logo.png" alt="Terser" width="400"></h1>
  2. [![NPM Version][npm-image]][npm-url]
  3. [![NPM Downloads][downloads-image]][downloads-url]
  4. [![Travis Build][travis-image]][travis-url]
  5. [![Opencollective financial contributors][opencollective-contributors]][opencollective-url]
  6. A JavaScript parser and mangler/compressor toolkit for ES6+.
  7. *note*: You can support this project on patreon: <a target="_blank" rel="nofollow" href="https://www.patreon.com/fabiosantoscode"><img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" alt="patron" width="100px" height="auto"></a>. Check out [PATRONS.md](https://github.com/terser/terser/blob/master/PATRONS.md) for our first-tier patrons.
  8. Terser recommends you use RollupJS to bundle your modules, as that produces smaller code overall.
  9. *Beautification* has been undocumented and is *being removed* from terser, we recommend you use [prettier](https://npmjs.com/package/prettier).
  10. Find the changelog in [CHANGELOG.md](https://github.com/terser/terser/blob/master/CHANGELOG.md)
  11. [npm-image]: https://img.shields.io/npm/v/terser.svg
  12. [npm-url]: https://npmjs.org/package/terser
  13. [downloads-image]: https://img.shields.io/npm/dm/terser.svg
  14. [downloads-url]: https://npmjs.org/package/terser
  15. [travis-image]: https://img.shields.io/travis/terser/terser/master.svg
  16. [travis-url]: https://travis-ci.org/terser/terser
  17. [opencollective-contributors]: https://opencollective.com/terser/tiers/badge.svg
  18. [opencollective-url]: https://opencollective.com/terser
  19. Why choose terser?
  20. ------------------
  21. `uglify-es` is [no longer maintained](https://github.com/mishoo/UglifyJS2/issues/3156#issuecomment-392943058) and `uglify-js` does not support ES6+.
  22. **`terser`** is a fork of `uglify-es` that mostly retains API and CLI compatibility
  23. with `uglify-es` and `uglify-js@3`.
  24. Install
  25. -------
  26. First make sure you have installed the latest version of [node.js](http://nodejs.org/)
  27. (You may need to restart your computer after this step).
  28. From NPM for use as a command line app:
  29. npm install terser -g
  30. From NPM for programmatic use:
  31. npm install terser
  32. # Command line usage
  33. terser [input files] [options]
  34. Terser can take multiple input files. It's recommended that you pass the
  35. input files first, then pass the options. Terser will parse input files
  36. in sequence and apply any compression options. The files are parsed in the
  37. same global scope, that is, a reference from a file to some
  38. variable/function declared in another file will be matched properly.
  39. If no input file is specified, Terser will read from STDIN.
  40. If you wish to pass your options before the input files, separate the two with
  41. a double dash to prevent input files being used as option arguments:
  42. terser --compress --mangle -- input.js
  43. ### Command line options
  44. ```
  45. -h, --help Print usage information.
  46. `--help options` for details on available options.
  47. -V, --version Print version number.
  48. -p, --parse <options> Specify parser options:
  49. `acorn` Use Acorn for parsing.
  50. `bare_returns` Allow return outside of functions.
  51. Useful when minifying CommonJS
  52. modules and Userscripts that may
  53. be anonymous function wrapped (IIFE)
  54. by the .user.js engine `caller`.
  55. `expression` Parse a single expression, rather than
  56. a program (for parsing JSON).
  57. `spidermonkey` Assume input files are SpiderMonkey
  58. AST format (as JSON).
  59. -c, --compress [options] Enable compressor/specify compressor options:
  60. `pure_funcs` List of functions that can be safely
  61. removed when their return values are
  62. not used.
  63. -m, --mangle [options] Mangle names/specify mangler options:
  64. `reserved` List of names that should not be mangled.
  65. --mangle-props [options] Mangle properties/specify mangler options:
  66. `builtins` Mangle property names that overlaps
  67. with standard JavaScript globals and DOM
  68. API props.
  69. `debug` Add debug prefix and suffix.
  70. `keep_quoted` Only mangle unquoted properties, quoted
  71. properties are automatically reserved.
  72. `strict` disables quoted properties
  73. being automatically reserved.
  74. `regex` Only mangle matched property names.
  75. `reserved` List of names that should not be mangled.
  76. -b, --beautify [options] Specify output options:
  77. `preamble` Preamble to prepend to the output. You
  78. can use this to insert a comment, for
  79. example for licensing information.
  80. This will not be parsed, but the source
  81. map will adjust for its presence.
  82. `quote_style` Quote style:
  83. 0 - auto
  84. 1 - single
  85. 2 - double
  86. 3 - original
  87. `wrap_iife` Wrap IIFEs in parenthesis. Note: you may
  88. want to disable `negate_iife` under
  89. compressor options.
  90. `wrap_func_args` Wrap function arguments in parenthesis.
  91. -o, --output <file> Output file path (default STDOUT). Specify `ast` or
  92. `spidermonkey` to write Terser or SpiderMonkey AST
  93. as JSON to STDOUT respectively.
  94. --comments [filter] Preserve copyright comments in the output. By
  95. default this works like Google Closure, keeping
  96. JSDoc-style comments that contain "@license" or
  97. "@preserve". You can optionally pass one of the
  98. following arguments to this flag:
  99. - "all" to keep all comments
  100. - `false` to omit comments in the output
  101. - a valid JS RegExp like `/foo/` or `/^!/` to
  102. keep only matching comments.
  103. Note that currently not *all* comments can be
  104. kept when compression is on, because of dead
  105. code removal or cascading statements into
  106. sequences.
  107. --config-file <file> Read `minify()` options from JSON file.
  108. -d, --define <expr>[=value] Global definitions.
  109. --ecma <version> Specify ECMAScript release: 5, 2015, 2016, etc.
  110. -e, --enclose [arg[:value]] Embed output in a big function with configurable
  111. arguments and values.
  112. --ie8 Support non-standard Internet Explorer 8.
  113. Equivalent to setting `ie8: true` in `minify()`
  114. for `compress`, `mangle` and `output` options.
  115. By default Terser will not try to be IE-proof.
  116. --keep-classnames Do not mangle/drop class names.
  117. --keep-fnames Do not mangle/drop function names. Useful for
  118. code relying on Function.prototype.name.
  119. --module Input is an ES6 module. If `compress` or `mangle` is
  120. enabled then the `toplevel` option will be enabled.
  121. --name-cache <file> File to hold mangled name mappings.
  122. --safari10 Support non-standard Safari 10/11.
  123. Equivalent to setting `safari10: true` in `minify()`
  124. for `mangle` and `output` options.
  125. By default `terser` will not work around
  126. Safari 10/11 bugs.
  127. --source-map [options] Enable source map/specify source map options:
  128. `base` Path to compute relative paths from input files.
  129. `content` Input source map, useful if you're compressing
  130. JS that was generated from some other original
  131. code. Specify "inline" if the source map is
  132. included within the sources.
  133. `filename` Name and/or location of the output source.
  134. `includeSources` Pass this flag if you want to include
  135. the content of source files in the
  136. source map as sourcesContent property.
  137. `root` Path to the original source to be included in
  138. the source map.
  139. `url` If specified, path to the source map to append in
  140. `//# sourceMappingURL`.
  141. --timings Display operations run time on STDERR.
  142. --toplevel Compress and/or mangle variables in top level scope.
  143. --verbose Print diagnostic messages.
  144. --warn Print warning messages.
  145. --wrap <name> Embed everything in a big function, making the
  146. “exports” and “global” variables available. You
  147. need to pass an argument to this option to
  148. specify the name that your module will take
  149. when included in, say, a browser.
  150. ```
  151. Specify `--output` (`-o`) to declare the output file. Otherwise the output
  152. goes to STDOUT.
  153. ## CLI source map options
  154. Terser can generate a source map file, which is highly useful for
  155. debugging your compressed JavaScript. To get a source map, pass
  156. `--source-map --output output.js` (source map will be written out to
  157. `output.js.map`).
  158. Additional options:
  159. - `--source-map "filename='<NAME>'"` to specify the name of the source map.
  160. - `--source-map "root='<URL>'"` to pass the URL where the original files can be found.
  161. - `--source-map "url='<URL>'"` to specify the URL where the source map can be found.
  162. Otherwise Terser assumes HTTP `X-SourceMap` is being used and will omit the
  163. `//# sourceMappingURL=` directive.
  164. For example:
  165. terser js/file1.js js/file2.js \
  166. -o foo.min.js -c -m \
  167. --source-map "root='http://foo.com/src',url='foo.min.js.map'"
  168. The above will compress and mangle `file1.js` and `file2.js`, will drop the
  169. output in `foo.min.js` and the source map in `foo.min.js.map`. The source
  170. mapping will refer to `http://foo.com/src/js/file1.js` and
  171. `http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src`
  172. as the source map root, and the original files as `js/file1.js` and
  173. `js/file2.js`).
  174. ### Composed source map
  175. When you're compressing JS code that was output by a compiler such as
  176. CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd
  177. like to map back to the original code (i.e. CoffeeScript). Terser has an
  178. option to take an input source map. Assuming you have a mapping from
  179. CoffeeScript → compiled JS, Terser can generate a map from CoffeeScript →
  180. compressed JS by mapping every token in the compiled JS to its original
  181. location.
  182. To use this feature pass `--source-map "content='/path/to/input/source.map'"`
  183. or `--source-map "content=inline"` if the source map is included inline with
  184. the sources.
  185. ## CLI compress options
  186. You need to pass `--compress` (`-c`) to enable the compressor. Optionally
  187. you can pass a comma-separated list of [compress options](#compress-options).
  188. Options are in the form `foo=bar`, or just `foo` (the latter implies
  189. a boolean option that you want to set `true`; it's effectively a
  190. shortcut for `foo=true`).
  191. Example:
  192. terser file.js -c toplevel,sequences=false
  193. ## CLI mangle options
  194. To enable the mangler you need to pass `--mangle` (`-m`). The following
  195. (comma-separated) options are supported:
  196. - `toplevel` (default `false`) -- mangle names declared in the top level scope.
  197. - `eval` (default `false`) -- mangle names visible in scopes where `eval` or `with` are used.
  198. When mangling is enabled but you want to prevent certain names from being
  199. mangled, you can declare those names with `--mangle reserved` — pass a
  200. comma-separated list of names. For example:
  201. terser ... -m reserved=['$','require','exports']
  202. to prevent the `require`, `exports` and `$` names from being changed.
  203. ### CLI mangling property names (`--mangle-props`)
  204. **Note:** THIS **WILL** BREAK YOUR CODE. A good rule of thumb is not to use this unless you know exactly what you're doing and how this works and read this section until the end.
  205. Mangling property names is a separate step, different from variable name mangling. Pass
  206. `--mangle-props` to enable it. The least dangerous
  207. way to use this is to use the `regex` option like so:
  208. ```
  209. terser example.js -c -m --mangle-props regex=/_$/
  210. ```
  211. This will mangle all properties that end with an
  212. underscore. So you can use it to mangle internal methods.
  213. By default, it will mangle all properties in the
  214. input code with the exception of built in DOM properties and properties
  215. in core JavaScript classes, which is what will break your code if you don't:
  216. 1. Control all the code you're mangling
  217. 2. Avoid using a module bundler, as they usually will call Terser on each file individually, making it impossible to pass mangled objects between modules.
  218. 3. Avoid calling functions like `defineProperty` or `hasOwnProperty`, because they refer to object properties using strings and will break your code if you don't know what you are doing.
  219. An example:
  220. ```javascript
  221. // example.js
  222. var x = {
  223. baz_: 0,
  224. foo_: 1,
  225. calc: function() {
  226. return this.foo_ + this.baz_;
  227. }
  228. };
  229. x.bar_ = 2;
  230. x["baz_"] = 3;
  231. console.log(x.calc());
  232. ```
  233. Mangle all properties (except for JavaScript `builtins`) (**very** unsafe):
  234. ```bash
  235. $ terser example.js -c passes=2 -m --mangle-props
  236. ```
  237. ```javascript
  238. var x={o:3,t:1,i:function(){return this.t+this.o},s:2};console.log(x.i());
  239. ```
  240. Mangle all properties except for `reserved` properties (still very unsafe):
  241. ```bash
  242. $ terser example.js -c passes=2 -m --mangle-props reserved=[foo_,bar_]
  243. ```
  244. ```javascript
  245. var x={o:3,foo_:1,t:function(){return this.foo_+this.o},bar_:2};console.log(x.t());
  246. ```
  247. Mangle all properties matching a `regex` (not as unsafe but still unsafe):
  248. ```bash
  249. $ terser example.js -c passes=2 -m --mangle-props regex=/_$/
  250. ```
  251. ```javascript
  252. var x={o:3,t:1,calc:function(){return this.t+this.o},i:2};console.log(x.calc());
  253. ```
  254. Combining mangle properties options:
  255. ```bash
  256. $ terser example.js -c passes=2 -m --mangle-props regex=/_$/,reserved=[bar_]
  257. ```
  258. ```javascript
  259. var x={o:3,t:1,calc:function(){return this.t+this.o},bar_:2};console.log(x.calc());
  260. ```
  261. In order for this to be of any use, we avoid mangling standard JS names and DOM
  262. API properties by default (`--mangle-props builtins` to override).
  263. A regular expression can be used to define which property names should be
  264. mangled. For example, `--mangle-props regex=/^_/` will only mangle property
  265. names that start with an underscore.
  266. When you compress multiple files using this option, in order for them to
  267. work together in the end we need to ensure somehow that one property gets
  268. mangled to the same name in all of them. For this, pass `--name-cache filename.json`
  269. and Terser will maintain these mappings in a file which can then be reused.
  270. It should be initially empty. Example:
  271. ```bash
  272. $ rm -f /tmp/cache.json # start fresh
  273. $ terser file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js
  274. $ terser file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js
  275. ```
  276. Now, `part1.js` and `part2.js` will be consistent with each other in terms
  277. of mangled property names.
  278. Using the name cache is not necessary if you compress all your files in a
  279. single call to Terser.
  280. ### Mangling unquoted names (`--mangle-props keep_quoted`)
  281. Using quoted property name (`o["foo"]`) reserves the property name (`foo`)
  282. so that it is not mangled throughout the entire script even when used in an
  283. unquoted style (`o.foo`). Example:
  284. ```javascript
  285. // stuff.js
  286. var o = {
  287. "foo": 1,
  288. bar: 3
  289. };
  290. o.foo += o.bar;
  291. console.log(o.foo);
  292. ```
  293. ```bash
  294. $ terser stuff.js --mangle-props keep_quoted -c -m
  295. ```
  296. ```javascript
  297. var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo);
  298. ```
  299. ### Debugging property name mangling
  300. You can also pass `--mangle-props debug` in order to mangle property names
  301. without completely obscuring them. For example the property `o.foo`
  302. would mangle to `o._$foo$_` with this option. This allows property mangling
  303. of a large codebase while still being able to debug the code and identify
  304. where mangling is breaking things.
  305. ```bash
  306. $ terser stuff.js --mangle-props debug -c -m
  307. ```
  308. ```javascript
  309. var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_);
  310. ```
  311. You can also pass a custom suffix using `--mangle-props debug=XYZ`. This would then
  312. mangle `o.foo` to `o._$foo$XYZ_`. You can change this each time you compile a
  313. script to identify how a property got mangled. One technique is to pass a
  314. random number on every compile to simulate mangling changing with different
  315. inputs (e.g. as you update the input script with new properties), and to help
  316. identify mistakes like writing mangled keys to storage.
  317. # API Reference
  318. Assuming installation via NPM, you can load Terser in your application
  319. like this:
  320. ```javascript
  321. var Terser = require("terser");
  322. ```
  323. Browser loading is also supported:
  324. ```html
  325. <script src="node_modules/source-map/dist/source-map.min.js"></script>
  326. <script src="dist/bundle.min.js"></script>
  327. ```
  328. There is a single high level function, **`minify(code, options)`**,
  329. which will perform all minification [phases](#minify-options) in a configurable
  330. manner. By default `minify()` will enable the options [`compress`](#compress-options)
  331. and [`mangle`](#mangle-options). Example:
  332. ```javascript
  333. var code = "function add(first, second) { return first + second; }";
  334. var result = Terser.minify(code);
  335. console.log(result.error); // runtime error, or `undefined` if no error
  336. console.log(result.code); // minified output: function add(n,d){return n+d}
  337. ```
  338. You can `minify` more than one JavaScript file at a time by using an object
  339. for the first argument where the keys are file names and the values are source
  340. code:
  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 result = Terser.minify(code);
  347. console.log(result.code);
  348. // function add(d,n){return d+n}console.log(add(3,7));
  349. ```
  350. The `toplevel` option:
  351. ```javascript
  352. var code = {
  353. "file1.js": "function add(first, second) { return first + second; }",
  354. "file2.js": "console.log(add(1 + 2, 3 + 4));"
  355. };
  356. var options = { toplevel: true };
  357. var result = Terser.minify(code, options);
  358. console.log(result.code);
  359. // console.log(3+7);
  360. ```
  361. The `nameCache` option:
  362. ```javascript
  363. var options = {
  364. mangle: {
  365. toplevel: true,
  366. },
  367. nameCache: {}
  368. };
  369. var result1 = Terser.minify({
  370. "file1.js": "function add(first, second) { return first + second; }"
  371. }, options);
  372. var result2 = Terser.minify({
  373. "file2.js": "console.log(add(1 + 2, 3 + 4));"
  374. }, options);
  375. console.log(result1.code);
  376. // function n(n,r){return n+r}
  377. console.log(result2.code);
  378. // console.log(n(3,7));
  379. ```
  380. You may persist the name cache to the file system in the following way:
  381. ```javascript
  382. var cacheFileName = "/tmp/cache.json";
  383. var options = {
  384. mangle: {
  385. properties: true,
  386. },
  387. nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8"))
  388. };
  389. fs.writeFileSync("part1.js", Terser.minify({
  390. "file1.js": fs.readFileSync("file1.js", "utf8"),
  391. "file2.js": fs.readFileSync("file2.js", "utf8")
  392. }, options).code, "utf8");
  393. fs.writeFileSync("part2.js", Terser.minify({
  394. "file3.js": fs.readFileSync("file3.js", "utf8"),
  395. "file4.js": fs.readFileSync("file4.js", "utf8")
  396. }, options).code, "utf8");
  397. fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8");
  398. ```
  399. An example of a combination of `minify()` options:
  400. ```javascript
  401. var code = {
  402. "file1.js": "function add(first, second) { return first + second; }",
  403. "file2.js": "console.log(add(1 + 2, 3 + 4));"
  404. };
  405. var options = {
  406. toplevel: true,
  407. compress: {
  408. global_defs: {
  409. "@console.log": "alert"
  410. },
  411. passes: 2
  412. },
  413. output: {
  414. beautify: false,
  415. preamble: "/* minified */"
  416. }
  417. };
  418. var result = Terser.minify(code, options);
  419. console.log(result.code);
  420. // /* minified */
  421. // alert(10);"
  422. ```
  423. To produce warnings:
  424. ```javascript
  425. var code = "function f(){ var u; return 2 + 3; }";
  426. var options = { warnings: true };
  427. var result = Terser.minify(code, options);
  428. console.log(result.error); // runtime error, `undefined` in this case
  429. console.log(result.warnings); // [ 'Dropping unused variable u [0:1,18]' ]
  430. console.log(result.code); // function f(){return 5}
  431. ```
  432. An error example:
  433. ```javascript
  434. var result = Terser.minify({"foo.js" : "if (0) else console.log(1);"});
  435. console.log(JSON.stringify(result.error));
  436. // {"message":"Unexpected token: keyword (else)","filename":"foo.js","line":1,"col":7,"pos":7}
  437. ```
  438. Note: unlike `uglify-js@2.x`, the Terser API does not throw errors.
  439. To achieve a similar effect one could do the following:
  440. ```javascript
  441. var result = Terser.minify(code, options);
  442. if (result.error) throw result.error;
  443. ```
  444. ## Minify options
  445. - `ecma` (default `undefined`) - pass `5`, `2015`, `2016`, etc to override `parse`,
  446. `compress` and `output`'s `ecma` options.
  447. - `warnings` (default `false`) — pass `true` to return compressor warnings
  448. in `result.warnings`. Use the value `"verbose"` for more detailed warnings.
  449. - `parse` (default `{}`) — pass an object if you wish to specify some
  450. additional [parse options](#parse-options).
  451. - `compress` (default `{}`) — pass `false` to skip compressing entirely.
  452. Pass an object to specify custom [compress options](#compress-options).
  453. - `mangle` (default `true`) — pass `false` to skip mangling names, or pass
  454. an object to specify [mangle options](#mangle-options) (see below).
  455. - `mangle.properties` (default `false`) — a subcategory of the mangle option.
  456. Pass an object to specify custom [mangle property options](#mangle-properties-options).
  457. - `module` (default `false`) — Use when minifying an ES6 module. "use strict"
  458. is implied and names can be mangled on the top scope. If `compress` or
  459. `mangle` is enabled then the `toplevel` option will be enabled.
  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. - `sourceMap` (default `false`) - pass an object if you wish to specify
  464. [source map options](#source-map-options).
  465. - `toplevel` (default `false`) - set to `true` if you wish to enable top level
  466. variable and function name mangling and to drop unused variables and functions.
  467. - `nameCache` (default `null`) - pass an empty object `{}` or a previously
  468. used `nameCache` object if you wish to cache mangled variable and
  469. property names across multiple invocations of `minify()`. Note: this is
  470. a read/write property. `minify()` will read the name cache state of this
  471. object and update it during minification so that it may be
  472. reused or externally persisted by the user.
  473. - `ie8` (default `false`) - set to `true` to support IE8.
  474. - `keep_classnames` (default: `undefined`) - pass `true` to prevent discarding or mangling
  475. of class names. Pass a regular expression to only keep class names matching that regex.
  476. - `keep_fnames` (default: `false`) - pass `true` to prevent discarding or mangling
  477. of function names. Pass a regular expression to only keep class names matching that regex.
  478. Useful for code relying on `Function.prototype.name`. If the top level minify option
  479. `keep_classnames` is `undefined` it will be overridden with the value of the top level
  480. minify option `keep_fnames`.
  481. - `safari10` (default: `false`) - pass `true` to work around Safari 10/11 bugs in
  482. loop scoping and `await`. See `safari10` options in [`mangle`](#mangle-options)
  483. and [`output`](#output-options) for details.
  484. ## Minify options structure
  485. ```javascript
  486. {
  487. parse: {
  488. // parse options
  489. },
  490. compress: {
  491. // compress options
  492. },
  493. mangle: {
  494. // mangle options
  495. properties: {
  496. // mangle property options
  497. }
  498. },
  499. output: {
  500. // output options
  501. },
  502. sourceMap: {
  503. // source map options
  504. },
  505. ecma: 5, // specify one of: 5, 2015, 2016, etc.
  506. keep_classnames: false,
  507. keep_fnames: false,
  508. ie8: false,
  509. module: false,
  510. nameCache: null, // or specify a name cache object
  511. safari10: false,
  512. toplevel: false,
  513. warnings: false,
  514. }
  515. ```
  516. ### Source map options
  517. To generate a source map:
  518. ```javascript
  519. var result = Terser.minify({"file1.js": "var a = function() {};"}, {
  520. sourceMap: {
  521. filename: "out.js",
  522. url: "out.js.map"
  523. }
  524. });
  525. console.log(result.code); // minified output
  526. console.log(result.map); // source map
  527. ```
  528. Note that the source map is not saved in a file, it's just returned in
  529. `result.map`. The value passed for `sourceMap.url` is only used to set
  530. `//# sourceMappingURL=out.js.map` in `result.code`. The value of
  531. `filename` is only used to set `file` attribute (see [the spec][sm-spec])
  532. in source map file.
  533. You can set option `sourceMap.url` to be `"inline"` and source map will
  534. be appended to code.
  535. You can also specify sourceRoot property to be included in source map:
  536. ```javascript
  537. var result = Terser.minify({"file1.js": "var a = function() {};"}, {
  538. sourceMap: {
  539. root: "http://example.com/src",
  540. url: "out.js.map"
  541. }
  542. });
  543. ```
  544. If you're compressing compiled JavaScript and have a source map for it, you
  545. can use `sourceMap.content`:
  546. ```javascript
  547. var result = Terser.minify({"compiled.js": "compiled code"}, {
  548. sourceMap: {
  549. content: "content from compiled.js.map",
  550. url: "minified.js.map"
  551. }
  552. });
  553. // same as before, it returns `code` and `map`
  554. ```
  555. If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.url`.
  556. If you happen to need the source map as a raw object, set `sourceMap.asObject` to `true`.
  557. ## Parse options
  558. - `bare_returns` (default `false`) -- support top level `return` statements
  559. - `ecma` (default: `2017`) -- specify one of `5`, `2015`, `2016` or `2017`. Note: this setting
  560. is not presently enforced except for ES8 optional trailing commas in function
  561. parameter lists and calls with `ecma` `2017`.
  562. - `html5_comments` (default `true`)
  563. - `shebang` (default `true`) -- support `#!command` as the first line
  564. ## Compress options
  565. - `defaults` (default: `true`) -- Pass `false` to disable most default
  566. enabled `compress` transforms. Useful when you only want to enable a few
  567. `compress` options while disabling the rest.
  568. - `arrows` (default: `true`) -- Class and object literal methods are converted
  569. will also be converted to arrow expressions if the resultant code is shorter:
  570. `m(){return x}` becomes `m:()=>x`. To do this to regular ES5 functions which
  571. don't use `this` or `arguments`, see `unsafe_arrows`.
  572. - `arguments` (default: `false`) -- replace `arguments[index]` with function
  573. parameter name whenever possible.
  574. - `booleans` (default: `true`) -- various optimizations for boolean context,
  575. for example `!!a ? b : c → a ? b : c`
  576. - `booleans_as_integers` (default: `false`) -- Turn booleans into 0 and 1, also
  577. makes comparisons with booleans use `==` and `!=` instead of `===` and `!==`.
  578. - `collapse_vars` (default: `true`) -- Collapse single-use non-constant variables,
  579. side effects permitting.
  580. - `comparisons` (default: `true`) -- apply certain optimizations to binary nodes,
  581. e.g. `!(a <= b) → a > b` (only when `unsafe_comps`), attempts to negate binary
  582. nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc.
  583. - `computed_props` (default: `true`) -- Transforms constant computed properties
  584. into regular ones: `{["computed"]: 1}` is converted to `{computed: 1}`.
  585. - `conditionals` (default: `true`) -- apply optimizations for `if`-s and conditional
  586. expressions
  587. - `dead_code` (default: `true`) -- remove unreachable code
  588. - `directives` (default: `true`) -- remove redundant or non-standard directives
  589. - `drop_console` (default: `false`) -- Pass `true` to discard calls to
  590. `console.*` functions. If you wish to drop a specific function call
  591. such as `console.info` and/or retain side effects from function arguments
  592. after dropping the function call then use `pure_funcs` instead.
  593. - `drop_debugger` (default: `true`) -- remove `debugger;` statements
  594. - `ecma` (default: `5`) -- Pass `2015` or greater to enable `compress` options that
  595. will transform ES5 code into smaller ES6+ equivalent forms.
  596. - `evaluate` (default: `true`) -- attempt to evaluate constant expressions
  597. - `expression` (default: `false`) -- Pass `true` to preserve completion values
  598. from terminal statements without `return`, e.g. in bookmarklets.
  599. - `global_defs` (default: `{}`) -- see [conditional compilation](#conditional-compilation)
  600. - `hoist_funs` (default: `false`) -- hoist function declarations
  601. - `hoist_props` (default: `true`) -- hoist properties from constant object and
  602. array literals into regular variables subject to a set of constraints. For example:
  603. `var o={p:1, q:2}; f(o.p, o.q);` is converted to `f(1, 2);`. Note: `hoist_props`
  604. works best with `mangle` enabled, the `compress` option `passes` set to `2` or higher,
  605. and the `compress` option `toplevel` enabled.
  606. - `hoist_vars` (default: `false`) -- hoist `var` declarations (this is `false`
  607. by default because it seems to increase the size of the output in general)
  608. - `if_return` (default: `true`) -- optimizations for if/return and if/continue
  609. - `inline` (default: `true`) -- inline calls to function with simple/`return` statement:
  610. - `false` -- same as `0`
  611. - `0` -- disabled inlining
  612. - `1` -- inline simple functions
  613. - `2` -- inline functions with arguments
  614. - `3` -- inline functions with arguments and variables
  615. - `true` -- same as `3`
  616. - `join_vars` (default: `true`) -- join consecutive `var` statements
  617. - `keep_classnames` (default: `false`) -- Pass `true` to prevent the compressor from
  618. discarding class names. Pass a regular expression to only keep class names matching
  619. that regex. See also: the `keep_classnames` [mangle option](#mangle).
  620. - `keep_fargs` (default: `true`) -- Prevents the compressor from discarding unused
  621. function arguments. You need this for code which relies on `Function.length`.
  622. - `keep_fnames` (default: `false`) -- Pass `true` to prevent the
  623. compressor from discarding function names. Pass a regular expression to only keep
  624. function names matching that regex. Useful for code relying on `Function.prototype.name`.
  625. See also: the `keep_fnames` [mangle option](#mangle).
  626. - `keep_infinity` (default: `false`) -- Pass `true` to prevent `Infinity` from
  627. being compressed into `1/0`, which may cause performance issues on Chrome.
  628. - `loops` (default: `true`) -- optimizations for `do`, `while` and `for` loops
  629. when we can statically determine the condition.
  630. - `module` (default `false`) -- Pass `true` when compressing an ES6 module. Strict
  631. mode is implied and the `toplevel` option as well.
  632. - `negate_iife` (default: `true`) -- negate "Immediately-Called Function Expressions"
  633. where the return value is discarded, to avoid the parens that the
  634. code generator would insert.
  635. - `passes` (default: `1`) -- The maximum number of times to run compress.
  636. In some cases more than one pass leads to further compressed code. Keep in
  637. mind more passes will take more time.
  638. - `properties` (default: `true`) -- rewrite property access using the dot notation, for
  639. example `foo["bar"] → foo.bar`
  640. - `pure_funcs` (default: `null`) -- You can pass an array of names and
  641. Terser will assume that those functions do not produce side
  642. effects. DANGER: will not check if the name is redefined in scope.
  643. An example case here, for instance `var q = Math.floor(a/b)`. If
  644. variable `q` is not used elsewhere, Terser will drop it, but will
  645. still keep the `Math.floor(a/b)`, not knowing what it does. You can
  646. pass `pure_funcs: [ 'Math.floor' ]` to let it know that this
  647. function won't produce any side effect, in which case the whole
  648. statement would get discarded. The current implementation adds some
  649. overhead (compression will be slower).
  650. - `pure_getters` (default: `"strict"`) -- If you pass `true` for
  651. this, Terser will assume that object property access
  652. (e.g. `foo.bar` or `foo["bar"]`) doesn't have any side effects.
  653. Specify `"strict"` to treat `foo.bar` as side-effect-free only when
  654. `foo` is certain to not throw, i.e. not `null` or `undefined`.
  655. - `reduce_funcs` (legacy option, safely ignored for backwards compatibility).
  656. - `reduce_vars` (default: `true`) -- Improve optimization on variables assigned with and
  657. used as constant values.
  658. - `sequences` (default: `true`) -- join consecutive simple statements using the
  659. comma operator. May be set to a positive integer to specify the maximum number
  660. of consecutive comma sequences that will be generated. If this option is set to
  661. `true` then the default `sequences` limit is `200`. Set option to `false` or `0`
  662. to disable. The smallest `sequences` length is `2`. A `sequences` value of `1`
  663. is grandfathered to be equivalent to `true` and as such means `200`. On rare
  664. occasions the default sequences limit leads to very slow compress times in which
  665. case a value of `20` or less is recommended.
  666. - `side_effects` (default: `true`) -- Pass `false` to disable potentially dropping
  667. function calls marked as "pure". A function call is marked as "pure" if a comment
  668. annotation `/*@__PURE__*/` or `/*#__PURE__*/` immediately precedes the call. For
  669. example: `/*@__PURE__*/foo();`
  670. - `switches` (default: `true`) -- de-duplicate and remove unreachable `switch` branches
  671. - `toplevel` (default: `false`) -- drop unreferenced functions (`"funcs"`) and/or
  672. variables (`"vars"`) in the top level scope (`false` by default, `true` to drop
  673. both unreferenced functions and variables)
  674. - `top_retain` (default: `null`) -- prevent specific toplevel functions and
  675. variables from `unused` removal (can be array, comma-separated, RegExp or
  676. function. Implies `toplevel`)
  677. - `typeofs` (default: `true`) -- Transforms `typeof foo == "undefined"` into
  678. `foo === void 0`. Note: recommend to set this value to `false` for IE10 and
  679. earlier versions due to known issues.
  680. - `unsafe` (default: `false`) -- apply "unsafe" transformations
  681. ([details](#the-unsafe-compress-option)).
  682. - `unsafe_arrows` (default: `false`) -- Convert ES5 style anonymous function
  683. expressions to arrow functions if the function body does not reference `this`.
  684. Note: it is not always safe to perform this conversion if code relies on the
  685. the function having a `prototype`, which arrow functions lack.
  686. This transform requires that the `ecma` compress option is set to `2015` or greater.
  687. - `unsafe_comps` (default: `false`) -- Reverse `<` and `<=` to `>` and `>=` to
  688. allow improved compression. This might be unsafe when an at least one of two
  689. operands is an object with computed values due the use of methods like `get`,
  690. or `valueOf`. This could cause change in execution order after operands in the
  691. comparison are switching. Compression only works if both `comparisons` and
  692. `unsafe_comps` are both set to true.
  693. - `unsafe_Function` (default: `false`) -- compress and mangle `Function(args, code)`
  694. when both `args` and `code` are string literals.
  695. - `unsafe_math` (default: `false`) -- optimize numerical expressions like
  696. `2 * x * 3` into `6 * x`, which may give imprecise floating point results.
  697. - `unsafe_symbols` (default: `false`) -- removes keys from native Symbol
  698. declarations, e.g `Symbol("kDog")` becomes `Symbol()`.
  699. - `unsafe_methods` (default: false) -- Converts `{ m: function(){} }` to
  700. `{ m(){} }`. `ecma` must be set to `6` or greater to enable this transform.
  701. If `unsafe_methods` is a RegExp then key/value pairs with keys matching the
  702. RegExp will be converted to concise methods.
  703. Note: if enabled there is a risk of getting a "`<method name>` is not a
  704. constructor" TypeError should any code try to `new` the former function.
  705. - `unsafe_proto` (default: `false`) -- optimize expressions like
  706. `Array.prototype.slice.call(a)` into `[].slice.call(a)`
  707. - `unsafe_regexp` (default: `false`) -- enable substitutions of variables with
  708. `RegExp` values the same way as if they are constants.
  709. - `unsafe_undefined` (default: `false`) -- substitute `void 0` if there is a
  710. variable named `undefined` in scope (variable name will be mangled, typically
  711. reduced to a single character)
  712. - `unused` (default: `true`) -- drop unreferenced functions and variables (simple
  713. direct variable assignments do not count as references unless set to `"keep_assign"`)
  714. - `warnings` (default: `false`) -- display warnings when dropping unreachable
  715. code or unused declarations etc.
  716. ## Mangle options
  717. - `eval` (default `false`) -- Pass `true` to mangle names visible in scopes
  718. where `eval` or `with` are used.
  719. - `keep_classnames` (default `false`) -- Pass `true` to not mangle class names.
  720. Pass a regular expression to only keep class names matching that regex.
  721. See also: the `keep_classnames` [compress option](#compress-options).
  722. - `keep_fnames` (default `false`) -- Pass `true` to not mangle function names.
  723. Pass a regular expression to only keep class names matching that regex.
  724. Useful for code relying on `Function.prototype.name`. See also: the `keep_fnames`
  725. [compress option](#compress-options).
  726. - `module` (default `false`) -- Pass `true` an ES6 modules, where the toplevel
  727. scope is not the global scope. Implies `toplevel`.
  728. - `reserved` (default `[]`) -- Pass an array of identifiers that should be
  729. excluded from mangling. Example: `["foo", "bar"]`.
  730. - `toplevel` (default `false`) -- Pass `true` to mangle names declared in the
  731. top level scope.
  732. - `safari10` (default `false`) -- Pass `true` to work around the Safari 10 loop
  733. iterator [bug](https://bugs.webkit.org/show_bug.cgi?id=171041)
  734. "Cannot declare a let variable twice".
  735. See also: the `safari10` [output option](#output-options).
  736. Examples:
  737. ```javascript
  738. // test.js
  739. var globalVar;
  740. function funcName(firstLongName, anotherLongName) {
  741. var myVariable = firstLongName + anotherLongName;
  742. }
  743. ```
  744. ```javascript
  745. var code = fs.readFileSync("test.js", "utf8");
  746. Terser.minify(code).code;
  747. // 'function funcName(a,n){}var globalVar;'
  748. Terser.minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
  749. // 'function funcName(firstLongName,a){}var globalVar;'
  750. Terser.minify(code, { mangle: { toplevel: true } }).code;
  751. // 'function n(n,a){}var a;'
  752. ```
  753. ### Mangle properties options
  754. - `builtins` (default: `false`) — Use `true` to allow the mangling of builtin
  755. DOM properties. Not recommended to override this setting.
  756. - `debug` (default: `false`) — Mangle names with the original name still present.
  757. Pass an empty string `""` to enable, or a non-empty string to set the debug suffix.
  758. - `keep_quoted` (default: `false`) — Only mangle unquoted property names.
  759. - `true` -- Quoted property names are automatically reserved and any unquoted
  760. property names will not be mangled.
  761. - `"strict"` -- Advanced, all unquoted property names are mangled unless
  762. explicitly reserved.
  763. - `regex` (default: `null`) — Pass a [RegExp literal or pattern string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to only mangle property matching the regular expression.
  764. - `reserved` (default: `[]`) — Do not mangle property names listed in the
  765. `reserved` array.
  766. - `undeclared` (default: `false`) - Mangle those names when they are accessed
  767. as properties of known top level variables but their declarations are never
  768. found in input code. May be useful when only minifying parts of a project.
  769. See [#397](https://github.com/terser/terser/issues/397) for more details.
  770. ## Output options
  771. The code generator tries to output shortest code possible by default. In
  772. case you want beautified output, pass `--beautify` (`-b`). Optionally you
  773. can pass additional arguments that control the code output:
  774. - `ascii_only` (default `false`) -- escape Unicode characters in strings and
  775. regexps (affects directives with non-ascii characters becoming invalid)
  776. - `beautify` (default `true`) -- whether to actually beautify the output.
  777. Passing `-b` will set this to true, but you might need to pass `-b` even
  778. when you want to generate minified code, in order to specify additional
  779. arguments, so you can use `-b beautify=false` to override it.
  780. - `braces` (default `false`) -- always insert braces in `if`, `for`,
  781. `do`, `while` or `with` statements, even if their body is a single
  782. statement.
  783. - `comments` (default `"some"`) -- by default it keeps JSDoc-style comments
  784. that contain "@license" or "@preserve", pass `true` or `"all"` to preserve all
  785. comments, `false` to omit comments in the output, a regular expression string
  786. (e.g. `/^!/`) or a function.
  787. - `ecma` (default `5`) -- set output printing mode. Set `ecma` to `2015` or
  788. greater to emit shorthand object properties - i.e.: `{a}` instead of `{a: a}`.
  789. The `ecma` option will only change the output in direct control of the
  790. beautifier. Non-compatible features in the abstract syntax tree will still
  791. be output as is. For example: an `ecma` setting of `5` will **not** convert
  792. ES6+ code to ES5.
  793. - `indent_level` (default `4`)
  794. - `indent_start` (default `0`) -- prefix all lines by that many spaces
  795. - `inline_script` (default `true`) -- escape HTML comments and the slash in
  796. occurrences of `</script>` in strings
  797. - `keep_numbers` (default `false`) -- keep number literals as it was in original code
  798. (disables optimizations like converting `1000000` into `1e6`)
  799. - `keep_quoted_props` (default `false`) -- when turned on, prevents stripping
  800. quotes from property names in object literals.
  801. - `max_line_len` (default `false`) -- maximum line length (for minified code)
  802. - `preamble` (default `null`) -- when passed it must be a string and
  803. it will be prepended to the output literally. The source map will
  804. adjust for this text. Can be used to insert a comment containing
  805. licensing information, for example.
  806. - `quote_keys` (default `false`) -- pass `true` to quote all keys in literal
  807. objects
  808. - `quote_style` (default `0`) -- preferred quote style for strings (affects
  809. quoted property names and directives as well):
  810. - `0` -- prefers double quotes, switches to single quotes when there are
  811. more double quotes in the string itself. `0` is best for gzip size.
  812. - `1` -- always use single quotes
  813. - `2` -- always use double quotes
  814. - `3` -- always use the original quotes
  815. - `preserve_annotations` -- (default `false`) -- Preserve [Terser annotations](#annotations) in the output.
  816. - `safari10` (default `false`) -- set this option to `true` to work around
  817. the [Safari 10/11 await bug](https://bugs.webkit.org/show_bug.cgi?id=176685).
  818. See also: the `safari10` [mangle option](#mangle-options).
  819. - `semicolons` (default `true`) -- separate statements with semicolons. If
  820. you pass `false` then whenever possible we will use a newline instead of a
  821. semicolon, leading to more readable output of minified code (size before
  822. gzip could be smaller; size after gzip insignificantly larger).
  823. - `shebang` (default `true`) -- preserve shebang `#!` in preamble (bash scripts)
  824. - `webkit` (default `false`) -- enable workarounds for WebKit bugs.
  825. PhantomJS users should set this option to `true`.
  826. - `wrap_iife` (default `false`) -- pass `true` to wrap immediately invoked
  827. function expressions. See
  828. [#640](https://github.com/mishoo/UglifyJS2/issues/640) for more details.
  829. - `wrap_func_args` (default `true`) -- pass `false` if you do not want to wrap
  830. function expressions that are passed as arguments, in parenthesis. See
  831. [OptimizeJS](https://github.com/nolanlawson/optimize-js) for more details.
  832. # Miscellaneous
  833. ### Keeping copyright notices or other comments
  834. You can pass `--comments` to retain certain comments in the output. By
  835. default it will keep JSDoc-style comments that contain "@preserve",
  836. "@license" or "@cc_on" (conditional compilation for IE). You can pass
  837. `--comments all` to keep all the comments, or a valid JavaScript regexp to
  838. keep only comments that match this regexp. For example `--comments /^!/`
  839. will keep comments like `/*! Copyright Notice */`.
  840. Note, however, that there might be situations where comments are lost. For
  841. example:
  842. ```javascript
  843. function f() {
  844. /** @preserve Foo Bar */
  845. function g() {
  846. // this function is never called
  847. }
  848. return something();
  849. }
  850. ```
  851. Even though it has "@preserve", the comment will be lost because the inner
  852. function `g` (which is the AST node to which the comment is attached to) is
  853. discarded by the compressor as not referenced.
  854. The safest comments where to place copyright information (or other info that
  855. needs to be kept in the output) are comments attached to toplevel nodes.
  856. ### The `unsafe` `compress` option
  857. It enables some transformations that *might* break code logic in certain
  858. contrived cases, but should be fine for most code. It assumes that standard
  859. built-in ECMAScript functions and classes have not been altered or replaced.
  860. You might want to try it on your own code; it should reduce the minified size.
  861. Some examples of the optimizations made when this option is enabled:
  862. - `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[ 1, 2, 3 ]`
  863. - `new Object()` → `{}`
  864. - `String(exp)` or `exp.toString()` → `"" + exp`
  865. - `new Object/RegExp/Function/Error/Array (...)` → we discard the `new`
  866. - `"foo bar".substr(4)` → `"bar"`
  867. ### Conditional compilation
  868. You can use the `--define` (`-d`) switch in order to declare global
  869. variables that Terser will assume to be constants (unless defined in
  870. scope). For example if you pass `--define DEBUG=false` then, coupled with
  871. dead code removal Terser will discard the following from the output:
  872. ```javascript
  873. if (DEBUG) {
  874. console.log("debug stuff");
  875. }
  876. ```
  877. You can specify nested constants in the form of `--define env.DEBUG=false`.
  878. Terser will warn about the condition being always false and about dropping
  879. unreachable code; for now there is no option to turn off only this specific
  880. warning, you can pass `warnings=false` to turn off *all* warnings.
  881. Another way of doing that is to declare your globals as constants in a
  882. separate file and include it into the build. For example you can have a
  883. `build/defines.js` file with the following:
  884. ```javascript
  885. var DEBUG = false;
  886. var PRODUCTION = true;
  887. // etc.
  888. ```
  889. and build your code like this:
  890. terser build/defines.js js/foo.js js/bar.js... -c
  891. Terser will notice the constants and, since they cannot be altered, it
  892. will evaluate references to them to the value itself and drop unreachable
  893. code as usual. The build will contain the `const` declarations if you use
  894. them. If you are targeting < ES6 environments which does not support `const`,
  895. using `var` with `reduce_vars` (enabled by default) should suffice.
  896. ### Conditional compilation API
  897. You can also use conditional compilation via the programmatic API. With the difference that the
  898. property name is `global_defs` and is a compressor property:
  899. ```javascript
  900. var result = Terser.minify(fs.readFileSync("input.js", "utf8"), {
  901. compress: {
  902. dead_code: true,
  903. global_defs: {
  904. DEBUG: false
  905. }
  906. }
  907. });
  908. ```
  909. To replace an identifier with an arbitrary non-constant expression it is
  910. necessary to prefix the `global_defs` key with `"@"` to instruct Terser
  911. to parse the value as an expression:
  912. ```javascript
  913. Terser.minify("alert('hello');", {
  914. compress: {
  915. global_defs: {
  916. "@alert": "console.log"
  917. }
  918. }
  919. }).code;
  920. // returns: 'console.log("hello");'
  921. ```
  922. Otherwise it would be replaced as string literal:
  923. ```javascript
  924. Terser.minify("alert('hello');", {
  925. compress: {
  926. global_defs: {
  927. "alert": "console.log"
  928. }
  929. }
  930. }).code;
  931. // returns: '"console.log"("hello");'
  932. ```
  933. ### Using native Terser AST with `minify()`
  934. ```javascript
  935. // example: parse only, produce native Terser AST
  936. var result = Terser.minify(code, {
  937. parse: {},
  938. compress: false,
  939. mangle: false,
  940. output: {
  941. ast: true,
  942. code: false // optional - faster if false
  943. }
  944. });
  945. // result.ast contains native Terser AST
  946. ```
  947. ```javascript
  948. // example: accept native Terser AST input and then compress and mangle
  949. // to produce both code and native AST.
  950. var result = Terser.minify(ast, {
  951. compress: {},
  952. mangle: {},
  953. output: {
  954. ast: true,
  955. code: true // optional - faster if false
  956. }
  957. });
  958. // result.ast contains native Terser AST
  959. // result.code contains the minified code in string form.
  960. ```
  961. ### Annotations
  962. Annotations in Terser are a way to tell it to treat a certain function call differently. The following annotations are available:
  963. * `/*@__INLINE__*/` - forces a function to be inlined somewhere.
  964. * `/*@__NOINLINE__*/` - Makes sure the called function is not inlined into the call site.
  965. * `/*@__PURE__*/` - Marks a function call as pure. That means, it can safely be dropped.
  966. You can use either a `@` sign at the start, or a `#`.
  967. Here are some examples on how to use them:
  968. ```javascript
  969. /*@__INLINE__*/
  970. function_always_inlined_here()
  971. /*#__NOINLINE__*/
  972. function_cant_be_inlined_into_here()
  973. const x = /*#__PURE__*/i_am_dropped_if_x_is_not_used()
  974. ```
  975. ### Working with Terser AST
  976. Traversal and transformation of the native AST can be performed through
  977. [`TreeWalker`](https://github.com/fabiosantoscode/terser/blob/master/lib/ast.js) and
  978. [`TreeTransformer`](https://github.com/fabiosantoscode/terser/blob/master/lib/transform.js)
  979. respectively.
  980. Largely compatible native AST examples can be found in the original UglifyJS
  981. documentation. See: [tree walker](http://lisperator.net/uglifyjs/walk) and
  982. [tree transform](http://lisperator.net/uglifyjs/transform).
  983. ### ESTree / SpiderMonkey AST
  984. Terser has its own abstract syntax tree format; for
  985. [practical reasons](http://lisperator.net/blog/uglifyjs-why-not-switching-to-spidermonkey-ast/)
  986. we can't easily change to using the SpiderMonkey AST internally. However,
  987. Terser now has a converter which can import a SpiderMonkey AST.
  988. For example [Acorn][acorn] is a super-fast parser that produces a
  989. SpiderMonkey AST. It has a small CLI utility that parses one file and dumps
  990. the AST in JSON on the standard output. To use Terser to mangle and
  991. compress that:
  992. acorn file.js | terser -p spidermonkey -m -c
  993. The `-p spidermonkey` option tells Terser that all input files are not
  994. JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we
  995. don't use our own parser in this case, but just transform that AST into our
  996. internal AST.
  997. ### Use Acorn for parsing
  998. More for fun, I added the `-p acorn` option which will use Acorn to do all
  999. the parsing. If you pass this option, Terser will `require("acorn")`.
  1000. Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but
  1001. converting the SpiderMonkey tree that Acorn produces takes another 150ms so
  1002. in total it's a bit more than just using Terser's own parser.
  1003. [acorn]: https://github.com/ternjs/acorn
  1004. [sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k
  1005. ### Terser Fast Minify Mode
  1006. It's not well known, but whitespace removal and symbol mangling accounts
  1007. for 95% of the size reduction in minified code for most JavaScript - not
  1008. elaborate code transforms. One can simply disable `compress` to speed up
  1009. Terser builds by 3 to 4 times.
  1010. | d3.js | size | gzip size | time (s) |
  1011. | --- | ---: | ---: | ---: |
  1012. | original | 451,131 | 108,733 | - |
  1013. | terser@3.7.5 mangle=false, compress=false | 316,600 | 85,245 | 0.82 |
  1014. | terser@3.7.5 mangle=true, compress=false | 220,216 | 72,730 | 1.45 |
  1015. | terser@3.7.5 mangle=true, compress=true | 212,046 | 70,954 | 5.87 |
  1016. | babili@0.1.4 | 210,713 | 72,140 | 12.64 |
  1017. | babel-minify@0.4.3 | 210,321 | 72,242 | 48.67 |
  1018. | babel-minify@0.5.0-alpha.01eac1c3 | 210,421 | 72,238 | 14.17 |
  1019. To enable fast minify mode from the CLI use:
  1020. ```
  1021. terser file.js -m
  1022. ```
  1023. To enable fast minify mode with the API use:
  1024. ```js
  1025. Terser.minify(code, { compress: false, mangle: true });
  1026. ```
  1027. #### Source maps and debugging
  1028. Various `compress` transforms that simplify, rearrange, inline and remove code
  1029. are known to have an adverse effect on debugging with source maps. This is
  1030. expected as code is optimized and mappings are often simply not possible as
  1031. some code no longer exists. For highest fidelity in source map debugging
  1032. disable the `compress` option and just use `mangle`.
  1033. ### Compiler assumptions
  1034. To allow for better optimizations, the compiler makes various assumptions:
  1035. - `.toString()` and `.valueOf()` don't have side effects, and for built-in
  1036. objects they have not been overridden.
  1037. - `undefined`, `NaN` and `Infinity` have not been externally redefined.
  1038. - `arguments.callee`, `arguments.caller` and `Function.prototype.caller` are not used.
  1039. - The code doesn't expect the contents of `Function.prototype.toString()` or
  1040. `Error.prototype.stack` to be anything in particular.
  1041. - Getting and setting properties on a plain object does not cause other side effects
  1042. (using `.watch()` or `Proxy`).
  1043. - Object properties can be added, removed and modified (not prevented with
  1044. `Object.defineProperty()`, `Object.defineProperties()`, `Object.freeze()`,
  1045. `Object.preventExtensions()` or `Object.seal()`).
  1046. - `document.all` is not `== null`
  1047. - Assigning properties to a class doesn't have side effects and does not throw.
  1048. ### Build Tools and Adaptors using Terser
  1049. https://www.npmjs.com/browse/depended/terser
  1050. ### Replacing `uglify-es` with `terser` in a project using `yarn`
  1051. A number of JS bundlers and uglify wrappers are still using buggy versions
  1052. of `uglify-es` and have not yet upgraded to `terser`. If you are using `yarn`
  1053. you can add the following alias to your project's `package.json` file:
  1054. ```js
  1055. "resolutions": {
  1056. "uglify-es": "npm:terser"
  1057. }
  1058. ```
  1059. to use `terser` instead of `uglify-es` in all deeply nested dependencies
  1060. without changing any code.
  1061. Note: for this change to take effect you must run the following commands
  1062. to remove the existing `yarn` lock file and reinstall all packages:
  1063. ```
  1064. $ rm -rf node_modules yarn.lock
  1065. $ yarn
  1066. ```
  1067. # Reporting issues
  1068. In the terser CLI we use [source-map-support](https://npmjs.com/source-map-support) to produce good error stacks. In your own app, you're expected to enable source-map-support (read their docs) to have nice stack traces that will make good issues.
  1069. # README.md Patrons:
  1070. *note*: You can support this project on patreon: <a target="_blank" rel="nofollow" href="https://www.patreon.com/fabiosantoscode"><img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" alt="patron" width="100px" height="auto"></a>. Check out [PATRONS.md](https://github.com/terser/terser/blob/master/PATRONS.md) for our first-tier patrons.
  1071. These are the second-tier patrons. Great thanks for your support!
  1072. * CKEditor ![](https://c10.patreonusercontent.com/3/eyJoIjoxMDAsInciOjEwMH0%3D/patreon-media/p/user/15452278/f8548dcf48d740619071e8d614459280/1?token-time=2145916800&token-hash=SIQ54PhIPHv3M7CVz9LxS8_8v4sOw4H304HaXsXj8MM%3D)
  1073. * 38elements ![](https://c10.patreonusercontent.com/3/eyJ3IjoyMDB9/patreon-media/p/user/12501844/88e7fc5dd62d45c6a5626533bbd48cfb/1?token-time=2145916800&token-hash=c3AsQ5T0IQWic0zKxFHu-bGGQJkXQFvafvJ4bPerFR4%3D)
  1074. ## Contributors
  1075. ### Code Contributors
  1076. This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
  1077. <a href="https://github.com/terser/terser/graphs/contributors"><img src="https://opencollective.com/terser/contributors.svg?width=890&button=false" /></a>
  1078. ### Financial Contributors
  1079. Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/terser/contribute)]
  1080. #### Individuals
  1081. <a href="https://opencollective.com/terser"><img src="https://opencollective.com/terser/individuals.svg?width=890"></a>
  1082. #### Organizations
  1083. Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/terser/contribute)]
  1084. <a href="https://opencollective.com/terser/organization/0/website"><img src="https://opencollective.com/terser/organization/0/avatar.svg"></a>
  1085. <a href="https://opencollective.com/terser/organization/1/website"><img src="https://opencollective.com/terser/organization/1/avatar.svg"></a>
  1086. <a href="https://opencollective.com/terser/organization/2/website"><img src="https://opencollective.com/terser/organization/2/avatar.svg"></a>
  1087. <a href="https://opencollective.com/terser/organization/3/website"><img src="https://opencollective.com/terser/organization/3/avatar.svg"></a>
  1088. <a href="https://opencollective.com/terser/organization/4/website"><img src="https://opencollective.com/terser/organization/4/avatar.svg"></a>
  1089. <a href="https://opencollective.com/terser/organization/5/website"><img src="https://opencollective.com/terser/organization/5/avatar.svg"></a>
  1090. <a href="https://opencollective.com/terser/organization/6/website"><img src="https://opencollective.com/terser/organization/6/avatar.svg"></a>
  1091. <a href="https://opencollective.com/terser/organization/7/website"><img src="https://opencollective.com/terser/organization/7/avatar.svg"></a>
  1092. <a href="https://opencollective.com/terser/organization/8/website"><img src="https://opencollective.com/terser/organization/8/avatar.svg"></a>
  1093. <a href="https://opencollective.com/terser/organization/9/website"><img src="https://opencollective.com/terser/organization/9/avatar.svg"></a>