1 <?xml version="1.0" encoding="utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml"
5 lang="en" xml:lang="en">
7 <title>UglifyJS – a JavaScript parser/compressor/beautifier</title>
8 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
9 <meta name="generator" content="Org-mode"/>
10 <meta name="generated" content="2011-12-09 14:59:08 EET"/>
11 <meta name="author" content="Mihai Bazon"/>
12 <meta name="description" content="a JavaScript parser/compressor/beautifier in JavaScript"/>
13 <meta name="keywords" content="javascript, js, parser, compiler, compressor, mangle, minify, minifier"/>
14 <style type="text/css">
15 <!--/*--><![CDATA[/*><!--*/
16 html { font-family: Times, serif; font-size: 12pt; }
17 .title { text-align: center; }
19 .done { color: green; }
20 .tag { background-color: #add8e6; font-weight:normal }
22 .timestamp { color: #bebebe; }
23 .timestamp-kwd { color: #5f9ea0; }
24 .right {margin-left:auto; margin-right:0px; text-align:right;}
25 .left {margin-left:0px; margin-right:auto; text-align:left;}
26 .center {margin-left:auto; margin-right:auto; text-align:center;}
27 p.verse { margin-left: 3% }
29 border: 1pt solid #AEBDCC;
30 background-color: #F3F5F7;
32 font-family: courier, monospace;
36 table { border-collapse: collapse; }
37 td, th { vertical-align: top; }
38 th.right { text-align:center; }
39 th.left { text-align:center; }
40 th.center { text-align:center; }
41 td.right { text-align:right; }
42 td.left { text-align:left; }
43 td.center { text-align:center; }
44 dt { font-weight: bold; }
45 div.figure { padding: 0.5em; }
46 div.figure p { text-align: center; }
49 border:2px solid gray;
53 textarea { overflow-x: auto; }
54 .linenr { font-size:smaller }
55 .code-highlighted {background-color:#ffff00;}
56 .org-info-js_info-navigation { border-style:none; }
57 #org-info-js_console-label { font-size:10px; font-weight:bold;
59 .org-info-js_search-highlight {background-color:#ffff00; color:#000000;
63 <link rel="stylesheet" type="text/css" href="docstyle.css" />
64 <script type="text/javascript">
65 <!--/*--><![CDATA[/*><!--*/
66 function CodeHighlightOn(elem, id)
68 var target = document.getElementById(id);
70 elem.cacheClassElem = elem.className;
71 elem.cacheClassTarget = target.className;
72 target.className = "code-highlighted";
73 elem.className = "code-highlighted";
76 function CodeHighlightOff(elem, id)
78 var target = document.getElementById(id);
79 if(elem.cacheClassElem)
80 elem.className = elem.cacheClassElem;
81 if(elem.cacheClassTarget)
82 target.className = elem.cacheClassTarget;
95 <h1 class="title">UglifyJS – a JavaScript parser/compressor/beautifier</h1>
98 <div id="table-of-contents">
99 <h2>Table of Contents</h2>
100 <div id="text-table-of-contents">
102 <li><a href="#sec-1">1 UglifyJS — a JavaScript parser/compressor/beautifier </a>
104 <li><a href="#sec-1-1">1.1 Unsafe transformations </a>
106 <li><a href="#sec-1-1-1">1.1.1 Calls involving the global Array constructor </a></li>
107 <li><a href="#sec-1-1-2">1.1.2 <code>obj.toString()</code> ==> <code>obj+“”</code> </a></li>
110 <li><a href="#sec-1-2">1.2 Install (NPM) </a></li>
111 <li><a href="#sec-1-3">1.3 Install latest code from GitHub </a></li>
112 <li><a href="#sec-1-4">1.4 Usage </a>
114 <li><a href="#sec-1-4-1">1.4.1 API </a></li>
115 <li><a href="#sec-1-4-2">1.4.2 Beautifier shortcoming – no more comments </a></li>
116 <li><a href="#sec-1-4-3">1.4.3 Use as a code pre-processor </a></li>
119 <li><a href="#sec-1-5">1.5 Compression – how good is it? </a></li>
120 <li><a href="#sec-1-6">1.6 Bugs? </a></li>
121 <li><a href="#sec-1-7">1.7 Links </a></li>
122 <li><a href="#sec-1-8">1.8 License </a></li>
129 <div id="outline-container-1" class="outline-2">
130 <h2 id="sec-1"><span class="section-number-2">1</span> UglifyJS — a JavaScript parser/compressor/beautifier </h2>
131 <div class="outline-text-2" id="text-1">
135 This package implements a general-purpose JavaScript
136 parser/compressor/beautifier toolkit. It is developed on <a href="http://nodejs.org/">NodeJS</a>, but it
137 should work on any JavaScript platform supporting the CommonJS module system
138 (and if your platform of choice doesn't support CommonJS, you can easily
139 implement it, or discard the <code>exports.*</code> lines from UglifyJS sources).
142 The tokenizer/parser generates an abstract syntax tree from JS code. You
143 can then traverse the AST to learn more about the code, or do various
144 manipulations on it. This part is implemented in <a href="../lib/parse-js.js">parse-js.js</a> and it's a
145 port to JavaScript of the excellent <a href="http://marijn.haverbeke.nl/parse-js/">parse-js</a> Common Lisp library from <a href="http://marijn.haverbeke.nl/">Marijn Haverbeke</a>.
148 ( See <a href="http://github.com/mishoo/cl-uglify-js">cl-uglify-js</a> if you're looking for the Common Lisp version of
152 The second part of this package, implemented in <a href="../lib/process.js">process.js</a>, inspects and
153 manipulates the AST generated by the parser to provide the following:
156 <li>ability to re-generate JavaScript code from the AST. Optionally
157 indented—you can use this if you want to “beautify” a program that has
158 been compressed, so that you can inspect the source. But you can also run
159 our code generator to print out an AST without any whitespace, so you
160 achieve compression as well.
163 <li>shorten variable names (usually to single characters). Our mangler will
164 analyze the code and generate proper variable names, depending on scope
165 and usage, and is smart enough to deal with globals defined elsewhere, or
166 with <code>eval()</code> calls or <code>with{}</code> statements. In short, if <code>eval()</code> or
167 <code>with{}</code> are used in some scope, then all variables in that scope and any
168 variables in the parent scopes will remain unmangled, and any references
169 to such variables remain unmangled as well.
172 <li>various small optimizations that may lead to faster code but certainly
173 lead to smaller code. Where possible, we do the following:
176 <li>foo["bar"] ==> foo.bar
179 <li>remove block brackets <code>{}</code>
182 <li>join consecutive var declarations:
183 var a = 10; var b = 20; ==> var a=10,b=20;
186 <li>resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the
187 replacement if the result occupies less bytes; for example 1/3 would
188 translate to 0.333333333333, so in this case we don't replace it.
191 <li>consecutive statements in blocks are merged into a sequence; in many
192 cases, this leaves blocks with a single statement, so then we can remove
196 <li>various optimizations for IF statements:
199 <li>if (foo) bar(); else baz(); ==> foo?bar():baz();
201 <li>if (!foo) bar(); else baz(); ==> foo?baz():bar();
203 <li>if (foo) bar(); ==> foo&&bar();
205 <li>if (!foo) bar(); ==> foo||bar();
207 <li>if (foo) return bar(); else return baz(); ==> return foo?bar():baz();
209 <li>if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
215 <li>remove some unreachable code and warn about it (code that follows a
216 <code>return</code>, <code>throw</code>, <code>break</code> or <code>continue</code> statement, except
217 function/variable declarations).
220 <li>act a limited version of a pre-processor (c.f. the pre-processor of
221 C/C++) to allow you to safely replace selected global symbols with
222 specified values. When combined with the optimisations above this can
223 make UglifyJS operate slightly more like a compilation process, in
224 that when certain symbols are replaced by constant values, entire code
225 blocks may be optimised away as unreachable.
236 <div id="outline-container-1-1" class="outline-3">
237 <h3 id="sec-1-1"><span class="section-number-3">1.1</span> <span class="target">Unsafe transformations</span> </h3>
238 <div class="outline-text-3" id="text-1-1">
242 The following transformations can in theory break code, although they're
243 probably safe in most practical cases. To enable them you need to pass the
244 <code>--unsafe</code> flag.
249 <div id="outline-container-1-1-1" class="outline-4">
250 <h4 id="sec-1-1-1"><span class="section-number-4">1.1.1</span> Calls involving the global Array constructor </h4>
251 <div class="outline-text-4" id="text-1-1-1">
255 The following transformations occur:
260 <pre class="src src-js"><span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3, 4) => [1,2,3,4]
261 Array(a, b, c) => [a,b,c]
262 <span class="org-keyword">new</span> <span class="org-type">Array</span>(5) => Array(5)
263 <span class="org-keyword">new</span> <span class="org-type">Array</span>(a) => Array(a)
268 These are all safe if the Array name isn't redefined. JavaScript does allow
269 one to globally redefine Array (and pretty much everything, in fact) but I
270 personally don't see why would anyone do that.
273 UglifyJS does handle the case where Array is redefined locally, or even
274 globally but with a <code>function</code> or <code>var</code> declaration. Therefore, in the
275 following cases UglifyJS <b>doesn't touch</b> calls or instantiations of Array:
280 <pre class="src src-js"><span class="org-comment-delimiter">// </span><span class="org-comment">case 1. globally declared variable</span>
281 <span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
282 <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
285 <span class="org-comment-delimiter">// </span><span class="org-comment">or (can be declared later)</span>
286 <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
287 <span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
289 <span class="org-comment-delimiter">// </span><span class="org-comment">or (can be a function)</span>
290 <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
291 <span class="org-keyword">function</span> <span class="org-function-name">Array</span>() { ... }
293 <span class="org-comment-delimiter">// </span><span class="org-comment">case 2. declared in a function</span>
294 (<span class="org-keyword">function</span>(){
295 a = <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
297 <span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
300 <span class="org-comment-delimiter">// </span><span class="org-comment">or</span>
301 (<span class="org-keyword">function</span>(<span class="org-variable-name">Array</span>){
302 <span class="org-keyword">return</span> Array(5, 6, 7);
305 <span class="org-comment-delimiter">// </span><span class="org-comment">or</span>
306 (<span class="org-keyword">function</span>(){
307 <span class="org-keyword">return</span> <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3, 4);
308 <span class="org-keyword">function</span> <span class="org-function-name">Array</span>() { ... }
311 <span class="org-comment-delimiter">// </span><span class="org-comment">etc.</span>
319 <div id="outline-container-1-1-2" class="outline-4">
320 <h4 id="sec-1-1-2"><span class="section-number-4">1.1.2</span> <code>obj.toString()</code> ==> <code>obj+“”</code> </h4>
321 <div class="outline-text-4" id="text-1-1-2">
329 <div id="outline-container-1-2" class="outline-3">
330 <h3 id="sec-1-2"><span class="section-number-3">1.2</span> Install (NPM) </h3>
331 <div class="outline-text-3" id="text-1-2">
335 UglifyJS is now available through NPM — <code>npm install uglify-js</code> should do
342 <div id="outline-container-1-3" class="outline-3">
343 <h3 id="sec-1-3"><span class="section-number-3">1.3</span> Install latest code from GitHub </h3>
344 <div class="outline-text-3" id="text-1-3">
350 <pre class="src src-sh"><span class="org-comment-delimiter">## </span><span class="org-comment">clone the repository</span>
351 mkdir -p /where/you/wanna/put/it
352 <span class="org-builtin">cd</span> /where/you/wanna/put/it
353 git clone git://github.com/mishoo/UglifyJS.git
355 <span class="org-comment-delimiter">## </span><span class="org-comment">make the module available to Node</span>
356 mkdir -p ~/.node_libraries/
357 <span class="org-builtin">cd</span> ~/.node_libraries/
358 ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
360 <span class="org-comment-delimiter">## </span><span class="org-comment">and if you want the CLI script too:</span>
362 <span class="org-builtin">cd</span> ~/bin
363 ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
364 <span class="org-comment-delimiter"># </span><span class="org-comment">(then add ~/bin to your $PATH if it's not there already)</span>
372 <div id="outline-container-1-4" class="outline-3">
373 <h3 id="sec-1-4"><span class="section-number-3">1.4</span> Usage </h3>
374 <div class="outline-text-3" id="text-1-4">
378 There is a command-line tool that exposes the functionality of this library
379 for your shell-scripting needs:
384 <pre class="src src-sh">uglifyjs [ options... ] [ filename ]
389 <code>filename</code> should be the last argument and should name the file from which
390 to read the JavaScript code. If you don't specify it, it will read code
397 <li><code>-b</code> or <code>--beautify</code> — output indented code; when passed, additional
398 options control the beautifier:
401 <li><code>-i N</code> or <code>--indent N</code> — indentation level (number of spaces)
404 <li><code>-q</code> or <code>--quote-keys</code> — quote keys in literal objects (by default,
405 only keys that cannot be identifier names will be quotes).
411 <li><code>--ascii</code> — pass this argument to encode non-ASCII characters as
412 <code>\uXXXX</code> sequences. By default UglifyJS won't bother to do it and will
413 output Unicode characters instead. (the output is always encoded in UTF8,
414 but if you pass this option you'll only get ASCII).
417 <li><code>-nm</code> or <code>--no-mangle</code> — don't mangle names.
420 <li><code>-nmf</code> or <code>--no-mangle-functions</code> – in case you want to mangle variable
421 names, but not touch function names.
424 <li><code>-ns</code> or <code>--no-squeeze</code> — don't call <code>ast_squeeze()</code> (which does various
425 optimizations that result in smaller, less readable code).
428 <li><code>-mt</code> or <code>--mangle-toplevel</code> — mangle names in the toplevel scope too
429 (by default we don't do this).
432 <li><code>--no-seqs</code> — when <code>ast_squeeze()</code> is called (thus, unless you pass
433 <code>--no-squeeze</code>) it will reduce consecutive statements in blocks into a
434 sequence. For example, "a = 10; b = 20; foo();" will be written as
435 "a=10,b=20,foo();". In various occasions, this allows us to discard the
436 block brackets (since the block becomes a single statement). This is ON
437 by default because it seems safe and saves a few hundred bytes on some
438 libs that I tested it on, but pass <code>--no-seqs</code> to disable it.
441 <li><code>--no-dead-code</code> — by default, UglifyJS will remove code that is
442 obviously unreachable (code that follows a <code>return</code>, <code>throw</code>, <code>break</code> or
443 <code>continue</code> statement and is not a function/variable declaration). Pass
444 this option to disable this optimization.
447 <li><code>-nc</code> or <code>--no-copyright</code> — by default, <code>uglifyjs</code> will keep the initial
448 comment tokens in the generated code (assumed to be copyright information
449 etc.). If you pass this it will discard it.
452 <li><code>-o filename</code> or <code>--output filename</code> — put the result in <code>filename</code>. If
453 this isn't given, the result goes to standard output (or see next one).
456 <li><code>--overwrite</code> — if the code is read from a file (not from STDIN) and you
457 pass <code>--overwrite</code> then the output will be written in the same file.
460 <li><code>--ast</code> — pass this if you want to get the Abstract Syntax Tree instead
461 of JavaScript as output. Useful for debugging or learning more about the
465 <li><code>-v</code> or <code>--verbose</code> — output some notes on STDERR (for now just how long
466 each operation takes).
469 <li><code>-d SYMBOL[=VALUE]</code> or <code>--define SYMBOL[=VALUE]</code> — will replace
470 all instances of the specified symbol where used as an identifier
471 (except where symbol has properly declared by a var declaration or
472 use as function parameter or similar) with the specified value. This
473 argument may be specified multiple times to define multiple
474 symbols - if no value is specified the symbol will be replaced with
475 the value <code>true</code>, or you can specify a numeric value (such as
476 <code>1024</code>), a quoted string value (such as ="object"= or
477 ='https://github.com'<code>), or the name of another symbol or keyword (such as =null</code> or <code>document</code>).
478 This allows you, for example, to assign meaningful names to key
479 constant values but discard the symbolic names in the uglified
480 version for brevity/efficiency, or when used wth care, allows
481 UglifyJS to operate as a form of <b>conditional compilation</b>
482 whereby defining appropriate values may, by dint of the constant
483 folding and dead code removal features above, remove entire
484 superfluous code blocks (e.g. completely remove instrumentation or
485 trace code for production use).
486 Where string values are being defined, the handling of quotes are
487 likely to be subject to the specifics of your command shell
488 environment, so you may need to experiment with quoting styles
489 depending on your platform, or you may find the option
490 <code>--define-from-module</code> more suitable for use.
493 <li><code>-define-from-module SOMEMODULE</code> — will load the named module (as
494 per the NodeJS <code>require()</code> function) and iterate all the exported
495 properties of the module defining them as symbol names to be defined
496 (as if by the <code>--define</code> option) per the name of each property
497 (i.e. without the module name prefix) and given the value of the
498 property. This is a much easier way to handle and document groups of
499 symbols to be defined rather than a large number of <code>--define</code>
503 <li><code>--unsafe</code> — enable other additional optimizations that are known to be
504 unsafe in some contrived situations, but could still be generally useful.
508 <li>foo.toString() ==> foo+""
510 <li>new Array(x,…) ==> [x,…]
512 <li>new Array(x) ==> Array(x)
518 <li><code>--max-line-len</code> (default 32K characters) — add a newline after around
519 32K characters. I've seen both FF and Chrome croak when all the code was
520 on a single line of around 670K. Pass –max-line-len 0 to disable this
524 <li><code>--reserved-names</code> — some libraries rely on certain names to be used, as
525 pointed out in issue #92 and #81, so this option allow you to exclude such
526 names from the mangler. For example, to keep names <code>require</code> and <code>$super</code>
527 intact you'd specify –reserved-names "require,$super".
530 <li><code>--inline-script</code> – when you want to include the output literally in an
531 HTML <code><script></code> tag you can use this option to prevent <code></script</code> from
532 showing up in the output.
535 <li><code>--lift-vars</code> – when you pass this, UglifyJS will apply the following
536 transformations (see the notes in API, <code>ast_lift_variables</code>):
539 <li>put all <code>var</code> declarations at the start of the scope
541 <li>make sure a variable is declared only once
543 <li>discard unused function arguments
545 <li>discard unused inner (named) functions
547 <li>finally, try to merge assignments into that one <code>var</code> declaration, if
559 <div id="outline-container-1-4-1" class="outline-4">
560 <h4 id="sec-1-4-1"><span class="section-number-4">1.4.1</span> API </h4>
561 <div class="outline-text-4" id="text-1-4-1">
565 To use the library from JavaScript, you'd do the following (example for
571 <pre class="src src-js"><span class="org-keyword">var</span> <span class="org-variable-name">jsp</span> = require(<span class="org-string">"uglify-js"</span>).parser;
572 <span class="org-keyword">var</span> <span class="org-variable-name">pro</span> = require(<span class="org-string">"uglify-js"</span>).uglify;
574 <span class="org-keyword">var</span> <span class="org-variable-name">orig_code</span> = <span class="org-string">"... JS code here"</span>;
575 <span class="org-keyword">var</span> <span class="org-variable-name">ast</span> = jsp.parse(orig_code); <span class="org-comment-delimiter">// </span><span class="org-comment">parse code and get the initial AST</span>
576 ast = pro.ast_mangle(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">get a new AST with mangled names</span>
577 ast = pro.ast_squeeze(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">get an AST with compression optimizations</span>
578 <span class="org-keyword">var</span> <span class="org-variable-name">final_code</span> = pro.gen_code(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">compressed code here</span>
583 The above performs the full compression that is possible right now. As you
584 can see, there are a sequence of steps which you can apply. For example if
585 you want compressed output but for some reason you don't want to mangle
586 variable names, you would simply skip the line that calls
587 <code>pro.ast_mangle(ast)</code>.
590 Some of these functions take optional arguments. Here's a description:
593 <li><code>jsp.parse(code, strict_semicolons)</code> – parses JS code and returns an AST.
594 <code>strict_semicolons</code> is optional and defaults to <code>false</code>. If you pass
595 <code>true</code> then the parser will throw an error when it expects a semicolon and
596 it doesn't find it. For most JS code you don't want that, but it's useful
597 if you want to strictly sanitize your code.
600 <li><code>pro.ast_lift_variables(ast)</code> – merge and move <code>var</code> declarations to the
601 scop of the scope; discard unused function arguments or variables; discard
602 unused (named) inner functions. It also tries to merge assignments
603 following the <code>var</code> declaration into it.
606 If your code is very hand-optimized concerning <code>var</code> declarations, this
607 lifting variable declarations might actually increase size. For me it
608 helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also
609 note that (since it's not enabled by default) this operation isn't yet
610 heavily tested (please report if you find issues!).
613 Note that although it might increase the image size (on jQuery it gains
614 865 bytes, 243 after gzip) it's technically more correct: in certain
615 situations, dead code removal might drop variable declarations, which
616 would not happen if the variables are lifted in advance.
619 Here's an example of what it does:
627 <pre class="src src-js"><span class="org-keyword">function</span> <span class="org-function-name">f</span>(<span class="org-variable-name">a</span>, <span class="org-variable-name">b</span>, <span class="org-variable-name">c</span>, <span class="org-variable-name">d</span>, <span class="org-variable-name">e</span>) {
628 <span class="org-keyword">var</span> <span class="org-variable-name">q</span>;
629 <span class="org-keyword">var</span> <span class="org-variable-name">w</span>;
632 <span class="org-keyword">for</span> (<span class="org-keyword">var</span> <span class="org-variable-name">i</span> = 1; i < 10; ++i) {
633 <span class="org-keyword">var</span> <span class="org-variable-name">boo</span> = foo(a);
635 <span class="org-keyword">for</span> (<span class="org-keyword">var</span> <span class="org-variable-name">i</span> = 0; i < 1; ++i) {
636 <span class="org-keyword">var</span> <span class="org-variable-name">boo</span> = bar(c);
638 <span class="org-keyword">function</span> <span class="org-function-name">foo</span>(){ ... }
639 <span class="org-keyword">function</span> <span class="org-function-name">bar</span>(){ ... }
640 <span class="org-keyword">function</span> <span class="org-function-name">baz</span>(){ ... }
643 <span class="org-comment-delimiter">// </span><span class="org-comment">transforms into ==></span>
645 <span class="org-keyword">function</span> <span class="org-function-name">f</span>(<span class="org-variable-name">a</span>, <span class="org-variable-name">b</span>, <span class="org-variable-name">c</span>) {
646 <span class="org-keyword">var</span> <span class="org-variable-name">i</span>, <span class="org-variable-name">boo</span>, <span class="org-variable-name">w</span> = 10, <span class="org-variable-name">q</span> = 20;
647 <span class="org-keyword">for</span> (i = 1; i < 10; ++i) {
650 <span class="org-keyword">for</span> (i = 0; i < 1; ++i) {
653 <span class="org-keyword">function</span> <span class="org-function-name">foo</span>() { ... }
654 <span class="org-keyword">function</span> <span class="org-function-name">bar</span>() { ... }
660 <li><code>pro.ast_mangle(ast, options)</code> – generates a new AST containing mangled
661 (compressed) variable and function names. It supports the following
665 <li><code>toplevel</code> – mangle toplevel names (by default we don't touch them).
667 <li><code>except</code> – an array of names to exclude from compression.
669 <li><code>defines</code> – an object with properties named after symbols to
670 replace (see the <code>--define</code> option for the script) and the values
671 representing the AST replacement value.
677 <li><code>pro.ast_squeeze(ast, options)</code> – employs further optimizations designed
678 to reduce the size of the code that <code>gen_code</code> would generate from the
679 AST. Returns a new AST. <code>options</code> can be a hash; the supported options
683 <li><code>make_seqs</code> (default true) which will cause consecutive statements in a
684 block to be merged using the "sequence" (comma) operator
687 <li><code>dead_code</code> (default true) which will remove unreachable code.
693 <li><code>pro.gen_code(ast, options)</code> – generates JS code from the AST. By
694 default it's minified, but using the <code>options</code> argument you can get nicely
695 formatted output. <code>options</code> is, well, optional :-) and if you pass it it
696 must be an object and supports the following properties (below you can see
700 <li><code>beautify: false</code> – pass <code>true</code> if you want indented output
702 <li><code>indent_start: 0</code> (only applies when <code>beautify</code> is <code>true</code>) – initial
703 indentation in spaces
705 <li><code>indent_level: 4</code> (only applies when <code>beautify</code> is <code>true</code>) --
706 indentation level, in spaces (pass an even number)
708 <li><code>quote_keys: false</code> – if you pass <code>true</code> it will quote all keys in
711 <li><code>space_colon: false</code> (only applies when <code>beautify</code> is <code>true</code>) – wether
712 to put a space before the colon in object literals
714 <li><code>ascii_only: false</code> – pass <code>true</code> if you want to encode non-ASCII
715 characters as <code>\uXXXX</code>.
717 <li><code>inline_script: false</code> – pass <code>true</code> to escape occurrences of
718 <code></script</code> in strings
730 <div id="outline-container-1-4-2" class="outline-4">
731 <h4 id="sec-1-4-2"><span class="section-number-4">1.4.2</span> Beautifier shortcoming – no more comments </h4>
732 <div class="outline-text-4" id="text-1-4-2">
736 The beautifier can be used as a general purpose indentation tool. It's
737 useful when you want to make a minified file readable. One limitation,
738 though, is that it discards all comments, so you don't really want to use it
739 to reformat your code, unless you don't have, or don't care about, comments.
742 In fact it's not the beautifier who discards comments — they are dumped at
743 the parsing stage, when we build the initial AST. Comments don't really
744 make sense in the AST, and while we could add nodes for them, it would be
745 inconvenient because we'd have to add special rules to ignore them at all
746 the processing stages.
752 <div id="outline-container-1-4-3" class="outline-4">
753 <h4 id="sec-1-4-3"><span class="section-number-4">1.4.3</span> Use as a code pre-processor </h4>
754 <div class="outline-text-4" id="text-1-4-3">
758 The <code>--define</code> option can be used, particularly when combined with the
759 constant folding logic, as a form of pre-processor to enable or remove
760 particular constructions, such as might be used for instrumenting
761 development code, or to produce variations aimed at a specific
765 The code below illustrates the way this can be done, and how the
766 symbol replacement is performed.
771 <pre class="src src-js">CLAUSE1: <span class="org-keyword">if</span> (<span class="org-keyword">typeof</span> DEVMODE === <span class="org-string">'undefined'</span>) {
772 DEVMODE = <span class="org-constant">true</span>;
775 <span class="org-function-name">CLAUSE2</span>: <span class="org-keyword">function</span> init() {
776 <span class="org-keyword">if</span> (DEVMODE) {
777 console.log(<span class="org-string">"init() called"</span>);
780 DEVMODE &amp;&amp; console.log(<span class="org-string">"init() complete"</span>);
783 <span class="org-function-name">CLAUSE3</span>: <span class="org-keyword">function</span> reportDeviceStatus(<span class="org-variable-name">device</span>) {
784 <span class="org-keyword">var</span> <span class="org-variable-name">DEVMODE</span> = device.mode, <span class="org-variable-name">DEVNAME</span> = device.name;
785 <span class="org-keyword">if</span> (DEVMODE === <span class="org-string">'open'</span>) {
793 When the above code is normally executed, the undeclared global
794 variable <code>DEVMODE</code> will be assigned the value <b>true</b> (see <code>CLAUSE1</code>)
795 and so the <code>init()</code> function (<code>CLAUSE2</code>) will write messages to the
796 console log when executed, but in <code>CLAUSE3</code> a locally declared
797 variable will mask access to the <code>DEVMODE</code> global symbol.
800 If the above code is processed by UglifyJS with an argument of
801 <code>--define DEVMODE=false</code> then UglifyJS will replace <code>DEVMODE</code> with the
802 boolean constant value <b>false</b> within <code>CLAUSE1</code> and <code>CLAUSE2</code>, but it
803 will leave <code>CLAUSE3</code> as it stands because there <code>DEVMODE</code> resolves to
804 a validly declared variable.
807 And more so, the constant-folding features of UglifyJS will recognise
808 that the <code>if</code> condition of <code>CLAUSE1</code> is thus always false, and so will
809 remove the test and body of <code>CLAUSE1</code> altogether (including the
810 otherwise slightly problematical statement <code>false = true;</code> which it
811 will have formed by replacing <code>DEVMODE</code> in the body). Similarly,
812 within <code>CLAUSE2</code> both calls to <code>console.log()</code> will be removed
816 In this way you can mimic, to a limited degree, the functionality of
817 the C/C++ pre-processor to enable or completely remove blocks
818 depending on how certain symbols are defined - perhaps using UglifyJS
819 to generate different versions of source aimed at different
823 It is recommmended (but not made mandatory) that symbols designed for
824 this purpose are given names consisting of <code>UPPER_CASE_LETTERS</code> to
825 distinguish them from other (normal) symbols and avoid the sort of
826 clash that <code>CLAUSE3</code> above illustrates.
833 <div id="outline-container-1-5" class="outline-3">
834 <h3 id="sec-1-5"><span class="section-number-3">1.5</span> Compression – how good is it? </h3>
835 <div class="outline-text-3" id="text-1-5">
839 Here are updated statistics. (I also updated my Google Closure and YUI
843 We're still a lot better than YUI in terms of compression, though slightly
844 slower. We're still a lot faster than Closure, and compression after gzip
847 <table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
849 <colgroup><col class="left" /><col class="left" /><col class="right" /><col class="left" /><col class="right" /><col class="left" /><col class="right" />
852 <tr><th scope="col" class="left">File</th><th scope="col" class="left">UglifyJS</th><th scope="col" class="right">UglifyJS+gzip</th><th scope="col" class="left">Closure</th><th scope="col" class="right">Closure+gzip</th><th scope="col" class="left">YUI</th><th scope="col" class="right">YUI+gzip</th></tr>
855 <tr><td class="left">jquery-1.6.2.js</td><td class="left">91001 (0:01.59)</td><td class="right">31896</td><td class="left">90678 (0:07.40)</td><td class="right">31979</td><td class="left">101527 (0:01.82)</td><td class="right">34646</td></tr>
856 <tr><td class="left">paper.js</td><td class="left">142023 (0:01.65)</td><td class="right">43334</td><td class="left">134301 (0:07.42)</td><td class="right">42495</td><td class="left">173383 (0:01.58)</td><td class="right">48785</td></tr>
857 <tr><td class="left">prototype.js</td><td class="left">88544 (0:01.09)</td><td class="right">26680</td><td class="left">86955 (0:06.97)</td><td class="right">26326</td><td class="left">92130 (0:00.79)</td><td class="right">28624</td></tr>
858 <tr><td class="left">thelib-full.js (DynarchLIB)</td><td class="left">251939 (0:02.55)</td><td class="right">72535</td><td class="left">249911 (0:09.05)</td><td class="right">72696</td><td class="left">258869 (0:01.94)</td><td class="right">76584</td></tr>
867 <div id="outline-container-1-6" class="outline-3">
868 <h3 id="sec-1-6"><span class="section-number-3">1.6</span> Bugs? </h3>
869 <div class="outline-text-3" id="text-1-6">
873 Unfortunately, for the time being there is no automated test suite. But I
874 ran the compressor manually on non-trivial code, and then I tested that the
875 generated code works as expected. A few hundred times.
878 DynarchLIB was started in times when there was no good JS minifier.
879 Therefore I was quite religious about trying to write short code manually,
880 and as such DL contains a lot of syntactic hacks<sup><a class="footref" name="fnr.1" href="#fn.1">1</a></sup> such as “foo == bar ? a
881 = 10 : b = 20”, though the more readable version would clearly be to use
885 Since the parser/compressor runs fine on DL and jQuery, I'm quite confident
886 that it's solid enough for production use. If you can identify any bugs,
887 I'd love to hear about them (<a href="http://groups.google.com/group/uglifyjs">use the Google Group</a> or email me directly).
893 <div id="outline-container-1-7" class="outline-3">
894 <h3 id="sec-1-7"><span class="section-number-3">1.7</span> Links </h3>
895 <div class="outline-text-3" id="text-1-7">
899 <li>Twitter: <a href="http://twitter.com/UglifyJS">@UglifyJS</a>
901 <li>Project at GitHub: <a href="http://github.com/mishoo/UglifyJS">http://github.com/mishoo/UglifyJS</a>
903 <li>Google Group: <a href="http://groups.google.com/group/uglifyjs">http://groups.google.com/group/uglifyjs</a>
905 <li>Common Lisp JS parser: <a href="http://marijn.haverbeke.nl/parse-js/">http://marijn.haverbeke.nl/parse-js/</a>
907 <li>JS-to-Lisp compiler: <a href="http://github.com/marijnh/js">http://github.com/marijnh/js</a>
909 <li>Common Lisp JS uglifier: <a href="http://github.com/mishoo/cl-uglify-js">http://github.com/mishoo/cl-uglify-js</a>
918 <div id="outline-container-1-8" class="outline-3">
919 <h3 id="sec-1-8"><span class="section-number-3">1.8</span> License </h3>
920 <div class="outline-text-3" id="text-1-8">
924 UglifyJS is released under the BSD license:
929 <pre class="example">Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
930 Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
932 Redistribution and use in source and binary forms, with or without
933 modification, are permitted provided that the following conditions
936 * Redistributions of source code must retain the above
937 copyright notice, this list of conditions and the following
940 * Redistributions in binary form must reproduce the above
941 copyright notice, this list of conditions and the following
942 disclaimer in the documentation and/or other materials
943 provided with the distribution.
945 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
946 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
947 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
948 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
949 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
950 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
951 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
952 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
953 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
954 TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
955 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
961 <h2 class="footnotes">Footnotes: </h2>
962 <div id="text-footnotes">
963 <p class="footnote"><sup><a class="footnum" name="fn.1" href="#fnr.1">1</a></sup> I even reported a few bugs and suggested some fixes in the original
964 <a href="http://marijn.haverbeke.nl/parse-js/">parse-js</a> library, and Marijn pushed fixes literally in minutes.
974 <p class="date">Date: 2011-12-09 14:59:08 EET</p>
975 <p class="author">Author: Mihai Bazon</p>
976 <p class="creator">Org version 7.7 with Emacs version 23</p>
977 <a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>