Nodejs merge compression JavaScript and CSS Tutorial

Source: Internet
Author: User
Tags closure md5 require

For the compression tool front-end siege division is the most common is the Yahoo Yui compressor/google closure compiler.

Compared to other compression tools in JS and CSS compression is relatively mature, compression rate is also better.

Generally choose to combine with ant to compress and merge, the effect is good, but more biased towards the individual, team collaboration everyone deployed java/ant some trouble.

It is also a relatively good choice for individual developers to use Ant. For teams, the best solution is to compress on the server side, and everyone just needs to log in and execute a unified script.

The following shares the approximate test results and the reasons for using Nodejs compression to merge Js/css.

JS Part uses UGLIFYJS

1. Compress jquery 1.8,253 KB: Use Uglifyjs (UJ): 90.5 kb; use closure Compiler (hereinafter referred to as CC): 91.1 KB.

2. If the closure (function ($, window, undefined) {...}) (JQuery, window); Within the unused Function/variables

CC will be deleted unused; UJ all reservations By default, plus Pro.ast_lift_variables (AST) removes unused functions/variables (objects/arrays are not deleted).

If the direct leak is under the window, two is roughly the same.

3. Function C () {2}, CC will warn that UJ will not

4. Function C () {E () 2} will throw an exception, showing the number of rows, and the reason for the error. CC Prompt column error, uj not.

5. Function C () {e (); 2}, all retain the 2,CC warning, uglifyjs no information

6. CC shows all the errors in JS at once (some are caused by the previous error, so part is false), UJ displays only one error at a time.

7.0 = {}; CC will complain, and Uj will not.

8. If statements can be well optimized.

9. cc prefers to insert the statements within a variable/function (structure simple) directly into the place where they are used, uj to remain the same.

If there is less content within the function, CC inserts the contents of the function directly into the place where it is invoked, such as:

Function C () {xxxxxxx (' 12345678901234567 ');}

Function C () {xxxxxx.yyyyy (' 12345678901234 ');}

Function C () {xxxxxx.yyyyy.zzzz (' 12345678901 ');}

Function C () {if (X) {alert (' 1234 ')};alert (' 12 ');}

When C () is called in other functions, the C () method is removed and the contents of C () are moved here

(When the string length inside is +1, the original function C () is used directly, so CC here is based on the character length).

10. If it is a very long string, var str = ' Very long ... Very long '; Using STR,CC in other functions inserts the value of STR directly, and UJ does not.

11.10000 will turn into 1e4.

Alert (3*7) will be turned into alert (21).

Function C () {}; Function B () {return; C ();}; Cc/uj (open--lift-vars) deletes the code for C ().

14. This Code: (function () {return;}) (); CC will be deleted, UJ will not.

In summary, CC is the compiler, there are advanced optimization options, UJ is currently only a compressor. CC prefers to insert the string value/content simple function content outside the function directly into the place where it is used, so it sometimes increases the size of the compressed file.

For compressed size, UJ compression is generally slightly larger than cc, generally around 1KB.

Compression speed, cc think of things more, and need Java, so compression slow, UJ speed quickly.

If the site structure is complex, JS more often, the speed advantage of UJ is very obvious.

So team members without JS Novice, the use of UJ is a good choice.

In addition, UGLIFYJS2 is also in development, better than UJ1 compression effect, HTTPS://GITHUB.COM/MISHOO/UGLIFYJS2,

Contrast UGLIFYJS1:

(function () {return;}) (); will become: function () {} (), delete return;

0 = {}; Still will not be an error;

When the unused method/variable is removed, the warn information is output;

Function C () {e (); 2} will delete 2 and have warn information;

The line number of the hint message is biased (1 lines less);

Because it is still a beta version, UJ2 Some of the problems are normal, UJ2 by UJ1 improvements, the test also did not find significant bugs, so the use of UJ2 is also reliable.

PS: A recent application found 2 bugs:

Useless internal variables, not removed intact, left "var;"

Compress the end of the file without adding ";" Number, when 2 files are merged, if so, the problem is big:

var a={};a.x=function () {Console.log (this)}//file1
(function () {...}) ()//file2//Becomes a.x () ().

So the above 2 bugs, need to write their own 2 to solve out.

CSS part with CLEAN-CSS

The CSS compression found are:

Https://github.com/GoalSmashers/clean-css

Https://github.com/ded/sqwish

Https://github.com/fczuardi/node-css-compressor

After comparison, select the CLEAN-CSS, compression speed and effect are good, the problem is found:. a{} Such Content-free rules will not be cleaned up.

Instead of Nodejs compression, 1 is the source is JS, found that the bug can be quickly resolved; 2 is Nodejs asynchronous multi-threaded IO features, can be multi-threaded compression, compression speed increased significantly; 3 is the unified environment, do not need to rely on Java. And merging files is also very simple.

The general idea of compression consolidation:

Build.js:

var argv = process.argv, arguments = Argv.splice (2);

Parameters used to receive passes, such as: sudo./build.js CSS {Project path}

var buildtype = arguments[0], ProjectPath = arguments[1];

Simple project, you can go to the assets directory in Project path to iterate through the files you want to compress.

Advanced point, you can write the file list to the configuration, var maps = require (' map '). Maps; Then traverse maps for compression merging, only compress map's structure one dimension is enough, if want to compress and merge, can change into two-dimensional structure.

More advanced point, traverse the folder to get the file to be compressed (find a way to remove the file does not need to be compressed), and then generate the file name to be merged according to the rules, and then automatically generate a map.

More advanced point, automatically generated map at the same time, for the file generation MD5, the next compression according to MD5 judge, if the file content changes, only compressed and regenerated map.

Of course, is not the best way behind, choose the right one is the best.

In general, this will make the "fool version" of the compression tool, only need to input parameters, others do not need to tube.

Our approach is to read the Header/footer section, where matching tokens generate the list of files to be compressed and the merged target file names, such as:

<!--target= "Pkg1.min.js" {{{-->
<script src= "A1.js" ></script>...<script src= "B1.js" ></script>
<!--}}}-->
<!--target= "Pkg2.min.js" {{--> ... <!--}}}}-->

It then generates a map with MD5, compares file changes, optionally compresses, and merges to target files targeted by target.

The development of the use of uncompressed, on-line compression before the merge, and then automatically put the Header/footer uncompressed comments, plus the merged js/css.

Using UglifyJS2, CLEAN-CSS compression code, has been placed to github,https://github.com/kairyou/f2e-tools/tree/master/libs.

Require build-css-cc.js or build-js-uj2.js, you can compress it using the build method inside.

In addition, compression needs to send an error to terminate and prompt, so the compression of the reading is the sync mode, but the generation of file map, generate MD5, merged file parts can be asynchronous way.

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.