[Reprint] With UglifyJS2 merge compression confusion JS Code--javascript series

Source: Internet
Author: User
Tags abstract language git clone

The zero-based NODEJS series article will show you how to benefit JavaScript as a server-side script through NODEJS Framework web development. The NODEJS framework is a V8-based engine and is the fastest JavaScript engine available today. The Chrome browser is based on V8, and opening 20-30 pages is a smooth one. The NODEJS Standard Web Development Framework Express helps us quickly build web sites that are more efficient than PHP and have a lower learning curve. Very suitable for small websites, personalization sites, our own Geek website!!

About the author

    • Zhang Dan (Conan), programmer Java,r,php,javascript
    • Weibo: @Conan_Z
    • Blog:http://blog.fens.me
    • Email: [Email protected]

Reprint please specify the source:
http://blog.fens.me/nodejs-uglifyjs2-js/

Objective

To do web front-end development, always consider the opening speed of the page, if the number of files less, the smaller the file length, you can directly improve the speed of the page access.

But in the development, in order to ensure the readability of the code, we write a lot of program files and very large, so as to deviate from the requirements of deployment, through the UglifyJS2 this tool, we can in the development process, the code file merging, confusion, compression, etc., to achieve optimal access performance.

Directory

    1. UGLIFYJS Introduction
    2. UglifyJS2 Introduction
    3. UGLIFYJS2 Installation
    4. UglifyJS2 command operation
    5. The UglifyJS2 API uses
1. Uglifyjs Introduction

Before we start UglifyJS2 introduction, let's talk about Uglifyjs first. UGLIFYJS is the predecessor of UglifyJS2, a toolkit for JavaScript-developed generic parsing, code compression, and code optimization. Uglifyjs is an arbitrary JavaScript platform that is developed based on the NODEJS environment and supports the COMMONJS module system.

The implementation of UGLIFYJS is divided into 2 main parts:

    • The abstract Syntax tree (AST) that generates the JS code is completed by Parse-js.js.
    • Iterate through the AST syntax tree and do various things, such as auto indent, shorten variable name, delete block bracket {}, go blank, constant expression, continuous variable declaration, block merge, remove inaccessible code, etc., through process.js.
2. UglifyJS2 Introduction

UglifyJS2 is the author's rewrite of Uglifyjs, which is a complete rewrite, not just an upgrade. From the UglifyJS2 Legal party page Introduction to see, UglifyJS2 the whole JS compression process, do a further refinement.

    • Parser, used to implement the abstract language method tree (AST).
    • The code generator generates JS code and source map via AST.
    • Compressor, used for the compression of JS code.
    • Mangler, used to reduce the naming of local variables and replace them with single letters.
    • Scope Analyzer, a tool used to determine the scope of variable definitions and the scope of variable references.
    • Tree Walker, AST trees traversal tool.
    • Tree transformer, AST tree conversion tool.

All of the above function code API is?? Around 6500 rows, smaller than other development packages with the same functionality. The author also provides an online version of the UglifyJS2 JS compression tool, http://lisperator.net/uglifyjs/, you can test it.

3. UglifyJS2 Installation

System environment:

    • Win7 64bit
    • nodejs:v0.10.5
    • npm:1.2.19

UglifyJS2 is very simple to install, and as with other packages in Nodejs, the global installation uses the following commands.

npm install uglify-js -g

You can also download the source code installation from GitHub.

git clone git://github.com/mishoo/UglifyJS2.gitcd UglifyJS2

When we use UglifyJS2, there are mainly 2 ways, one is to compress the specified JS file by command line operation, and the other is to compress the JS code in the file or in memory through the program's API call. I'll introduce you in two different situations.

4. UglifyJS2 command operation

After the global installation of UglifyJS2, we can use the UglifyJS2 command.

Printing the Help information for the UGLIFYJS command line will give you a long description.

D:\workspace\javascript\nodejs-uglifyjs2>uglifyjs-hd:\toolkit\nodejs\\node.exe D:\toolkit\nodejs\node_ Modules\uglify-js\bin\uglifyjs input1.js [Input2.js ...] [Options] Use a single dash to read input from the standard input. Note:by default there is no mangling/compression.  Without [options] it would simply parse input files and dump the Astwith whitespace and comments discarded. To achieve compression andmangling your need to use '-C ' and '-M '. Options:--source-map Specify an output file where to generate source map                                    . [string]--source-map-root the path to the original source to being included in T                      He source map. [string]--source-map-url the path to the source map to being added in//# SOURC  Emappingurl.                  Defaults to the value passed with--source-map.    [string]--source-map-include-sources Pass This flag if you want to include the Conte               NT of source files in the source map as Sourcescontent property. [Boolean]--in-source-map Input source map, useful if you ' re compressing JS  That is generated from some and other original code. --SCREW-IE8 Pass This flag if your don ' t care on full compliance with I                                                                       Nternet Explorer 6-8 Quirks (by default Uglifyjs'll try to be ie-proof).  [Boolean]--expr Parse a single expression,                  Rather than a program (for parsing JSON) [Boolean]-P,--prefix                           Skip prefix for original filenames that appear     In source maps.                                For Example-p 3 would drop 3 directories from file names and ensure they is Relative paths.                                You can also specify-p relative, which'll make UGLIFYJS figure out  itself the relative paths between original sources, the source map and the output                                                                        File.  [string]-O,--output output file (default STDOUT).                                                                        -B,--beautify beautify output/specify output options.      [string]-M,--mangle mangle names/pass mangler options.  [string]-R,--reserved reserved names to exclude from mangling. -C,--compress Enable compressor/pass compressor options.    Pass Options Like-c                            Hoist_vars=false,if_return=false. Use-c with no argument to use the default compression optio                                Ns. [String]-D,--define Global definitions [string]-E,--enclose Em   Bed everything in a big function, with a configurable parameter/argument list. [string]--comments Preserve Copyright comments in the output. By default this works like Google Closure, keeping jsdoc-sty Le comments that contain "@license" or "@preserve".                                You can optionally pass one of the following arguments to this flag:                          -"All" to keep all comments-a valid JS RegExp (needs to start with a      Slash) to keep only comments that match.                                Note that currently isn't *all* comments can be kept when compression are on, because of dead                              Code removal or cascading statements into sequences.  [string]--preamble preamble to prepend to the output. Can use this to insert a comment, for example for Licens  ing information.                                This is not being parsed, but the source map would adjust for its  Presence.                                                                       --stats Display operations run time on STDERR.                 [Boolean]--acorn use Acorn for parsing. [Boolean]--spidermonkey assume input files is SpiderMonkey AST forMat (as JSON). [Boolean]--self Build itself (UglifyJS2) as a library (implies--w Rap=uglifyjs--export-all) [Boolean]--wrap Embed everything in a big function, making th E "exports" and "global" variables available. You need to pass a argument to this option to specify the N       Ame that your module would take if included in, say, a browser. [string]--export-all only used if--wrap, this tells Uglifyjs to add C                                                                       Ode to automatically export all globals. [Boolean]--lint Display some scope warnings [Boolean]-V,--verbose V                    Erbose            [Boolean]-V,--version Print version number and exit.  [Boolean]--noerr Don ' t throw a error for unknown options In-c,-b                              Or-m. [Boolean]

To interpret the command parameters:

  • –source-map [string] to generate the source map file.
  • –source-map-root [string] that specifies the location of the source file that generated the source map.
  • –source-map-url [string] that specifies the Web access address of the source map.
  • –source-map-include-sources, the settings source file is included in the sources map.
  • –in-source-map, custom source map, used by other tools to generate the source map.
  • –SCREW-IE8, which is used to generate fully compatible IE6-8 code.
  • –expr, parses an expression or JSON.
  • -p,–prefix [string], skipping the prefix portion of the original file name, which specifies the relative path of the source file, sources map, and output file.
  • -o,–output [string], output to file.
  • -b,–beautify [string], output the formatted file.
  • -m,–mangle [string], the output variable name after the replacement of the file.
  • -r,–reserved [string], preserving the variable name and excluding the mangle procedure.
  • -c,–compress [string], output the compressed file.
  • -d,–define [string], defined globally.
  • -e,–enclose [string], merges all the code into a function, and provides a configurable list of parameters.
  • –comments [string], adding annotation parameters, such as @license, @preserve.
  • –preamble [string] To add a comment description.
  • –stats, displays the running status.
  • –acorn, use Acorn to parse.
  • –spidermonkey, parsing files in SpiderMonkey format, such as JSON.
  • –self, package UglifyJS2 as a dependent library.
  • –wrap, merge all the code into one function.
  • –export-all, used with –wrap, is automatically exported to the global environment.
  • –lint, which displays the environment's exception information.
  • -v,–verbose, print run log verbose.
  • -v,–version, print the version number.
  • –noerr, ignoring error command-line arguments.

By explaining the various parameters of the command line, we basically know what these parameters are, and I'll try it out below.

Write 2 simple JS files, demo.js, Main.js.

~ vi D:\workspace\javascript\nodejs-uglifyJS2\demo.js‘use strict‘;function hello(name){if(name===‘fens.me‘){return "Long time no see, "+name;}return "hello "+name;}console.log(hello(‘Conan‘));console.log(hello(‘fens.me‘));

Main.js

~ vi D:\workspace\javascript\nodejs-uglifyJS2\main.js‘use strict‘;function book(){    return [        {head:‘前言‘,page:‘/views/tpl/book-r1/preface.html‘,active:false},        {head:‘目录‘,page:‘/views/tpl/book-r1/contents.html‘,active:true},        {head:‘代码‘,page:‘/views/tpl/book-r1/code.html‘,active:false},        {head:‘试读‘,page:‘/views/tpl/book-r1/sample.html‘,active:false},        {head:‘勘误‘,page:‘/views/tpl/book-r1/mistake.html‘,active:false}    ];}var tab=function(arr,idx){for(var i=0;i<arr.length;i++){arr[i].active = (idx==i?true:false);}return arr;}console.log(tab(book(),3));

Next, with the UglifyJS2 command, merge two files, replace the variable name with a single letter, compress it, all the code is merged into a function, generate a source map, specify the source map from the site.

D:\workspace\javascript\nodejs-uglifyJS2>uglifyjs main.js demo.js -o foo.min.js --source-map foo.min.js.map --source-map-root http://onbook.me -p 5 -c -m --wrap --export-all

2 new files were generated in the current directory: Foo.min.js.map, foo.min.js, view these two files respectively.

Foo.min.js

!function(e,t){"use strict";function o(){return[{head:"前言",page:"/views/tpl/book-r1/preface.html",active:!1},{head:"目录",page:"/views/tpl/book-r1/contents.html",active:!0},{head:"代码",page:"/views/tpl/book-r1/code.html",active:!1},{head:"试读",page:"/views/tpl/book-r1/sample.html",active:!1},{head:"勘误",page:"/views/tpl/book-r1/mistake.html",active:!1}]}function n(e){return"fens.me"===e?"Long time no see, "+e:"hello "+e}t["true"]=e,console.log(a(o(),3));var a=function(e,t){for(var o=0;o<e.length;o++)e[o].active=t==o?!0:!1;return e};console.log(n("conan")),console.log(n("fens.me")),e.book="o,e.hello=n,e.tab=a}({},function(){return" this}());="" #="" sourcemappingurl="foo.min.js.map" <="" code="">

Foo.min.js.map

{"version":3,"file":"foo.min.js","sources":["?"],"names":["exports","global","book","head","page","active","hello","name","console","log","tab","arr","idx","i","length","this"],"mappings":"CAAC,SAASA,EAASC,GAAnB,YAEA,SAASC,KACL,QACKC,KAAK,KAAKC,KAAK,kCAAkCC,QAAO,IACxDF,KAAK,KAAKC,KAAK,mCAAmCC,QAAO,IACzDF,KAAK,KAAKC,KAAK,+BAA+BC,QAAO,IACrDF,KAAK,KAAKC,KAAK,iCAAiCC,QAAO,IACvDF,KAAK,KAAKC,KAAK,kCAAkCC,QAAO,IANjE,QAASC,GAAMC,GACd,MAAU,YAAPA,EACK,qBAAqBA,EAEtB,SAASA,EANWN,EAAO,QAAUD,EAY7CQ,QAAQC,IAAIC,EAAIR,IAAO,GADvB,IAAIQ,GAAI,SAASC,EAAIC,GACpB,IAAI,GAAIC,GAAE,EAAEA,EAAEF,EAAIG,OAAOD,IACxBF,EAAIE,GAAGR,OAAUO,GAAKC,GAAE,GAAK,CAE9B,OAAOF,GAGRH,SAAQC,IAAIH,EAAM,UAClBE,QAAQC,IAAIH,EAAM,mBAjBTJ,UAAAI,QASLI,MAX8E,WAAW,MAAOK","sourceRoot":"http://onbook.me"}

Through a simple command, the implementation of the JS code merging, compression, and so on, is really very convenient.

Download the Jquery-2.1.1.js file yourself and compare it with the official compressed file.

# 下载~ wget http://code.jquery.com/jquery-2.1.1.js~ wget http://code.jquery.com/jquery-2.1.1.min.js# 压缩~ uglifyjs jquery-2.1.1.js -o jquery-2.1.1.min.uglifyjs2.js -p 5 -c -m# 比较3个文件大小~ ls -l-rwx------  1 4294967295 mkpasswd 247351 Jul  6 16:26 jquery-2.1.1.js-rwx------  1 4294967295 mkpasswd  84245 Jul  6 16:32 jquery-2.1.1.min.js-rwx------  1 4294967295 mkpasswd  84113 Jul  6 16:28 jquery-2.1.1.min.uglifyjs2.js

I compressed files in the local jquery-2.1.1.min.uglifyjs2.js, and the jquery lawsuit network download compressed files jquery-2.1.1.min.js size, all around 84KB.

5. UglifyJS2 's API Usage

Another way to use is to put the UGLIFYJS2 package into the program, through the API to the JS file or JS code compression. First, create a new NPM project file, Package.json, and then download the UglifyJS2 dependency package.

New File Package.json

~ vi D:\workspace\javascript\nodejs-uglifyJS2\package.json{  "name": "nodejs-uglifyjs2",  "version": "0.0.1",  "description": "uglifyjs2",  "author": "Conan Zhang <[email protected]>",  "dependencies": {  }}

Download UglifyJS2 Dependency packages

D:\WORKSPACE\JAVASCRIPT\NODEJS-UGLIFYJS2&GT;NPM Install Uglify-js--savenpm WARN Package.json [email protected] No Readme data!npm http GET https://registry.npmjs.org/uglify-jsnpm http 304 https://registry.npmjs.org/uglify-jsnpm HTTP GET https://registry.npmjs.org/asyncnpm http GET https://registry.npmjs.org/source-mapnpm http GET https:// REGISTRY.NPMJS.ORG/OPTIMISTNPM http GET https://registry.npmjs.org/uglify-to-browserifynpm http 304 https:// REGISTRY.NPMJS.ORG/UGLIFY-TO-BROWSERIFYNPM HTTP 304 https://registry.npmjs.org/optimistnpm http 304 https:// REGISTRY.NPMJS.ORG/ASYNCNPM http 304 https://registry.npmjs.org/source-mapnpm http GET https://registry.npmjs.org/ WORDWRAPNPM http GET https://registry.npmjs.org/amdefinenpm http 304 https://registry.npmjs.org/wordwrapnpm http 304 Https://registry.npmjs.org/amdefine[email protected] node_modules\uglify-js├──[email protected]├──[ Email protected]├──[email protected] ([email protected]) └──[email protecteD] ([email protected]) 

We created a new file, Uglify2.js, for writing programs.

~ vi D:\workspace\javascript\nodejs-uglifyJS2\uglify2.js‘use strict‘;var UglifyJS = require(‘uglify-js‘);//代码压缩var result = UglifyJS.minify("var b = function () {};", {fromString: true});console.log("\n===========================");console.log(result);//文件压缩result = UglifyJS.minify(["demo.js"]);console.log("\n===========================");console.log(result.code);//多文件压缩,指定source map和网站来源result = UglifyJS.minify(["main.js","demo.js"],{    outSourceMap: "out.js.map",    sourceRoot: "http://onbook.me",    mangle:true});console.log("\n===========================");console.log(result.code);console.log(result.map);

Program output:

D:\workspace\javascript\nodejs-uglifyjs2>node uglify2.js==========================={code: ' var b=function () {}; ' , map: ' null '}=========================== "use strict"; function Hello (e) {return "fens.me" ===e? " Long time no See, "+e:" Hello "+e}var tab=function (E,o) {for (Var n=0;n<e.length;n++) e[n].active=o==n?! 0:!1;return E};console.log (Hello ("Conan")), Console.log (Hello ("fens.me")); =========================== "Use strict" function Book () {return[{head: "Preface", Page: "/views/tpl/book-r1/preface.html", Active:!1},{head: "Directory", page: "/views/ Tpl/book-r1/contents.html ", Active:!0},{head:" Code ", page:"/views/tpl/book-r1/code.html ", Active:!1},{head:" Probation ", Page: "/views/tpl/book-r1/sample.html", Active:!1},{head: "Errata", page: "/views/tpl/book-r1/mistake.html", active:!1}] }function Hello (e) {return "fens.me" ===e? " Long time no See, "+e:" Hello "+e}console.log (tab (Book (), 3)), Var tab=function (E,o) {for (Var t=0;t<e.length;t++) e[t]. active=o==t?! 0:!1;return E};console.log (Hello ("Conan")), Console.log (Hello ("fens.me"));//# sourcemappingurl=out.js.map{"Version": 3, "file": "Out.js.map", "Sources": ["Main.js", "Demo.js"], "names": ["book", "head "," page "," active "," Hello "," name "," Console "," Log "," tab "," Arr "," idx "," I "," Length "," Mappings ":" Aaaa,yaea,saasa, QACL,QACKC,KAAK,KAAKC,KAAK,KCAAKCC,QAAO,IACXDF,KAAK,KAAKC,KAAK,MCAAMCC,QAAO,IACZDF,KAAK,KAAKC,KAAK,+BAA+BC, Qaao,iacrdf,kaak,kaakc,kaak,icaaicc,qaao,iacvdf,kaak,kaakc,kaak,kcaakcc,qaao,icnje,qaasc,oaamc,gacd,maau,yaapa , Eack,qbaaqba,eaetb,saasa,edmjbc,qaaqc,iaaic,iaair,oaao,gcdvb,iaaiq,kaai,saasc,eaaic,gacpb,iaai,gaaic,gaae, Eaaea,eaaef,eaaig,oaaod,iacxbf,eaaie,gaagr,oaauo,gaakc,gaae,gaak,cae9b,oaaof,gagrh,saaqc,iaaih,maam,uaclbe, Qaaqc,iaaih,maam "," SourceRoot ":" Http://onbook.me "}

We see that the API to operate the UGLIFYJS2 package is quite simple, and if there is a traversal requirement for the AST tree, the API provides very useful function support.

But I found 2 problems during the testing of the API.

    • The mangle option is set through the API, but the output has no effect.
    • There are no APIs corresponding to the--wrap and--export-all command line arguments.

Through the introduction of this article, we basically understand the function of the uglifyJS2 package and how to use, then you can be assured that the JS code compression. In the actual front-end project, generally do not have to configure the UglifyJS2 package, but through grunt to call uglifyJS2 for code before the release of compression, about grunt use, please refer to the article: Grunt let Nodejs specification up.

Reprint please specify the source:
http://blog.fens.me/nodejs-uglifyjs2-js/

[Reprint] With UglifyJS2 merge compression confusion JS Code--javascript series

Related Article

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.