New JavaScript code optimization tool UglifyJS

Source: Internet
Author: User

When jQuery 1.5 was released, john resig said that the code optimization program was switched from Google Closure to UglifyJS. The compression effect of the new tool was very satisfactory. UglifyJS is a server node. js compression program. I tested that the compression ratio is indeed relatively high. Therefore, it is recommended to write an article.

You can also try the online version of Uglifyjs:Http://sweet.fengyin.name/

If you are interested in uglifyjs, you can install it as follows.

1. Install the node. js Environment

2. Go to the upper right corner of the https://github.com/mishoo/UglifyJS and Download the entire package.

3. decompress and open UglifyJS/bin/uglifyjs.

4. Find

 
 
  1. global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");  
  2. var fs = require("fs");  
  3. var uglify = require("uglify-js"), // symlink ~/.node_libraries/uglify-js.js to ../uglify-js.js  
  4.     jsp = uglify.parser,  
  5.     pro = uglify.uglify;  

Replace

 
 
  1. global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");  
  2. var fs = require("fs");  
  3. require.paths.unshift(__dirname + "/../");  
  4. var uglify = require("index"),  
  5. jsp = uglify.parser,  
  6. pro = uglify.uglify; 

5. Run the cd command to the UglifyJS/bin/directory. Execute./uglifyjs/Your js path/xx. js. If the installation is successful, Your compressed code will be directly displayed in the command line. You can use./uglifyjs 1.js 2.js to save the compressed code to 2.js.

So far, the uglifyjs installation is complete, and I have also written a PHP class. You can call uglifyjs for compression.

 
 
  1. /* 
  2. # Code by https://fengyin.name 
  3. # DEMO http://sweet.fengyin.name/ 
  4. # Dual licensed under the MIT 
  5. */ 
  6.  
  7. $ Uglifyjs =NewUglifyjs (array (
  8.  'Node _ home'=>'/Usr/local/bin/node',
  9.  'Uglifyjs _ Path'=>'/Usr/UglifyJS/bin/uglifyjs',// Path of the uglifyjs compression tool. 
  10.  // -------- Additional parameter ---------// 
  11.  'Prefix'=>'-B',// The input parameter-B is formatted without being compressed. For more information, see command usage. 
  12.  'Append'=>''// Save the file. If it is null, the result is output directly on the command line. 
  13. ));
  14. $ Results = $ uglifyjs-> compress ($ _ FILES ['File'] ['Tmp _ name']);
  15.  
  16.  
  17. ClassUglifyjs {
  18. Function_ Construct ($ options = array ()){
  19. $This-> Options = $ options;
  20. }
  21. FunctionArgs ($ option ){
  22. Return$ Option ['Node _ home'].''. $ Option ['Uglifyjs _ Path'].'
  23. '. $ Option ['Prefix'].''. $ Option ['File'].''. $ Option ['Append'];
  24. }
  25. FunctionExec ($ cmd ){
  26. Exec ($ cmd.'2> & 1', $ Out, $ status );
  27. ReturnJson_encode (array (
  28. 'Shell'=>$ Cmd,
  29. 'Output'=> Implode ("\ N", $ Out ),
  30. 'Status'=> $ Status
  31. ));
  32. }
  33. FunctionCompress ($ file ){
  34. $This-> Options ['File'] = $ File;
  35. Return$This-> Exec ($This-> Args ($This-> Options ));
  36. }
  37. }
  38. ?>

The following is a Chinese description of the command line of uglifyjs.

Usage:

This is a script Assistant (Tool)-bin/uglifyjs-this library can be used to compress a script to a minimum.

Introduction:

Uglifyjs [Options...] [files]

File parameters should be placed behind the options. uglifyjs will read the javascript code in the file for processing.

If you do not specify the output file name, the processed content is output to the command line.

For example, uglifyjs 1.js 2.js will create a 2.js file to input the content processed by 1.js to this

For example, uglifyjs 1.js reads 1.js and outputs the result to the command line.

Supported options:

-B or -- beautify-parameter-B or -- beautify is used to beautify (Format) the code. Code will be compressed before beautification (not verified .)

-I N or -- indent N-number of spaces at the indent level

For example, uglifyjs-B 1.js 2.js will output the content format of 1.js to 2.js.

-Q or -- quote-keys-quote keys in literal objects (by default, only keys that cannot be identifier names will be quotes ).

-Nm or -- no-mangle-variable name is not shortened, meaning that the variable name in the Code is not shortened to abcdefg

-Ns or -- no-squeeze-do not use ast_squeeze () (it can make the code after various optimizations smaller and more readable .)

-Mt or -- mangle-toplevel-mangle names in the toplevel scope too (by default we don't do this ).

-- No-seqs-When ast_squeeze () is called (it will not be called unless you have added the -- no-squeeze parameter), it will reduce the rows that are repeatedly declared in a code block. For example, "a = 10; B = 20; foo ();" will be rewritten as "a = 10, B = 20, foo ();". In various cases, this will allow us to discard the parentheses in the code block (after some statement blocks become an independent declaration line ). This is the default one, because it seems safer and can save several hundred bytes, but it will be disabled after -- no-seqs is added.

-- No-dead-code-by default, UglifyJS will delete obviously inaccessible statements (such as return, throw, break, or continue statements) in the code, and some declarations that are not functions or variables ). This option can be used to disable this optimization function.

-Nc or -- no-copyright-by default, uglifyjs retains some initial tags (such as copyright information) in the generated code ). If you set this parameter, it will be disabled.

-O filename or -- output filename-output the result to a file with the specified file name. Without this parameter, the result will be output to the command line.

-

-Overwrite-if the code is read from a file (not directly input as a standard) and the -- overwrite parameter is used, the result will be written into the same file.

-- Ast-pass this if you want to get the Abstract Syntax Tree instead of JavaScript as output. Useful for debugging or learning more about the internals.

-- Ast-pass: If you want to obtain an abstract syntax tree that replaces javascript output, these parameters are useful when you debug or learn internal components.

-V or -- verbose-output some notes on STDERR (for now just how long each operation takes ).

-V or -- verbose-output some standard error messages (show how long each time is spent)

-- Extra-enable additional optimizations that have not yet been extensively tested. These might, or might not, break your code. If you find a bug using this option, please report a test case.

When you discover a BUG, you can add a breakpoint to optimize the code that has not been thoroughly tested. You can use this option to generate a test case.

-- Extra-enable

-- Unsafe-enable other additional optimizations that are known to be unsafe in some contrived situations, but cocould still be generally useful. For now only this:

Foo. toString () => foo + ""

It is also feasible to think of foo. toString (), but there are some insecure situations. We also need to add some optimizations, such as foo + ""

-- Max-line-len (default 32 K characters)-add a newline after around 32 K characters. I 've seen both FF and Chrome croak when all the code was on a single line of around 670 K. pass-max-line-len 0 to disable this safety feature.

When the size exceeds 32 KB, you need to add a line. I have found that when the line of Firefox and chorme Code exceeds kb, an alarm will be triggered. Use-max-line-len 0 to stop this Security Attribute

-- Reserved-names-some libraries rely on certain names to be used, as pointed out in issue #92 and #81, so this option allow you to exclude such names from the mangler. for example, to keep names require and $ super intact you 'd specify-reserved-names "require, $ super ".

-- Reserved-names-some class libraries will be used based on specific names, such as: #92 and #81. Therefore, this option allows you to exclude some keywords.

  1. Powerful JavaScript editor WebStorm 2.1 released
  2. JavaScript cross-origin summary and Solutions
  3. Use JavaScript to manage table data
  4. Hacker investigation: What is the most popular JavaScript library?
  5. Common sorting algorithms for JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.