"Grunt first bomb" 30 minutes learn to use Grunt to package front-end code

Source: Internet
Author: User

Preface

With the current front-end JS surge in the situation, a project down dozens of JS files lightly loose
For a more complex single-page application, the document hundred is simply a commonplace, then this time our JS file should be how to deal with it?
In addition, for the CSS file, how to deal with it??
These are the problems we are going to encounter in our actual work, such as we are now using zepto, backbone, underscore
How we're going to synthesize them into a libs file is a headache.

But the advent of grunt has made these things elegant!
Simple one button, packaging end, not impossible!

Grunt

is a set of front-end automation tools, a Nodejs-based command-line tool, typically used to:
① Compressed Files
② Merging files
③ Simple Grammar Check

For other uses, I'm not sure yet, here's a brief introduction to the compressed, merged files of the grunt

Beginner, wrong, please forgive me.

Preparation Phase 1, NODEJS environment

Because Grunt is based on Nodejs, so first you need to install NODEJS environment, this piece we don't care
Http://www.cnblogs.com/yexiaochai/p/3527418.html

2, Installation Grunt

With the NODEJS environment, we can start grunt because we may run the packager in any directory, so we need to install the CLI
Official recommendation in the Global Installation CLI (Grunt command line interface)

NPM install-g GRUNT-CLI

This command will insert the grunt command into the system path so that it can be run in any directory because

Each time grunt is run, it uses the require of node to find out if the grunt is installed locally and loads the local grunt library if the CLI is found
Then apply the Gruntfile configuration in our project and perform the task
PS: This paragraph first do not tube, installed down look down

Example Learning: Packaging Zepto

Some things say more are tears, directly on the first instance, the case after the end of the other
First create a new project on the D drive (the folder is good)
Add two new files inside (don't ask why, get in first)

①package.json
{  "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-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 "  }}
②gruntfile.js

We need to perform NPM install in the grunt directory to download the relevant files:

$ cd d:$ CD Grunt

And then we'll have a little more stuff in our catalogue:

A lot of things, do not do what the steward, we will use, this time in the directory to create a new SRC folder, and engage a zepto in

Then add the following code in the Gruntfile (forget it, add it again)

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 the plugin  grunt.loadnpmtasks (' grunt-contrib-uglify ') that provides the "uglify" task;  Default task  grunt.registertask (' Default ', [' uglify ']);}

Then after you run the grunt command

Grunt

Well, more than one file, and is compressed, not bad!!! End of the first step

Know Gruntdile and Package.json

No accident, each gurnt will need these two files, and it is likely that only two files (complex situation is different)

Package.json

This file is used to store the dependencies of the NPM module (for example, if our package is dependent on the Requirejs plugin, it needs to be configured here)
Then, we will configure some different information in it, such as the file above us, which will be put in the package
For the flexible configuration of the package, we will refer to the following

Gruntfile

This document is particularly critical, and he usually does two things:
① Reading Package Information
② plugin loading, registering tasks, running tasks (Grunt external interface all written in this area)

Gruntfile generally consists of four parts
① wrapper function
There's nothing in this wrapper, it means that all our code has to be put into this function.

Module.exports = function (grunt) {//Your code}

This does not need to know why, directly put the code can

② Project/Task configuration
The first thing we used in Gruntfile was the Initconfig method. Configure Dependency Information

Pkg:grunt.file.readJSON (' Package.json ')

The Grunt.file.readJSON here will read our configuration file and convert it to a JSON object.

Then we can use the pkg in the back place. XXX Way to access the data in it
It is important to note that the underscore template engine is used here, so you can write a lot of things here.

Uglify is a plugin that we configured in the package dependencies, and this time we configured a task for the system
Uglify (compressed), he would do these things:

① found in src zepto for compression (specific name found in the package)
② found the Dest directory, did not create a new, and then put the compressed files into
③ add a few descriptive languages on top

This task configuration is actually a method interface call, according to the specification to be good, temporarily ignore, insider later
This only defines the relevant parameters, but does not load the actual function, so there is a sentence immediately after:

Grunt.loadnpmtasks (' grunt-contrib-uglify ');

For loading related plugins

Finally register a custom task (which is also the default task), so our command line below is equivalent:

Grunt = = Grunt Uglify

At this point, we simply parse the entire operation of the grunt, the following example of merging files

Merging files

The merge file relies on the Grunt-contrib-concat plugin, so our package dependencies add a new

"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"},

And then write the code like this.

Module.exports = function (grunt) {  //project configuration  grunt.initconfig ({    Pkg:grunt.file.readJSON (' Package.json '),    concat: {      options: {        separator: '; '      },      dist: {        src: [' src/zepto.js ', ' src/underscore.js ', ' Src/backbone.js '],        dest: ' Dest/libs.js '}}  );  Grunt.loadnpmtasks (' Grunt-contrib-concat ');  Default task  grunt.registertask (' Default ', [' concat ']);}

After the operation, the magical scene took place:

Three files are compressed into one, but there is no compression, so we add one more step here, compress and then merge

Module.exports = function (grunt) {  //project configuration  grunt.initconfig ({    Pkg:grunt.file.readJSON (' Package.json '),    concat: {      options: {        separator: '; '      },      dist: {        src: [' src/zepto.js ', ' src/underscore.js ', ' Src/backbone.js '],        dest: ' Dest/libs.js '      }    ,    uglify: {      build: {        src: ' dest/libs.js ',        dest: ' Dest/libs.min.js '}}  );  Grunt.loadnpmtasks (' grunt-contrib-uglify ');  Grunt.loadnpmtasks (' Grunt-contrib-concat ');  Default task  grunt.registertask (' Default ', [' concat ', ' uglify ']);

What I do here is to merge and form a libs and then compress the Libs into libs.min.js

So here we go in a different way, to compress and merge, in fact Unglify has done these things.

Module.exports = function (grunt) {  //project configuration  grunt.initconfig ({    Pkg:grunt.file.readJSON (' Package.json '),    uglify: {"      my_target": {"        files": {          ' dest/libs.min.js ': [' src/zepto.js ', ' src/underscore.js ', ' src/ Backbone.js ']}}}  );  Grunt.loadnpmtasks (' grunt-contrib-uglify ');  Default task  grunt.registertask (' Default ', [' uglify ']);}

So, we're not going to focus on concat for the moment.

Finally, today's time is not early, we finally study the grunt cooperate with require so then end today's study bar

Merging Requirejs-managed files

With the basis of the previous, we come to do a usually very headache, is to require management of all JS files to compressed merged into a file
First we set up a simple program that uses zepto, backbone, underscore (in fact, what I didn't use)

Add code in Main.js:

Require.config ({baseUrl: ', shim: {  $: {      exports: ' Zepto '  },  _: {   exports: ' _ '  },  B: {   Deps: [    ' _ ',    ' $ '     ],   exports: ' Backbone '  }, paths: {  ' $ ': ' Src/zepto ',  ' _ ': ' src/ Underscore ',  ' B ': ' Src/backbone '}}); Requirejs ([' B '], function (B) {});

In this case, the operation will automatically load several files, we now want to merge it into a libs.js how to do it???

We use custom task methods here, because we don't seem to introduce him.

Need plug-ins to use REQUIREJS related

Grunt.loadnpmtasks (' Grunt-contrib-requirejs ');

Since we may be in a situation where the configuration file exists for each project file, we will requirejs the relevant configuration into Gruntcfg.json

So our Package.json has no practical significance:

{  "name": "Demo",  "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 "}  }

The Require related grunt configuration file we set here is as follows (Gruntcfg.json):

{"Requirejs": {"main": {"    Options": {"BASEURL": ""        ,        "paths": {          "$": "Src/zepto",          "_": "Src/underscore",          "B": "Src/backbone",          "Test": "Src/test"        },        "web": {          "include ": [            " $ ",            " _ ",            " B ",            " Test "          ],          " Out ":" Dest/libs.js "  }}}}

Here we have to pack these files into Dest's libs.js file, this file is done, and the final core code is as follows:

Module.exports = function (grunt) {  grunt.loadnpmtasks (' Grunt-contrib-requirejs ');  In order to introduce a custom task engage a This  grunt.registertask (' Build ', ' Require demo ', function () {    //Task List    var tasks = [' Requirejs '];    source file    var srcdir = ' src ';    Target file    var destDir = ' dest ';    Set    the parameter grunt.config.set (' config ', {      srcdir:srcdir,      destdir:destdir    });    Set Requirejs information    var taskcfg = Grunt.file.readJSON (' Gruntcfg.json ');    var options = taskCfg.requirejs.main.options,        platformcfg = Options.web,        includes = Platformcfg.include,        paths = options.paths;    var pos =-1;    var requiretask = Taskcfg.requirejs;    Options.path = paths;    Options.out = platformcfg.out;    Options.include = includes;    Run Task    grunt.task.run (tasks);    Grunt.config.set ("Requirejs", Requiretask);  });

It's finished running. Good: Grunt Build

Grunt Build

"Grunt first bomb" 30 minutes learn to use Grunt to package front-end code

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.