Front End automation Tools--Introduction to grunt use

Source: Internet
Author: User

Grunt is what, Grunt is a thing.

Grunt as a front-end building tool, there are resource compression, code checking, file merging and other functions.

Here's a quick overview of the use of grunt.

First, the Environment configuration

Grunt is based on Nodejs, so need a nodejs environment, not understand can come here to see

or under Windows,

First make sure the Grunt command is available, so use NPM to install the corresponding CLI

NPM install-g GRUNT-CLI

Installation complete You can enter "grunt" on the command line to test whether the installation was successful

After successful installation

Ii. Description of Usage

Grunt requires a Package.json file description, and many operations are accessed directly from this JSON file.

Need Gruntfile.js file, this is a portal file, Grunt will start here and implement your intentions.

So, first create a new project Catalog grunt, and then create these two files inside.

Package.json requires a strict JSON format, which can be written to several key-value such as:

{  "name": "Grunt_test",  "version": "1.0.0"}

Gruntfile.js can be initialized into this form:

function (Grunt) {     grunt.initconfig ({         Pkg:grunt.file.readJSON (' Package.json ')            });     // grunt.registertask (' Default ', []);};

At this point we command line into the project directory, NPM installed grunt support, the following parameter--dev-save means to add this grunt support to the dependency

What do you mean by adding to the dependency? After the installation, see Package.json inside, is not more this thing ~

{  "name": "Grunt_test",  "version": "1.0.0",  "Devdependencies": {     "Grunt": "^0.4.5"  }}

Good at this time, we use the grunt command to execute, and sure enough, there is no default this goods, see it is need this goods, then put the top of that note out, and then try

In fact, so far has been the most basic process.

Third, the use of plug-ins

The usual method is to use the provided plug-in, further processing

1) such as code compression:

HTML compression: Htmlmin

CSS compression: cssmin

JS Compression: Uglify

The official provides ample introduction, of course, the first contact, it is easy to be confused by a variety of miscellaneous configuration items.

Now that you want to compress the code, create a new Test.js file in the./static/script/directory and write a few sentences.

function Firstlettertoup (str) {     return String (str). replace (' ^\s*|\s*$ ')                . Replace (/\b\w +\b/g,function(word) {                     = word.tolowercase ();                     return word[0].touppercase () + word.substring (1);                }); var s = Firstlettertoup ('  aBCDE Bda erew '); Console.log (s);

JS code compression requires a very common plug-in grunt-contrib-uglify, the same first NPM installation support

You can see that the Package.json has also updated

{  "name": "Grunt_test",  "version": "1.0.0",  "Devdependencies": {     "Grunt": "^0.4.5",    "grunt-contrib-uglify": "^0.9.1"  }}

A similar approach to HTML installation grunt-contrib-htmlmin, CSS installation grunt-contrib-cssmin

After the installation is complete, the next step is to update the configuration item to Gruntfile.js

Grunt.initconfig: Defines parameters for various modules, each of which corresponds to a module of the same name.
Grunt.loadnpmtasks: Loads the modules required to complete the task.
Grunt.registertask: Defines a specific task. The first parameter is the task name, and the second argument is an array that represents the module that the task needs to use in sequence.

Each setting item has the general usage, the special need to go to the official website to view the explanation, for example

    • Expand: If set to True, the placeholder (that is, *) of the following file name is extended to a specific file name.
    • CWD: The directory where the file (input) needs to be processed.
    • src: Represents a file that needs to be processed. If an array is used, each item of the array is a file name, and wildcard characters can be used.
    • dest: Indicates the file name or directory in which it was processed.
    • ext: Indicates the file suffix name after processing.

Current Gruntfile.js configuration:

Module.exports =function(Grunt) {grunt.initconfig ({//get to Package.json itemsPkg:grunt.file.readJSON (' Package.json '),        //JS Compressionuglify: {//Use the options for this reputationoptions: {//true to allow header information to be addedStripbanners:true,                //Add a JS file name and time comment to the headerBanner: '/*! <%=pkg.name%>-<%=pkg.version%>.js <%=grunt.template.today ("Yyyy-mm-dd")%> */\n '            },            //files name arbitrary, such as the bottom of the build key is src-dest to indicate goodfiles: {src:'./static/script/test.js ', dest:' Build/static/script/<%=pkg.name%>-<%=pkg.version%>.min.js '            }        },        //CSS Compressioncssmin: {options:{report:' Gzip '}, Build: {expand:true, CWD:'./static/style ', src: [' Test.css '], dest:'./build/static/style '            }        },        //HTML Compressionhtmlmin: {options: {removecomments :true, Removecommentsfromcdata:true, Collapsewhitespace:true, Collapsebooleanattributes:true, Removeattributequotes:true, Removeredundantattributes:true, Useshortdoctype:true, Removeemptyattributes:true, Removeoptionaltags:true}, build:{expand:true, CWD:‘./‘, src: [' *.html '], dest:‘./‘            }        }    }); Grunt.loadnpmtasks (' Grunt-contrib-uglify '); Grunt.loadnpmtasks (' Grunt-contrib-cssmin '); Grunt.loadnpmtasks (' Grunt-contrib-htmlmin '); Grunt.registertask (' Default ',[        ' Uglify ',        ' Cssmin ',        ' Htmlmin '        ]);};

command line execution See effect

Of course, there are pictures of the compression imagemin can also go to try

2) Jshint Code check

JS code Check can use the Jshint plugin

In the same vein, install Grunt-contrib-jshint first.

Check the rules see DOCS

Such as

Curly: curly braces Wrap

Eqeqeq: For simple types, use = = = and!== instead of = = and! =

Newcap: For first-letter uppercase functions (declared classes), force the use of the new

noarg: Disabling Arguments.caller and Arguments.callee

Sub: Use AAA.BBB instead of aaa[' BBB ' for properties

undef: Find all undefined variables

boss: Look for code similar to if (a = 0)

node: Specifies that the runtime environment is node. js

To configure the related items in Gruntfile.js:

Module.exports =function(Grunt) {grunt.initconfig ({//get to Package.json itemsPkg:grunt.file.readJSON (' Package.json '),        //JS Compression        //... Omitted}, Jshint: {options: {curly :true, Eqeqeq:true, Newcap:true, Noarg:true, Sub:true, undef:true, Boss:true, node:true, Globals: {exports:true, JQuery:true}}, files:['./static/script/test.js ']        }    }); Grunt.loadnpmtasks (' Grunt-contrib-uglify '); Grunt.loadnpmtasks (' Grunt-contrib-cssmin '); Grunt.loadnpmtasks (' Grunt-contrib-htmlmin '); Grunt.loadnpmtasks (' Grunt-contrib-jshint '); Grunt.registertask (' Default ',[        ' Jshint ',        ' Uglify ',        ' Cssmin ',        ' Htmlmin '        ]);}; 

Modify, and then execute grunt, you can see the error message, and grunt no longer continue to execute

Similarly, csslint can also be used as a CSS grammar check, you can try

3) using the Grunt-contrib-watch plugin

Watch usage automatically listens for changes and grunt automatically builds

Similarly, add a watch configuration item in config

Files represents the file to listen on, which can be a single value or an array, and tasks indicate what to do when listening for changes

Watch: {             build: {                 files: ['./static/style/*.css '],                tasks: [' Cssmin '],                options:{                     false                }            }        }

4) using the Grunt-contrib-sass plugin

This plugin can automatically compile sass into a CSS file, and then use it with other plugins. Beautiful ~

After you have installed support dependencies, add the following in the config configuration:

sass:{             dist:{                 options:{                     // Do you remember this? This is the style in the four style of sass compile time                    : ' Expanded '                }                ,                     files:{'./static/style/test.css ': '. Static/style/test.scss '}}        }

In files, it is defined as a form of dest:src.

With Watch's assist, after executing the command, each change of the Scss file can automatically build a new CSS

5) concat Plugin file merge

It can be implemented in a way similar to this

grunt.initconfig ({  concat: {    options: {      '; ') ,    },    dist: {      src: [' src/intro.js ', ' src/project.js ', ' src/outro.js '],      ' dist/ Built.js ',    },  },});

Of course, there are many plugins that are often used, such as clean copy and so on. These can be found in the grunt plug-in center, with the contrib word of the expression is officially provided.

Plug-in specific usage, a variety of, or from the corresponding site, read a good read

In fact grunt this build tool is very simple to use, mainly is the configuration + a lot of configuration. The initial may be a headache for each configuration item, but often practice, will eventually clear the chest.

Front End automation Tools--Introduction to grunt use

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.