Debian Codegraph @

uglify-js/README.html

raw
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">
6 <head>
7 <title>UglifyJS &ndash; 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="2012-11-22 10:46:14 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; }
18 .todo { color: red; }
19 .done { color: green; }
20 .tag { background-color: #add8e6; font-weight:normal }
21 .target { }
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% }
28 pre {
29 border: 1pt solid #AEBDCC;
30 background-color: #F3F5F7;
31 padding: 5pt;
32 font-family: courier, monospace;
33 font-size: 90%;
34 overflow:auto;
35 }
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; }
47 div.inlinetask {
48 padding:10px;
49 border:2px solid gray;
50 margin:10px;
51 background: #ffffcc;
52 }
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;
58 white-space:nowrap; }
59 .org-info-js_search-highlight {background-color:#ffff00; color:#000000;
60 font-weight:bold; }
61 /*]]>*/-->
62 </style>
63 <link rel="stylesheet" type="text/css" href="docstyle.css" />
64 <script type="text/javascript">
65 <!--/*--><![CDATA[/*><!--*/
66 function CodeHighlightOn(elem, id)
67 {
68 var target = document.getElementById(id);
69 if(null != target) {
70 elem.cacheClassElem = elem.className;
71 elem.cacheClassTarget = target.className;
72 target.className = "code-highlighted";
73 elem.className = "code-highlighted";
74 }
75 }
76 function CodeHighlightOff(elem, id)
77 {
78 var target = document.getElementById(id);
79 if(elem.cacheClassElem)
80 elem.className = elem.cacheClassElem;
81 if(elem.cacheClassTarget)
82 target.className = elem.cacheClassTarget;
83 }
84 /*]]>*///-->
85 </script>
86
87 </head>
88 <body>
89
90 <div id="preamble">
91
92 </div>
93
94 <div id="content">
95 <h1 class="title">UglifyJS &ndash; a JavaScript parser/compressor/beautifier</h1>
96
97
98 <div id="table-of-contents">
99 <h2>Table of Contents</h2>
100 <div id="text-table-of-contents">
101 <ul>
102 <li><a href="#sec-1">1 NEW: UglifyJS2 </a></li>
103 <li><a href="#sec-2">2 UglifyJS &mdash; a JavaScript parser/compressor/beautifier </a>
104 <ul>
105 <li><a href="#sec-2-1">2.1 Unsafe transformations </a>
106 <ul>
107 <li><a href="#sec-2-1-1">2.1.1 Calls involving the global Array constructor </a></li>
108 <li><a href="#sec-2-1-2">2.1.2 <code>obj.toString()</code> ==&gt; <code>obj+“”</code> </a></li>
109 </ul>
110 </li>
111 <li><a href="#sec-2-2">2.2 Install (NPM) </a></li>
112 <li><a href="#sec-2-3">2.3 Install latest code from GitHub </a></li>
113 <li><a href="#sec-2-4">2.4 Usage </a>
114 <ul>
115 <li><a href="#sec-2-4-1">2.4.1 API </a></li>
116 <li><a href="#sec-2-4-2">2.4.2 Beautifier shortcoming &ndash; no more comments </a></li>
117 <li><a href="#sec-2-4-3">2.4.3 Use as a code pre-processor </a></li>
118 </ul>
119 </li>
120 <li><a href="#sec-2-5">2.5 Compression &ndash; how good is it? </a></li>
121 <li><a href="#sec-2-6">2.6 Bugs? </a></li>
122 <li><a href="#sec-2-7">2.7 Links </a></li>
123 <li><a href="#sec-2-8">2.8 License </a></li>
124 </ul>
125 </li>
126 </ul>
127 </div>
128 </div>
129
130 <div id="outline-container-1" class="outline-2">
131 <h2 id="sec-1"><span class="section-number-2">1</span> NEW: UglifyJS2 </h2>
132 <div class="outline-text-2" id="text-1">
133
134
135 <p>
136 I started working on UglifyJS's successor, version 2. It's almost a full
137 rewrite (except for the parser which is heavily modified, everything else
138 starts from scratch). I've detailed my reasons in the README, see the
139 project page.
140 </p>
141 <p>
142 <a href="https://github.com/mishoo/UglifyJS2">https://github.com/mishoo/UglifyJS2</a>
143 </p>
144 <p>
145 Version 1 will continue to be maintained for fixing show-stopper bugs, but
146 no new features should be expected.
147 </p>
148 </div>
149
150 </div>
151
152 <div id="outline-container-2" class="outline-2">
153 <h2 id="sec-2"><span class="section-number-2">2</span> UglifyJS &mdash; a JavaScript parser/compressor/beautifier </h2>
154 <div class="outline-text-2" id="text-2">
155
156
157 <p>
158 This package implements a general-purpose JavaScript
159 parser/compressor/beautifier toolkit. It is developed on <a href="http://nodejs.org/">NodeJS</a>, but it
160 should work on any JavaScript platform supporting the CommonJS module system
161 (and if your platform of choice doesn't support CommonJS, you can easily
162 implement it, or discard the <code>exports.*</code> lines from UglifyJS sources).
163 </p>
164 <p>
165 The tokenizer/parser generates an abstract syntax tree from JS code. You
166 can then traverse the AST to learn more about the code, or do various
167 manipulations on it. This part is implemented in <a href="../lib/parse-js.js">parse-js.js</a> and it's a
168 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>.
169 </p>
170 <p>
171 ( See <a href="http://github.com/mishoo/cl-uglify-js">cl-uglify-js</a> if you're looking for the Common Lisp version of
172 UglifyJS. )
173 </p>
174 <p>
175 The second part of this package, implemented in <a href="../lib/process.js">process.js</a>, inspects and
176 manipulates the AST generated by the parser to provide the following:
177 </p>
178 <ul>
179 <li>ability to re-generate JavaScript code from the AST. Optionally
180 indented&mdash;you can use this if you want to “beautify” a program that has
181 been compressed, so that you can inspect the source. But you can also run
182 our code generator to print out an AST without any whitespace, so you
183 achieve compression as well.
184
185 </li>
186 <li>shorten variable names (usually to single characters). Our mangler will
187 analyze the code and generate proper variable names, depending on scope
188 and usage, and is smart enough to deal with globals defined elsewhere, or
189 with <code>eval()</code> calls or <code>with{}</code> statements. In short, if <code>eval()</code> or
190 <code>with{}</code> are used in some scope, then all variables in that scope and any
191 variables in the parent scopes will remain unmangled, and any references
192 to such variables remain unmangled as well.
193
194 </li>
195 <li>various small optimizations that may lead to faster code but certainly
196 lead to smaller code. Where possible, we do the following:
197
198 <ul>
199 <li>foo["bar"] ==&gt; foo.bar
200
201 </li>
202 <li>remove block brackets <code>{}</code>
203
204 </li>
205 <li>join consecutive var declarations:
206 var a = 10; var b = 20; ==&gt; var a=10,b=20;
207
208 </li>
209 <li>resolve simple constant expressions: 1 +2 * 3 ==&gt; 7. We only do the
210 replacement if the result occupies less bytes; for example 1/3 would
211 translate to 0.333333333333, so in this case we don't replace it.
212
213 </li>
214 <li>consecutive statements in blocks are merged into a sequence; in many
215 cases, this leaves blocks with a single statement, so then we can remove
216 the block brackets.
217
218 </li>
219 <li>various optimizations for IF statements:
220
221 <ul>
222 <li>if (foo) bar(); else baz(); ==&gt; foo?bar():baz();
223 </li>
224 <li>if (!foo) bar(); else baz(); ==&gt; foo?baz():bar();
225 </li>
226 <li>if (foo) bar(); ==&gt; foo&amp;&amp;bar();
227 </li>
228 <li>if (!foo) bar(); ==&gt; foo||bar();
229 </li>
230 <li>if (foo) return bar(); else return baz(); ==&gt; return foo?bar():baz();
231 </li>
232 <li>if (foo) return bar(); else something(); ==&gt; {if(foo)return bar();something()}
233
234 </li>
235 </ul>
236
237 </li>
238 <li>remove some unreachable code and warn about it (code that follows a
239 <code>return</code>, <code>throw</code>, <code>break</code> or <code>continue</code> statement, except
240 function/variable declarations).
241
242 </li>
243 <li>act a limited version of a pre-processor (c.f. the pre-processor of
244 C/C++) to allow you to safely replace selected global symbols with
245 specified values. When combined with the optimisations above this can
246 make UglifyJS operate slightly more like a compilation process, in
247 that when certain symbols are replaced by constant values, entire code
248 blocks may be optimised away as unreachable.
249 </li>
250 </ul>
251
252 </li>
253 </ul>
254
255
256
257 </div>
258
259 <div id="outline-container-2-1" class="outline-3">
260 <h3 id="sec-2-1"><span class="section-number-3">2.1</span> <span class="target">Unsafe transformations</span> </h3>
261 <div class="outline-text-3" id="text-2-1">
262
263
264 <p>
265 The following transformations can in theory break code, although they're
266 probably safe in most practical cases. To enable them you need to pass the
267 <code>--unsafe</code> flag.
268 </p>
269
270 </div>
271
272 <div id="outline-container-2-1-1" class="outline-4">
273 <h4 id="sec-2-1-1"><span class="section-number-4">2.1.1</span> Calls involving the global Array constructor </h4>
274 <div class="outline-text-4" id="text-2-1-1">
275
276
277 <p>
278 The following transformations occur:
279 </p>
280
281
282
283 <pre class="src src-js"><span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3, 4) =&gt; [1,2,3,4]
284 Array(a, b, c) =&gt; [a,b,c]
285 <span class="org-keyword">new</span> <span class="org-type">Array</span>(5) =&gt; Array(5)
286 <span class="org-keyword">new</span> <span class="org-type">Array</span>(a) =&gt; Array(a)
287 </pre>
288
289
290 <p>
291 These are all safe if the Array name isn't redefined. JavaScript does allow
292 one to globally redefine Array (and pretty much everything, in fact) but I
293 personally don't see why would anyone do that.
294 </p>
295 <p>
296 UglifyJS does handle the case where Array is redefined locally, or even
297 globally but with a <code>function</code> or <code>var</code> declaration. Therefore, in the
298 following cases UglifyJS <b>doesn't touch</b> calls or instantiations of Array:
299 </p>
300
301
302
303 <pre class="src src-js"><span class="org-comment-delimiter">// </span><span class="org-comment">case 1. globally declared variable</span>
304 <span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
305 <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
306 Array(a, b);
307
308 <span class="org-comment-delimiter">// </span><span class="org-comment">or (can be declared later)</span>
309 <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
310 <span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
311
312 <span class="org-comment-delimiter">// </span><span class="org-comment">or (can be a function)</span>
313 <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
314 <span class="org-keyword">function</span> <span class="org-function-name">Array</span>() { ... }
315
316 <span class="org-comment-delimiter">// </span><span class="org-comment">case 2. declared in a function</span>
317 (<span class="org-keyword">function</span>(){
318 a = <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
319 b = Array(5, 6);
320 <span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
321 })();
322
323 <span class="org-comment-delimiter">// </span><span class="org-comment">or</span>
324 (<span class="org-keyword">function</span>(<span class="org-variable-name">Array</span>){
325 <span class="org-keyword">return</span> Array(5, 6, 7);
326 })();
327
328 <span class="org-comment-delimiter">// </span><span class="org-comment">or</span>
329 (<span class="org-keyword">function</span>(){
330 <span class="org-keyword">return</span> <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3, 4);
331 <span class="org-keyword">function</span> <span class="org-function-name">Array</span>() { ... }
332 })();
333
334 <span class="org-comment-delimiter">// </span><span class="org-comment">etc.</span>
335 </pre>
336
337
338 </div>
339
340 </div>
341
342 <div id="outline-container-2-1-2" class="outline-4">
343 <h4 id="sec-2-1-2"><span class="section-number-4">2.1.2</span> <code>obj.toString()</code> ==&gt; <code>obj+“”</code> </h4>
344 <div class="outline-text-4" id="text-2-1-2">
345
346
347 </div>
348 </div>
349
350 </div>
351
352 <div id="outline-container-2-2" class="outline-3">
353 <h3 id="sec-2-2"><span class="section-number-3">2.2</span> Install (NPM) </h3>
354 <div class="outline-text-3" id="text-2-2">
355
356
357 <p>
358 UglifyJS is now available through NPM &mdash; <code>npm install uglify-js@1</code> should
359 do the job.
360 </p>
361 <p>
362 <b>NOTE:</b> The NPM package has been upgraded to UglifyJS2. If you need to
363 install version 1.x you need to add `@1` to the command, as I did above. I
364 strongly suggest you to try to upgrade, though this might not be simple (v2
365 has a completely different AST structure and API).
366 </p>
367 </div>
368
369 </div>
370
371 <div id="outline-container-2-3" class="outline-3">
372 <h3 id="sec-2-3"><span class="section-number-3">2.3</span> Install latest code from GitHub </h3>
373 <div class="outline-text-3" id="text-2-3">
374
375
376
377
378
379 <pre class="src src-sh"><span class="org-comment-delimiter">## </span><span class="org-comment">clone the repository</span>
380 mkdir -p /where/you/wanna/put/it
381 <span class="org-builtin">cd</span> /where/you/wanna/put/it
382 git clone git://github.com/mishoo/UglifyJS.git
383
384 <span class="org-comment-delimiter">## </span><span class="org-comment">make the module available to Node</span>
385 mkdir -p ~/.node_libraries/
386 <span class="org-builtin">cd</span> ~/.node_libraries/
387 ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
388
389 <span class="org-comment-delimiter">## </span><span class="org-comment">and if you want the CLI script too:</span>
390 mkdir -p ~/bin
391 <span class="org-builtin">cd</span> ~/bin
392 ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
393 <span class="org-comment-delimiter"># </span><span class="org-comment">(then add ~/bin to your $PATH if it's not there already)</span>
394 </pre>
395
396
397 </div>
398
399 </div>
400
401 <div id="outline-container-2-4" class="outline-3">
402 <h3 id="sec-2-4"><span class="section-number-3">2.4</span> Usage </h3>
403 <div class="outline-text-3" id="text-2-4">
404
405
406 <p>
407 There is a command-line tool that exposes the functionality of this library
408 for your shell-scripting needs:
409 </p>
410
411
412
413 <pre class="src src-sh">uglifyjs [ options... ] [ filename ]
414 </pre>
415
416
417 <p>
418 <code>filename</code> should be the last argument and should name the file from which
419 to read the JavaScript code. If you don't specify it, it will read code
420 from STDIN.
421 </p>
422 <p>
423 Supported options:
424 </p>
425 <ul>
426 <li><code>-b</code> or <code>--beautify</code> &mdash; output indented code; when passed, additional
427 options control the beautifier:
428
429 <ul>
430 <li><code>-i N</code> or <code>--indent N</code> &mdash; indentation level (number of spaces)
431
432 </li>
433 <li><code>-q</code> or <code>--quote-keys</code> &mdash; quote keys in literal objects (by default,
434 only keys that cannot be identifier names will be quotes).
435
436 </li>
437 </ul>
438
439 </li>
440 <li><code>-c</code> or <code>----consolidate-primitive-values</code> &mdash; consolidates null, Boolean,
441 and String values. Known as aliasing in the Closure Compiler. Worsens the
442 data compression ratio of gzip.
443
444 </li>
445 <li><code>--ascii</code> &mdash; pass this argument to encode non-ASCII characters as
446 <code>\uXXXX</code> sequences. By default UglifyJS won't bother to do it and will
447 output Unicode characters instead. (the output is always encoded in UTF8,
448 but if you pass this option you'll only get ASCII).
449
450 </li>
451 <li><code>-nm</code> or <code>--no-mangle</code> &mdash; don't mangle names.
452
453 </li>
454 <li><code>-nmf</code> or <code>--no-mangle-functions</code> &ndash; in case you want to mangle variable
455 names, but not touch function names.
456
457 </li>
458 <li><code>-ns</code> or <code>--no-squeeze</code> &mdash; don't call <code>ast_squeeze()</code> (which does various
459 optimizations that result in smaller, less readable code).
460
461 </li>
462 <li><code>-mt</code> or <code>--mangle-toplevel</code> &mdash; mangle names in the toplevel scope too
463 (by default we don't do this).
464
465 </li>
466 <li><code>--no-seqs</code> &mdash; when <code>ast_squeeze()</code> is called (thus, unless you pass
467 <code>--no-squeeze</code>) it will reduce consecutive statements in blocks into a
468 sequence. For example, "a = 10; b = 20; foo();" will be written as
469 "a=10,b=20,foo();". In various occasions, this allows us to discard the
470 block brackets (since the block becomes a single statement). This is ON
471 by default because it seems safe and saves a few hundred bytes on some
472 libs that I tested it on, but pass <code>--no-seqs</code> to disable it.
473
474 </li>
475 <li><code>--no-dead-code</code> &mdash; by default, UglifyJS will remove code that is
476 obviously unreachable (code that follows a <code>return</code>, <code>throw</code>, <code>break</code> or
477 <code>continue</code> statement and is not a function/variable declaration). Pass
478 this option to disable this optimization.
479
480 </li>
481 <li><code>-nc</code> or <code>--no-copyright</code> &mdash; by default, <code>uglifyjs</code> will keep the initial
482 comment tokens in the generated code (assumed to be copyright information
483 etc.). If you pass this it will discard it.
484
485 </li>
486 <li><code>-o filename</code> or <code>--output filename</code> &mdash; put the result in <code>filename</code>. If
487 this isn't given, the result goes to standard output (or see next one).
488
489 </li>
490 <li><code>--overwrite</code> &mdash; if the code is read from a file (not from STDIN) and you
491 pass <code>--overwrite</code> then the output will be written in the same file.
492
493 </li>
494 <li><code>--ast</code> &mdash; pass this if you want to get the Abstract Syntax Tree instead
495 of JavaScript as output. Useful for debugging or learning more about the
496 internals.
497
498 </li>
499 <li><code>-v</code> or <code>--verbose</code> &mdash; output some notes on STDERR (for now just how long
500 each operation takes).
501
502 </li>
503 <li><code>-d SYMBOL[=VALUE]</code> or <code>--define SYMBOL[=VALUE]</code> &mdash; will replace
504 all instances of the specified symbol where used as an identifier
505 (except where symbol has properly declared by a var declaration or
506 use as function parameter or similar) with the specified value. This
507 argument may be specified multiple times to define multiple
508 symbols - if no value is specified the symbol will be replaced with
509 the value <code>true</code>, or you can specify a numeric value (such as
510 <code>1024</code>), a quoted string value (such as ="object"= or
511 ='https://github.com'<code>), or the name of another symbol or keyword (such as =null</code> or <code>document</code>).
512 This allows you, for example, to assign meaningful names to key
513 constant values but discard the symbolic names in the uglified
514 version for brevity/efficiency, or when used wth care, allows
515 UglifyJS to operate as a form of <b>conditional compilation</b>
516 whereby defining appropriate values may, by dint of the constant
517 folding and dead code removal features above, remove entire
518 superfluous code blocks (e.g. completely remove instrumentation or
519 trace code for production use).
520 Where string values are being defined, the handling of quotes are
521 likely to be subject to the specifics of your command shell
522 environment, so you may need to experiment with quoting styles
523 depending on your platform, or you may find the option
524 <code>--define-from-module</code> more suitable for use.
525
526 </li>
527 <li><code>-define-from-module SOMEMODULE</code> &mdash; will load the named module (as
528 per the NodeJS <code>require()</code> function) and iterate all the exported
529 properties of the module defining them as symbol names to be defined
530 (as if by the <code>--define</code> option) per the name of each property
531 (i.e. without the module name prefix) and given the value of the
532 property. This is a much easier way to handle and document groups of
533 symbols to be defined rather than a large number of <code>--define</code>
534 options.
535
536 </li>
537 <li><code>--unsafe</code> &mdash; enable other additional optimizations that are known to be
538 unsafe in some contrived situations, but could still be generally useful.
539 For now only these:
540
541 <ul>
542 <li>foo.toString() ==&gt; foo+""
543 </li>
544 <li>new Array(x,&hellip;) ==&gt; [x,&hellip;]
545 </li>
546 <li>new Array(x) ==&gt; Array(x)
547
548 </li>
549 </ul>
550
551 </li>
552 <li><code>--max-line-len</code> (default 32K characters) &mdash; add a newline after around
553 32K characters. I've seen both FF and Chrome croak when all the code was
554 on a single line of around 670K. Pass &ndash;max-line-len 0 to disable this
555 safety feature.
556
557 </li>
558 <li><code>--reserved-names</code> &mdash; some libraries rely on certain names to be used, as
559 pointed out in issue #92 and #81, so this option allow you to exclude such
560 names from the mangler. For example, to keep names <code>require</code> and <code>$super</code>
561 intact you'd specify &ndash;reserved-names "require,$super".
562
563 </li>
564 <li><code>--inline-script</code> &ndash; when you want to include the output literally in an
565 HTML <code>&lt;script&gt;</code> tag you can use this option to prevent <code>&lt;/script</code> from
566 showing up in the output.
567
568 </li>
569 <li><code>--lift-vars</code> &ndash; when you pass this, UglifyJS will apply the following
570 transformations (see the notes in API, <code>ast_lift_variables</code>):
571
572 <ul>
573 <li>put all <code>var</code> declarations at the start of the scope
574 </li>
575 <li>make sure a variable is declared only once
576 </li>
577 <li>discard unused function arguments
578 </li>
579 <li>discard unused inner (named) functions
580 </li>
581 <li>finally, try to merge assignments into that one <code>var</code> declaration, if
582 possible.
583 </li>
584 </ul>
585
586 </li>
587 </ul>
588
589
590
591 </div>
592
593 <div id="outline-container-2-4-1" class="outline-4">
594 <h4 id="sec-2-4-1"><span class="section-number-4">2.4.1</span> API </h4>
595 <div class="outline-text-4" id="text-2-4-1">
596
597
598 <p>
599 To use the library from JavaScript, you'd do the following (example for
600 NodeJS):
601 </p>
602
603
604
605 <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;
606 <span class="org-keyword">var</span> <span class="org-variable-name">pro</span> = require(<span class="org-string">"uglify-js"</span>).uglify;
607
608 <span class="org-keyword">var</span> <span class="org-variable-name">orig_code</span> = <span class="org-string">"... JS code here"</span>;
609 <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>
610 ast = pro.ast_mangle(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">get a new AST with mangled names</span>
611 ast = pro.ast_squeeze(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">get an AST with compression optimizations</span>
612 <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>
613 </pre>
614
615
616 <p>
617 The above performs the full compression that is possible right now. As you
618 can see, there are a sequence of steps which you can apply. For example if
619 you want compressed output but for some reason you don't want to mangle
620 variable names, you would simply skip the line that calls
621 <code>pro.ast_mangle(ast)</code>.
622 </p>
623 <p>
624 Some of these functions take optional arguments. Here's a description:
625 </p>
626 <ul>
627 <li><code>jsp.parse(code, strict_semicolons)</code> &ndash; parses JS code and returns an AST.
628 <code>strict_semicolons</code> is optional and defaults to <code>false</code>. If you pass
629 <code>true</code> then the parser will throw an error when it expects a semicolon and
630 it doesn't find it. For most JS code you don't want that, but it's useful
631 if you want to strictly sanitize your code.
632
633 </li>
634 <li><code>pro.ast_lift_variables(ast)</code> &ndash; merge and move <code>var</code> declarations to the
635 scop of the scope; discard unused function arguments or variables; discard
636 unused (named) inner functions. It also tries to merge assignments
637 following the <code>var</code> declaration into it.
638
639 <p>
640 If your code is very hand-optimized concerning <code>var</code> declarations, this
641 lifting variable declarations might actually increase size. For me it
642 helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also
643 note that (since it's not enabled by default) this operation isn't yet
644 heavily tested (please report if you find issues!).
645 </p>
646 <p>
647 Note that although it might increase the image size (on jQuery it gains
648 865 bytes, 243 after gzip) it's technically more correct: in certain
649 situations, dead code removal might drop variable declarations, which
650 would not happen if the variables are lifted in advance.
651 </p>
652 <p>
653 Here's an example of what it does:
654 </p></li>
655 </ul>
656
657
658
659
660
661 <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>) {
662 <span class="org-keyword">var</span> <span class="org-variable-name">q</span>;
663 <span class="org-keyword">var</span> <span class="org-variable-name">w</span>;
664 w = 10;
665 q = 20;
666 <span class="org-keyword">for</span> (<span class="org-keyword">var</span> <span class="org-variable-name">i</span> = 1; i &lt; 10; ++i) {
667 <span class="org-keyword">var</span> <span class="org-variable-name">boo</span> = foo(a);
668 }
669 <span class="org-keyword">for</span> (<span class="org-keyword">var</span> <span class="org-variable-name">i</span> = 0; i &lt; 1; ++i) {
670 <span class="org-keyword">var</span> <span class="org-variable-name">boo</span> = bar(c);
671 }
672 <span class="org-keyword">function</span> <span class="org-function-name">foo</span>(){ ... }
673 <span class="org-keyword">function</span> <span class="org-function-name">bar</span>(){ ... }
674 <span class="org-keyword">function</span> <span class="org-function-name">baz</span>(){ ... }
675 }
676
677 <span class="org-comment-delimiter">// </span><span class="org-comment">transforms into ==&gt;</span>
678
679 <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>) {
680 <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;
681 <span class="org-keyword">for</span> (i = 1; i &lt; 10; ++i) {
682 boo = foo(a);
683 }
684 <span class="org-keyword">for</span> (i = 0; i &lt; 1; ++i) {
685 boo = bar(c);
686 }
687 <span class="org-keyword">function</span> <span class="org-function-name">foo</span>() { ... }
688 <span class="org-keyword">function</span> <span class="org-function-name">bar</span>() { ... }
689 }
690 </pre>
691
692
693 <ul>
694 <li><code>pro.ast_mangle(ast, options)</code> &ndash; generates a new AST containing mangled
695 (compressed) variable and function names. It supports the following
696 options:
697
698 <ul>
699 <li><code>toplevel</code> &ndash; mangle toplevel names (by default we don't touch them).
700 </li>
701 <li><code>except</code> &ndash; an array of names to exclude from compression.
702 </li>
703 <li><code>defines</code> &ndash; an object with properties named after symbols to
704 replace (see the <code>--define</code> option for the script) and the values
705 representing the AST replacement value. For example,
706 <code>{ defines: { DEBUG: ['name', 'false'], VERSION: ['string', '1.0'] } }</code>
707
708 </li>
709 </ul>
710
711 </li>
712 <li><code>pro.ast_squeeze(ast, options)</code> &ndash; employs further optimizations designed
713 to reduce the size of the code that <code>gen_code</code> would generate from the
714 AST. Returns a new AST. <code>options</code> can be a hash; the supported options
715 are:
716
717 <ul>
718 <li><code>make_seqs</code> (default true) which will cause consecutive statements in a
719 block to be merged using the "sequence" (comma) operator
720
721 </li>
722 <li><code>dead_code</code> (default true) which will remove unreachable code.
723
724 </li>
725 </ul>
726
727 </li>
728 <li><code>pro.gen_code(ast, options)</code> &ndash; generates JS code from the AST. By
729 default it's minified, but using the <code>options</code> argument you can get nicely
730 formatted output. <code>options</code> is, well, optional :-) and if you pass it it
731 must be an object and supports the following properties (below you can see
732 the default values):
733
734 <ul>
735 <li><code>beautify: false</code> &ndash; pass <code>true</code> if you want indented output
736 </li>
737 <li><code>indent_start: 0</code> (only applies when <code>beautify</code> is <code>true</code>) &ndash; initial
738 indentation in spaces
739 </li>
740 <li><code>indent_level: 4</code> (only applies when <code>beautify</code> is <code>true</code>) --
741 indentation level, in spaces (pass an even number)
742 </li>
743 <li><code>quote_keys: false</code> &ndash; if you pass <code>true</code> it will quote all keys in
744 literal objects
745 </li>
746 <li><code>space_colon: false</code> (only applies when <code>beautify</code> is <code>true</code>) &ndash; wether
747 to put a space before the colon in object literals
748 </li>
749 <li><code>ascii_only: false</code> &ndash; pass <code>true</code> if you want to encode non-ASCII
750 characters as <code>\uXXXX</code>.
751 </li>
752 <li><code>inline_script: false</code> &ndash; pass <code>true</code> to escape occurrences of
753 <code>&lt;/script</code> in strings
754 </li>
755 </ul>
756
757 </li>
758 </ul>
759
760
761 </div>
762
763 </div>
764
765 <div id="outline-container-2-4-2" class="outline-4">
766 <h4 id="sec-2-4-2"><span class="section-number-4">2.4.2</span> Beautifier shortcoming &ndash; no more comments </h4>
767 <div class="outline-text-4" id="text-2-4-2">
768
769
770 <p>
771 The beautifier can be used as a general purpose indentation tool. It's
772 useful when you want to make a minified file readable. One limitation,
773 though, is that it discards all comments, so you don't really want to use it
774 to reformat your code, unless you don't have, or don't care about, comments.
775 </p>
776 <p>
777 In fact it's not the beautifier who discards comments &mdash; they are dumped at
778 the parsing stage, when we build the initial AST. Comments don't really
779 make sense in the AST, and while we could add nodes for them, it would be
780 inconvenient because we'd have to add special rules to ignore them at all
781 the processing stages.
782 </p>
783 </div>
784
785 </div>
786
787 <div id="outline-container-2-4-3" class="outline-4">
788 <h4 id="sec-2-4-3"><span class="section-number-4">2.4.3</span> Use as a code pre-processor </h4>
789 <div class="outline-text-4" id="text-2-4-3">
790
791
792 <p>
793 The <code>--define</code> option can be used, particularly when combined with the
794 constant folding logic, as a form of pre-processor to enable or remove
795 particular constructions, such as might be used for instrumenting
796 development code, or to produce variations aimed at a specific
797 platform.
798 </p>
799 <p>
800 The code below illustrates the way this can be done, and how the
801 symbol replacement is performed.
802 </p>
803
804
805
806 <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>) {
807 DEVMODE = <span class="org-constant">true</span>;
808 }
809
810 <span class="org-function-name">CLAUSE2</span>: <span class="org-keyword">function</span> init() {
811 <span class="org-keyword">if</span> (DEVMODE) {
812 console.log(<span class="org-string">"init() called"</span>);
813 }
814 ....
815 DEVMODE &amp;amp;&amp;amp; console.log(<span class="org-string">"init() complete"</span>);
816 }
817
818 <span class="org-function-name">CLAUSE3</span>: <span class="org-keyword">function</span> reportDeviceStatus(<span class="org-variable-name">device</span>) {
819 <span class="org-keyword">var</span> <span class="org-variable-name">DEVMODE</span> = device.mode, <span class="org-variable-name">DEVNAME</span> = device.name;
820 <span class="org-keyword">if</span> (DEVMODE === <span class="org-string">'open'</span>) {
821 ....
822 }
823 }
824 </pre>
825
826
827 <p>
828 When the above code is normally executed, the undeclared global
829 variable <code>DEVMODE</code> will be assigned the value <b>true</b> (see <code>CLAUSE1</code>)
830 and so the <code>init()</code> function (<code>CLAUSE2</code>) will write messages to the
831 console log when executed, but in <code>CLAUSE3</code> a locally declared
832 variable will mask access to the <code>DEVMODE</code> global symbol.
833 </p>
834 <p>
835 If the above code is processed by UglifyJS with an argument of
836 <code>--define DEVMODE=false</code> then UglifyJS will replace <code>DEVMODE</code> with the
837 boolean constant value <b>false</b> within <code>CLAUSE1</code> and <code>CLAUSE2</code>, but it
838 will leave <code>CLAUSE3</code> as it stands because there <code>DEVMODE</code> resolves to
839 a validly declared variable.
840 </p>
841 <p>
842 And more so, the constant-folding features of UglifyJS will recognise
843 that the <code>if</code> condition of <code>CLAUSE1</code> is thus always false, and so will
844 remove the test and body of <code>CLAUSE1</code> altogether (including the
845 otherwise slightly problematical statement <code>false = true;</code> which it
846 will have formed by replacing <code>DEVMODE</code> in the body). Similarly,
847 within <code>CLAUSE2</code> both calls to <code>console.log()</code> will be removed
848 altogether.
849 </p>
850 <p>
851 In this way you can mimic, to a limited degree, the functionality of
852 the C/C++ pre-processor to enable or completely remove blocks
853 depending on how certain symbols are defined - perhaps using UglifyJS
854 to generate different versions of source aimed at different
855 environments
856 </p>
857 <p>
858 It is recommmended (but not made mandatory) that symbols designed for
859 this purpose are given names consisting of <code>UPPER_CASE_LETTERS</code> to
860 distinguish them from other (normal) symbols and avoid the sort of
861 clash that <code>CLAUSE3</code> above illustrates.
862 </p>
863 </div>
864 </div>
865
866 </div>
867
868 <div id="outline-container-2-5" class="outline-3">
869 <h3 id="sec-2-5"><span class="section-number-3">2.5</span> Compression &ndash; how good is it? </h3>
870 <div class="outline-text-3" id="text-2-5">
871
872
873 <p>
874 Here are updated statistics. (I also updated my Google Closure and YUI
875 installations).
876 </p>
877 <p>
878 We're still a lot better than YUI in terms of compression, though slightly
879 slower. We're still a lot faster than Closure, and compression after gzip
880 is comparable.
881 </p>
882 <table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
883 <caption></caption>
884 <colgroup><col class="left" /><col class="left" /><col class="right" /><col class="left" /><col class="right" /><col class="left" /><col class="right" />
885 </colgroup>
886 <thead>
887 <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>
888 </thead>
889 <tbody>
890 <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>
891 <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>
892 <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>
893 <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>
894 </tbody>
895 </table>
896
897
898 </div>
899
900 </div>
901
902 <div id="outline-container-2-6" class="outline-3">
903 <h3 id="sec-2-6"><span class="section-number-3">2.6</span> Bugs? </h3>
904 <div class="outline-text-3" id="text-2-6">
905
906
907 <p>
908 Unfortunately, for the time being there is no automated test suite. But I
909 ran the compressor manually on non-trivial code, and then I tested that the
910 generated code works as expected. A few hundred times.
911 </p>
912 <p>
913 DynarchLIB was started in times when there was no good JS minifier.
914 Therefore I was quite religious about trying to write short code manually,
915 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
916 = 10 : b = 20”, though the more readable version would clearly be to use
917 “if/else”.
918 </p>
919 <p>
920 Since the parser/compressor runs fine on DL and jQuery, I'm quite confident
921 that it's solid enough for production use. If you can identify any bugs,
922 I'd love to hear about them (<a href="http://groups.google.com/group/uglifyjs">use the Google Group</a> or email me directly).
923 </p>
924 </div>
925
926 </div>
927
928 <div id="outline-container-2-7" class="outline-3">
929 <h3 id="sec-2-7"><span class="section-number-3">2.7</span> Links </h3>
930 <div class="outline-text-3" id="text-2-7">
931
932
933 <ul>
934 <li>Twitter: <a href="http://twitter.com/UglifyJS">@UglifyJS</a>
935 </li>
936 <li>Project at GitHub: <a href="http://github.com/mishoo/UglifyJS">http://github.com/mishoo/UglifyJS</a>
937 </li>
938 <li>Google Group: <a href="http://groups.google.com/group/uglifyjs">http://groups.google.com/group/uglifyjs</a>
939 </li>
940 <li>Common Lisp JS parser: <a href="http://marijn.haverbeke.nl/parse-js/">http://marijn.haverbeke.nl/parse-js/</a>
941 </li>
942 <li>JS-to-Lisp compiler: <a href="http://github.com/marijnh/js">http://github.com/marijnh/js</a>
943 </li>
944 <li>Common Lisp JS uglifier: <a href="http://github.com/mishoo/cl-uglify-js">http://github.com/mishoo/cl-uglify-js</a>
945 </li>
946 </ul>
947
948
949 </div>
950
951 </div>
952
953 <div id="outline-container-2-8" class="outline-3">
954 <h3 id="sec-2-8"><span class="section-number-3">2.8</span> License </h3>
955 <div class="outline-text-3" id="text-2-8">
956
957
958 <p>
959 UglifyJS is released under the BSD license:
960 </p>
961
962
963
964 <pre class="example">Copyright 2010 (c) Mihai Bazon &lt;[email protected]&gt;
965 Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
966
967 Redistribution and use in source and binary forms, with or without
968 modification, are permitted provided that the following conditions
969 are met:
970
971 * Redistributions of source code must retain the above
972 copyright notice, this list of conditions and the following
973 disclaimer.
974
975 * Redistributions in binary form must reproduce the above
976 copyright notice, this list of conditions and the following
977 disclaimer in the documentation and/or other materials
978 provided with the distribution.
979
980 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
981 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
982 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
983 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
984 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
985 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
986 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
987 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
988 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
989 TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
990 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
991 SUCH DAMAGE.
992 </pre>
993
994
995 <div id="footnotes">
996 <h2 class="footnotes">Footnotes: </h2>
997 <div id="text-footnotes">
998 <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
999 <a href="http://marijn.haverbeke.nl/parse-js/">parse-js</a> library, and Marijn pushed fixes literally in minutes.
1000 </p></div>
1001 </div>
1002 </div>
1003
1004 </div>
1005 </div>
1006 </div>
1007
1008 <div id="postamble">
1009 <p class="date">Date: 2012-11-22 10:46:14 EET</p>
1010 <p class="author">Author: Mihai Bazon</p>
1011 <p class="creator">Org version 7.7 with Emacs version 24</p>
1012 <a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>
1013
1014 </div>
1015 </body>
1016 </html>