Merging and compressing JS files with Gruntjs

Source: Internet
Author: User

Why merge and compress your JS files?         A project development is complete we can always find a bunch of JS files very confusing. In general, when an HTML document is loaded, the browser reads the CSS, JS, pictures, and so on from top to bottom of the HTML code, except for files that you specify to load asynchronously. Every reading of a file, the browser sends a load request to the Web server, and the server will not start receiving the file until it finds that the request is not a problem. That is, each time a file is loaded, it consumes a certain amount of time on the server and on the client's back and forth.

Loading a file consumes time that can be ignored, the problem is that you display a complex web page may load n Many files, we can control the range, we can spend less time to spend a little bit less. The user is very picky about how fast the page loads!

For pictures We often merge some of the icons into a large picture with CSS background to get the corresponding picture to reduce the request. CSS is also usually a kind of media to write only one file, of course, this side to pay attention to the evil ie restrictions on CSS, refer to my blog: with scss need to be careful of IE several restrictions on CSS. For JS, it is common to merge and compress all the files that are used locally. Of course, the above exceptions are loaded for frames using the Requirejs class.

The so-called compression is to remove all whitespace, annotations, etc. do not affect the code removed, the long name is replaced by a short name to save characters. When your JS is compressed, in addition to the head may add additional file comments, all the JS code is a line, a lot of variable names into a ah a letter, completely lost readability. Then you see your JS from 300KB may be reduced to only 5KB. The only way to do this is to make the JS file smaller, so that it loads faster.

Gruntjs is a set of front-end automation tools, a Nodejs-based command-line tool, typically used to:

① Compressed Files
② Merging Files
③ Simple Grammar checkInstallation and use of Gruntjs

Gruntjs is a task management tool built on the basis of Nodejs.

    1. Download and install the Nodejs for your system on the NODEJS website. Today's Nodejs installation comes with NPM package management, so you don't have to install NPM anymore.
    2. Use NPM to install the Gruntjs CLI, because you want to execute GRUNTJS command at the command line:
      NPM install-g GRUNT-CLI
    3. Prepare the Package.json file in the development project root folder.
    4. Assign the command line to this root folder and execute
      NPM Install

To implement Gruntjs in your project, you need the following steps:

    1. Prepare the file gruntfile.js or Gruntfile.coffee.
    2. Assign the command line to this root folder and execute
      Grunt 
The Package.json configuration of this JSON file is for NPM package management. Here we just have to base on the Gruntjs official website to give a sample change is enough. Specific configuration Please refer to the Examiner Net: https://www.npmjs.org/doc/files/package.json.html

{
"Name": "Demo",
"File": "Zepto",
"Version": "0.1.0",
"description": "Demo",
"License": "MIT",
"Devdependencies": {
"Grunt": "~0.4.1",
"Grunt-contrib-jshint": "~0.6.3",
"Grunt-contrib-concat": "~0.3.0",
"Grunt-contrib-uglify": "~0.2.1",
"Grunt-contrib-requirejs": "~0.4.1",
"Grunt-contrib-copy": "~0.4.1",
"Grunt-contrib-clean": "~0.5.0",
"Grunt-strip": "~0.2.1"
},
"Dependencies": {
"Express": "3.x"
}
}

This example includes configuring the name of the project, the version number of the project, and the NPM package used for development. When executing NPM install, read this devdependencies content to download the corresponding package to the Node_modules folder in the project root folder. You can also specify the version number of the downloaded package.

Here, we merge, Compress JS need to use 2-3 NPM package. Each is:

    • Grunt
    • Grunt-contrib-concat Https://github.com/gruntjs/grunt-contrib-concat
      Used for merging files.
    • Grunt-contrib-uglify https://github.com/gruntjs/grunt-contrib-uglify
      For the compression of JS.

The name is in the middle with "contrib" for the GRUNTJS officially provided plug-ins.

In addition, the demo sample uses the Grunt-contrib-jshint is a plugin to check the JS syntax error, can help you to check the error when you merge files.

Configuration of the Gruntfile.js

A major gruntfile includes the following sections:

Module.exports =function(Grunt) {

Grunt.initconfig ({
Pkg:grunt.file.readJSON (' Package.json '),
//settings information for the plug-in here
TaskName: {}
});

//load the plug-in you want to use
Grunt.loadnpmtasks (' Grunt-taskname ');
//The task of the handbook
Grunt.registertask (' Default ', [' grunt-taskname ']);

};

The whole piece of code is included in a function, using Nodejs a notation that exposes a function and can be used by other files.

Merge JS Example:


Module.exports =function(Grunt) {
//project Configuration
Grunt.initconfig ({
Pkg:grunt.file.readJSON (' Package.json '),
Concat: {
Options: {
Separator: '; '
},
Dist: {
SRC: [' src/login.js ', ' src/reg.js ', ' src/index.js '],
Dest: ' Dest/cdel.min.js '
}
}
});
Grunt.loadnpmtasks (' Grunt-contrib-concat ');
//Default Task
Grunt.registertask (' Default ', [' concat ']);
}

"Concat" specifies the appropriate plug-in for this configuration. "Dev" is a subtask of my own definition, and I named it "Dev". A plug-in can have multiple sets of configurations to cope with different requirements, that is, under "concat" can include arbitrarily many of their own defined sub-tasks, each sub-task can have a different configuration.

Here I set the "banner" parameter, which is in a lot of file operation plug-ins, such as uglify, less, sass and so on. Its purpose is to add some information or code to the end of the target file header.

In this "banner", I added a file gaze for the app.debug.js that was finally generated. Several special codes are also used:

\ n
newline character, after writing the file, the characters before and after the line will be branch.
<%= Pkg.name%>
similar to the ASP's notation. The PKG is a JSON that is read with Grunt.file.readJSON (' Package.json ') and has been converted to a JS object. This code will be replaced with "My-project-name" when writing to the file, as shown in the previous Package.json demo sample.
in
fact, from here we can see that in the grunt configuration, we can use the JS object and JSON to do the auxiliary configuration.
<%= grunt.template.today ("Yyyy-mm-dd")%>
This is a grunt approach that allows you to execute the task time and specify the resulting format.

When performing this concat task, my app.debug.js head will have the following gaze:

/* !
* My-project-name-js for Debug
* @licence my-project-name-v0.1.0 (2014-07-07)
* Http://blog.csdn.net/jennieji | Licence:mit
*/

In the file path, you can use some matching symbols. If I use an asterisk "*.js" to indicate the random name of the JS file, two asterisks "* *" means the current folder or sub-folder. So the JS file under the "js/app/" folder and all its subfolders will be merged into the App.debug.js file.

After configuration, also remember to load plug-ins and register you this task, or will error!

Loading plug-ins is the name of the plugin NPM package "Grunt-contrib-concat" passed to the Grunt.loadnpmtasks method.

The task of registration is to use the Grunt.registertask method. The first parameter is the name of the task queue for the register, and the default task queue for this gruntfile is written as "default". The second parameter is an array of task names to be run by this task queue, where the task name is used in the Initconfig configuration with the name "Concat". Change the code such as the following:

// load the plug-in you want to use
Grunt.loadnpmtasks (' Grunt-contrib-concat ');
// The task of the handbook
Grunt.registertask (' Default ', [' concat ']);

If you write this, you can run the JS merge once by typing the following command directly into the command line:

Grunt

Assuming "default" is changed to another name, such as "Debug", then the command line needs to be entered:

Grunt Debug

Adding uglify compression JS also makes a similar configuration. Note that this is not the same as the configuration of the source file and the destination file. is in the files parameter with "destination file path: [Source file path 1, source file path 2,...]" Format to write.


Compression JS Example:

Module.exports =function(Grunt) {
//project Configuration
Grunt.initconfig ({
Pkg:grunt.file.readJSON (' Package.json '),
Uglify: {
Options: {
Banner: '/*! <%= pkg.file%> <%= grunt.template.today ("Yyyy-mm-dd")%> */\n '
},
Build: {
SRC: ' src/<%=pkg.file%>.js ',
Dest: ' dest/<%= pkg.file%>.min.js '
}
}
});
//Load plug-ins that provide "uglify" tasks
Grunt.loadnpmtasks (' grunt-contrib-uglify ');
//Default Task
Grunt.registertask (' Default ', [' uglify ']);
}

Merging and compressing JS files with Gruntjs

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.