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.

1305 lines
53 KiB

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