Merging and compressing JS files with Gruntjs

Source: Internet
Author: User

Long-term east busy west busy, but not busy to update their blog, the lack of output, very ashamed

I remember the first time I contacted Gruntjs to Nodejs smattering, so it took some time to get acquainted with it. This article hopes to help friends get started quickly.


Why merge and compress your JS files?

Before you begin, let me reiterate this question. Because often when helping to change things to see the HTML page quoted N JS, and usually see this to know how bad this person js write. HTML interspersed with a bunch of JS code I will not spit slot.

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.

Everything is for the better performance ... Which day we go down the speed and the server uplink speed are upgraded to the GB level which worry about this?


Installation and use of Gruntjs

Gruntjs is a task management tool built on the basis of Nodejs. I do not repeat the concept, in addition to configuration annoying very good.

The installation method of Gruntjs is introduced in detail on the official website. Click to view the official website Tutorials >>

The summary is actually just a few steps:

    1. Download and install the Nodejs for your system on the NODEJS website. Now the 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 directory. I will explain the contents of this file in detail later.
    4. Assign the command line to this root directory and run
      NPM Install

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

    1. Prepare the file gruntfile.js or Gruntfile.coffee. The contents of the file I will explain in detail later.
    2. Assign the command line to this root directory and run
      Grunt

Configuration of the Package.json

This JSON file is for NPM package management. Here we only need to according to Gruntjs official website to give an example of change is enough. For detailed configuration, please refer to the official website: https://www.npmjs.org/doc/files/package.json.html

Examples of Gruntjs official website:

{  "name": "My-project-name",  "version": "0.1.0",  "Devdependencies": {    "grunt": "~0.4.5",    " Grunt-contrib-jshint ":" ~0.10.0 ",    " Grunt-contrib-nodeunit ":" ~0.3.3 ",    " grunt-contrib-uglify ":" ~0.4.0 "  }}

This example contains the name of the project, the version of the project, and the NPM package used for the development. When running NPM install, read the contents of this devdependencies to download the corresponding package to the Node_modules folder in the project root directory. You can also specify the version of the downloaded package. There are also symbols and notation for the version to specify a range of versions. Click to view version number syntax details >>

In general, you can find and select the grunt package you want to use on GitHub, and write the current version directly, as 0.3.3 specifies the current version. Or select an adjacent version with the "~" symbol before the version number. or x to replace the last 3, write 0.3.x, select 0.3. The latest version of the beginning, because the last number change is usually the developer fixed the bug without any configuration or grammatical changes.

In this case, we need to use 2-3 NPM packages to merge and compress JS. respectively:

    • Grunt
    • Grunt-contrib-concat
      Used for merging files.
    • Grunt-contrib-uglify
      For the compression of JS.

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

I said 2-3 packets because grunt-contrib-uglify can also merge multiple files into one file directly, but it will "change" the code. Here I would like to eventually generate two files: one is purely to merge all the JS code without changes to debug debugging, and the other is compressed JS, that is, all debugging through the release of the project when the final use of JS. So I also used the grunt-contrib-concat.

In addition, the grunt-contrib-jshint used in the example is a plugin to check for JS syntax errors, which can help you to check for errors when you merge files, but sometimes it hurts a bit. Here I don't need it to cut the space.

Modify the example above to read as follows:

{  "name": "My-project-name",  "version": "0.1.0",  "Devdependencies": {    "grunt": "~0.4.5",    " Grunt-contrib-concat ":" 0.5.x ","    grunt-contrib-uglify ":" 0.5.x "  }}

Configuration of the Gruntfile.js

A basic gruntfile consists of the following parts:

Module.exports = function (grunt) {  grunt.initconfig ({    Pkg:grunt.file.readJSON (' Package.json '),    // The settings information for the plug-in here    taskname: {}  });  Load the plugin  grunt.loadnpmtasks (' Grunt-taskname ') to be used;  Register Task  grunt.registertask (' Default ', [' grunt-taskname ']);};

The entire code is contained within a function, using Nodejs a notation that exposes a function to be used by other files.

The grunt.initconfig is used to receive configuration information for each plug-in. The configuration options for each plugin can be found on their own GitHub project pages, and are basically similar. Such as:

Grunt.initconfig ({    Pkg:grunt.file.readJSON (' Package.json '),    //Task name, according to the plugin's instructions to write concat: {//Sub-task name, this name with you      Dev: {      //optional configuration parameter        options: {          banner: '/*!\n * <%= pkg.name%>-JS for debug\n * @licence <%= PK G.name%>-v<%= pkg.version%> (<%= grunt.template.today ("Yyyy-mm-dd")%>) \ n * http://blog.csdn.net/ Jennieji | licence:mit\n */\n '        },//        source file path        src: [          ' Js/app/**/*.js '        ],        //target file generated after running the task        dest: ' JS /app.debug.js '}}    );

The above is a configuration instance of "Grunt-contrib-concat".

"Concat" Specifies the plug-in for this set of configurations. "Dev" is a subtask I've customized and I've named it "Dev". A plug-in can have multiple sets of configurations to cope with different requirements, meaning that under "concat" can contain any number of customized subtasks, each of which can have different configurations.

Here I set the "banner" parameter, this parameter 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 final target file header.

In this "banner", I added a file comment for the resulting app.debug.js. 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. Following the example from the previous Package.json, this code will be replaced with "My-project-name" when writing to the file.
In fact, from here can be seen 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 method that allows you to run the time of the task and specify the resulting format.

When I run this concat task, my app.debug.js's head will have the following comment:

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

On the way to the file path, you can use some matching symbols. If I use an asterisk "*.js" for any name of the JS file, two asterisks "* *" means the current directory or sub-directory. So the JS files under the "js/app/" directory and all of its subdirectories will be merged into the App.debug.js file.

After the configuration, also remember to load plug-ins and register your task, otherwise it will error!

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

Register a task, then use the Grunt.registertask method. The first parameter is the name of the registered task queue, and the write as "default" becomes the default task queue for this gruntfile. The second parameter is an array of task names to be executed by this task queue, where the task name is used in the Initconfig configuration with the name "Concat". Modify the code as follows:

Load the plugin to be used Grunt.loadnpmtasks (' grunt-contrib-concat ');//Register Task Grunt.registertask (' Default ', [' concat ']);

If you write this, you can perform a JS merge once you have configured the command line by typing the following command directly:

Grunt

If you change "default" 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. I also used the merged files generated by Concat to do the compression directly. The complete gruntfile.js is as follows:

Module.exports = function (grunt) {Grunt.initconfig ({Pkg:grunt.file.readJSON (' Package.json '), concat: {dev: {  Options: {banner: '/*!\n * <%= pkg.name%>-JS for debug\n * @licence <%= pkg.name%>-v<%= Pkg.version%> (<%= grunt.template.today ("Yyyy-mm-dd")%>) \ n * http://blog.csdn.net/jennieji |    licence:mit\n */\n '}, src: [' js/app/**/*.js '], dest: ' Js/app.debug.js '} }, Uglify: {prod:{options: {banner: '/*!\n * <%= pkg.name%>-Compressed js\n * @licence <% = Pkg.name%>-v<%= pkg.version%> (<%= grunt.template.today ("Yyyy-mm-dd")%>) \ n * http://blog.csdn.net/j Ennieji | licence:mit\n */\n '}, files: {' js/app.min.js ': [' <%= concat.dev.dest%> ']}}}}); Grunt.loadnpmtasks (' Grunt-contrib-concat '); Grunt.loadnpmtasks (' grunt-contrib-uglify '); Grunt.registerTask (' Default ', [' concat ', ' uglify ']);

At last

This should be the most basic usage, I see Bootstrap and angular configuration files are super complex.

If you do not want to change the code every time to run grunt on the command line, it is recommended to use the watch plugin, it will automatically detect the file changes, and then run the corresponding task.

In addition, less is compiled into CSS with "grunt-contrib-less".

Sass compiled for the CSS has "grunt-contrib-compass" more useful, because you can refer to the mixin in Compass-style.

and "Grunt-conritb-requirejs" to the JS file written with Requirejs to do compression.

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.