ArticleDirectory
- Call of Global Array Constructor
- NPM Installation
- Install the latest version through GitHub
Uglifyjs is a javascript parsing/compression/formatting Tool Based on nodejs. It supports the Javascript platform of any commonjs Module System (it is not difficult to implement your own commonjs platform ). Uglifyjs re-generates JS through ParsingCodeSyntax tree, you can use ast to learn more code, or do a different implementation by yourself. Uglifyjs parser is implemented in parse-js.js, it is a very good parse.
Insecure Conversion
Uglifyjs is a javascript parsing/compression/formatting Tool Based on nodejs. It supports the Javascript platform of any commonjs Module System (it is not difficult to implement your own commonjs platform ).
Uglifyjs parses and re-generates the syntax tree of js code. You can use ast to learn more about the code or implement different implementations by yourself. Uglifyjs parser is implemented in parse-js.js and is part of a very good parse-js Common Lisp library.
(If you are looking for the Common Lisp version of uglifyjs, click here)
Another important part of uglifyjs is implemented in process. js. It is used to check and parse the generated AST:
-
- Use ast to regenerate JavaScript code: If you want to format the compressed code, you can select the indent parameter. You can also print the whitespace-free AST for compression purposes.
- shorten variable names: uglifyjs analyzes the code and generates new variable names, depending on the scope. These names are generally simplified to single characters and can intelligently process global variables, or eval () call and with {} block. In other words, if eval () or with {} is used in a specific scope, all variables in the scope and their parent scope will not be renamed, and all references pointing to such variables will not be changed.
- The following are some optimization rules that make the code more concise and efficient:
- Foo ["bar"] => Foo. Bar
- Delete block tag {}
- Declaration of merging variables: var A = 10; var B = 20 ;=> var A = 10, B = 20;
- Calculate a simple constant expression: 1 + 2*3 => 7. uglifyjs only replaces the calculation result with fewer bytes than the actual expression. For example, if the 1/3 result is 0.333333333333, It is not replaced.
- Consecutive statement blocks are merged into a sequence. In most cases, a statement is retained, and block brackets can be removed.
- If statement optimization:
- If (FOO) bar (); else Baz () ;=> Foo? Bar (): Baz ();
- If (! Foo) bar (); else Baz () ;=> Foo? Baz (): bar ();
- If (FOO) bar () ;=> Foo & Bar ();
- If (! Foo) bar () ;=> Foo | bar ();
- If (FOO) return bar (); else return Baz () ;=> return Foo? Bar (): Baz ();
- If (FOO) return bar (); else something () ;=>{ if (FOO) return bar (); something ()}
- Remove unused code and give a warning.
Insecure Conversion
Uglifyjs tries its best to increase the compression ratio while retaining the semantics. If your code logic becomes invalid after uglifyjs processing, or you have a better idea of optimizing and implementing uglifyjs, you can directly contact the author.
Call of Global Array Constructor
The following conversion is performed:
New Array ( 1 , 2 , 3 , 4 ) => [ 1 , 2 , 3 , 4 ] Array ( A , B , C ) => [ A , B , C ] New Array ( 5 ) => Array ( 5 ) New Array ( A ) => Array ( A )
These conversions are safe before array is redefined. Uglifyjs will also process the locally or globally redefined array, but it is recommended that you do not do this:
// Case 1. Global Declaration VaR Array ; New Array ( 1 , 2 , WWW . Csser . Com ); Array ( A , B ); // Or post Declaration New Array ( 1 , 2 , 3 ); VaR Array ; // Or define it as a function New Array ( 1 , 2 , 3 ); Function Array () { ... } // Case 2. declare in the function ( Function (){ A = New Array ( 1 , 2 , 3 ); B = Array ( 5 , 6 ); VaR Array ; })(); // Or ( Function ( Array ){ Return Array ( 5 , 6 , 7 ); })(); // Or ( Function (){ Return New Array ( 1 , 2 , 3 , 4 ); Function Array () { ... } })();
// And so on.
Installation through NPM
You can use NPM to install uglifyjs:
NPM install uglify-JS
Install the latest version through GitHub
# Clone a repository Mkdir - P / Where / You / Wanna / Put / ITCD / Where / You / Wanna / Put / Itgit clone git : // Github.com/mishoo/uglifyjs.git # Make the uglify module effective for nodejs Mkdir - P ~ /. Node_libraries/ CD ~ /. Node_libraries/ Ln - S / Where / You / Wanna / Put / It / Uglifyjs / Uglify - JS . JS # Support for command line calling Mkdir - P ~ /Bincd ~ / Binln - S / Where / You / Wanna / Put / It / Uglifyjs / Bin / Uglifyjs # (Then ~ /Add bin to $ PATH)
How to Use
Uglifyjs provides command line tools to support shell script operations:
Uglifyjs[Option...][File Name]
The last parameter is the JS file name to be processed. If this parameter is not specified, it is read from the standard input (stdin.
Supported options:
-
- -B or -- beautify-output formatting code. When this parameter is passed in, the following additional options are used to control formatting in a more elegant way:
- -I n or -- indent N-indent level (number of spaces)
- -Q or -- quote-keys-whether to use quotation marks to cause the key of the string object (by default, only the key names that cannot be correctly marked will be caused)
-
- -- Ascii-by default, uglifyjs does not process character encoding but directly outputs Unicode characters. By inputting this parameter, non-ASCII characters are converted to the \ cxxxx sequence (the output is always UTF-8 encoded, but input this option to get the output of the ASCII code ).
-
- -Nm or -- no-mangle-do not change the variable name
-
- -Ns or -- no-squeeze-do not call the ast_squeeze () function (this function will be optimized to make the result smaller and slightly less readable)
-
- -Mt or -- mangle-toplevel-disrupt variable names in top-level scopes (disabled by default)
-
- -- No-seqs-when you call ast_squeeze (), multiple statement blocks are merged into one statement block, for example, "A = 10; B = 20; Foo () "will be converted to" A = 10, B = 20, Foo ()"
-
- -- No-dead-code-the default uglifyjs will delete unused code and pass in this parameter to disable this function.
-
- -NC or -- no-copyright-by default, uglifyjs adds copyright information and other comments to the output code, and passes in this parameter to disable this function.
- -O file name or -- output file name-specifies the output file name. If not specified, it is printed to the standard output (stdout)
-
- -- Overwrite-if the input JS Code comes from a file rather than a standard input, the input parameter will overwrite the file.
-
- -- Ast-passing in this parameter will produce an abstract syntax tree instead of JavaScript, which is useful for debugging or understanding internal code.
-
- -V or -- verbose-output some information in the standard error (the current version only outputs the operation time)
-
- -- Extra-enable additional optimizations, which are not fully tested.
-
- -- Unsafe-enable other additional optimizations, which are known to be insecure under specific circumstances. Currently, only the following optimizations are supported:
- Foo. tostring () => Foo + ""
-
- -- Max-line-len (32 K byte by default)-adds a line break to 32 K byte, and passes in 0 to disable this function.
-
- -- Reserved-names-some class libraries depend on some variables, and the names specified by this parameter are not obfuscated. Multiple class libraries are separated by commas.
API
To use the uglifyjs class library in Javascript, refer to the following example (using nodejs as an example ):
VaR JSP = Require ( "Uglify-js" ). Parser ; VaR Pro = Require ( "Uglify-js" ). Uglify ; VaR Orig_code = "JavaScript code" ; VaR AST = JSP . Parse ( Orig_code ); // Parse the code and return the initial AST AST = Pro . Ast_mangle ( AST ); // Get the ast with variable name disorder AST = Pro . Ast_squeeze ( AST ); // Obtain the compressed and optimized AST VaR Final_code = Pro . Gen_code ( AST ); // Compressed code
The above code will immediately compress the code. As you can see, here you have gone through a series of steps, you may omit some steps to meet your needs.
Here, the function has some parameters. We will introduce them as follows:
-
- JSP. parse (Code, strict_semicolons)-parse the JS Code and return the ast. Strict_semicolons is optional. The default value is false. When true is passed in, the parser throws an error if it is expected to be a semicolon but cannot be found. We do not need to do this for most js code, but it is helpful to strictly constrain the code.
-
- Pro. ast_mangle (AST, options)-returns the ast that is mixed with the function name. It supports the following options:
- Toplevel-obfuscation of variables and function names in top-level scopes (disabled by default ).
- Effect-specifies the array of names not compressed
- Pro. ast_squeeze (AST, options)-enable deep optimization to reduce the code size and return a new ast. The options can be a hash. Supported parameters include:
- Make_seqs (true by default) combines multiple statement blocks into one.
- Dead_code (true by default) deletes unused code.
-
- Pro. gen_code (AST, options)-generate JS Code through ast. By default, the compressed code is output, but formatted output can be obtained by adjusting the option parameters. The options are optional. If the input must be an object, the following options are supported:
- Beautify: false-if you want to get formatted output, input true
- Indent_start: 0 (valid only when beau is true)-space for initial indentation
- Indent_level: 4 (valid only when beautify is true)-indent level, number of spaces
- Quote_keys: false-entering true will enclose the keys of all text objects in quotation marks.
- Space_colon: false (valid only when beautify is true)-whether to retain spaces before the colon
- Ascii_only: false-pass in true to encode non-ASCII characters to \ uxxxx
Conclusion
Uglifyjs is similar in syntax to Google compression, and has excellent performance. Therefore, we recommend that you use more practices!