Grunt Getting Started Tutorial (Automatic Task Manager) _javascript Tips

Source: Internet
Author: User
Tags documentation lowercase script tag tag name install node

During the development of JavaScript, you often encounter repetitive tasks such as merging files, compressing code, checking syntax errors, converting SASS code into CSS code, and so on. Usually, we need to use different tools to accomplish different tasks, both repetitive labor and time-consuming. Grunt is a tool invented to solve this problem and can help us automate the management and operation of various tasks.

Simply put, grunt is an automated task manager that runs a series of tasks automatically in a predetermined order. This simplifies the workflow and reduces the burden of repetitive work.



# # Installation


Grunt is based on Node.js, install node.js before installing, and then run the following command.


sudo npm install grunt-cli-g


GRUNT-CLI indicates that the grunt command line interface is installed, and parameter G represents a global installation.

Grunt uses the module structure to install the appropriate modules as needed, in addition to the command line interface. These modules should be installed locally because different projects may require different versions of the same module.

First, in the project's root directory, create a text file Package.json that specifies the modules required for the current project. Here's an example.


{"Name": "My-project-name", "Version": "0.1.0", "Author": "Your name", "Devdependencies": {"grunt": "0.x.x", "Grunt-cont Rib-jshint ":" "," Grunt-contrib-concat ":" ~0.1.1 "," grunt-contrib-uglify ":" ~0.1.0 "," Grunt-contrib-watch ":" ~ 0.1.4 "}}


In this Package.json file, in addition to the name and version of the project, the Devdependencies attribute is also specified in the Grunt model of the project dependency Block and Version: Grunt Core module for the latest 0.x.x version, Jshint plug-ins for the latest version, Concat Plug-ins are not less than 0.1.1 version, uglify plug-ins no less than 0.1.0 version, watch plug-ins not less than 0.1.4 version.

The following commands are then run under the root directory of the project, and the Plug-ins are automatically installed in the Node_modules subdirectory.


NPM Install


The above method is aimed at the existing package.json situation. If you want to automatically generate the Package.json file, you can use the NPM init command to answer the name and version of the desired module by following the on-screen prompts.


NPM Init


If the existing Package.json file does not include the grunt module, you can install the Grunt module directly, add the-save-dev parameters, the module will automatically be added to the Package.json file.


NPM Install <module>-save-dev


For example, the following NPM command needs to be run for the module specified in the Package.json file above.


NPM Install grunt-save-dev npm install grunt-contrib-jshint-save-dev npm install Grunt-contrib-concat-save-dev NPM Inst All Grunt-contrib-uglify-save-dev npm Install Grunt-contrib-watch-save-dev




# # command Script file Gruntfile.js


After the module is installed, the next step is to create a new script file gruntfile.js under the root directory of the project. It is a grunt configuration file, just as Package.json is the configuration file for NPM. Gruntfile.js is the General node.js module.


/}, Concat: {//},uglify: {//}, Watch: {//}}); Load module file from Node_modules directory grunt.loadnpmtasks (' Grunt-contrib-jshint '); Grunt.loadnpmtasks (' Grunt-contrib-concat '); Grunt.loadnpmtasks (' grunt-contrib-uglify '); Grunt.loadnpmtasks (' Grunt-contrib-watch '); Each line Registertask defines a task Grunt.registertask (' Default ', [' jshint ', ' concat ', ' uglify ']); Grunt.registertask (' Check ', [' jshint ']); };


The above code uses three methods of grunt code: grunt.initconfig: Defines the parameters of 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: Define specific tasks. The first parameter is the task name, and the second parameter is an array that represents the module that the task needs to be used sequentially. The default task name indicates that if the grunt command is entered directly, followed by no arguments, the module being invoked (the example is Jshint,concat and uglify), and the check task for this example indicates that the code is syntactically checked using the Jshint plug-in.
The code above is loaded with four modules: jshint (check syntax errors), concat (merged files), Uglify (compressed code), and watch (Automatic execution). Next, there are two ways to use it.

(1) The command line executes a module, such as


Grunt Jshint


The code above indicates that the Jshint module is running.

(2) The command line performs a task. Like what


Grunt Check


The code above indicates that the check task is run. If the operation succeeds, it will show "done, without errors."

If you do not give a task name, just type grunt, which means that you are performing the default defaults task.



# # Gruntfile.js instance: Grunt-contrib-cssmin module


The following is a cssmin module that demonstrates how to write a gruntfile.js file. The function of the Cssmin module is to minimize the CSS file.

First, install the module in the root directory of the project.


NPM Install Grunt-contrib-cssmin-save-dev


Then, create a new file gruntfile.js.


Module.exports = function (grunt) {grunt.initconfig {cssmin: {minify: {expand:true, CWD: ' css/', src: ['. css ', '!< /c2>.min.css '], dest: ' css/', ext: '. Min.css '}, combine: {files: {' css/out.min.css ': [' css/part1.min.css ', ' css/part2.m In.css ']}}}); Grunt.loadnpmtasks (' grunt-contrib-cssmin '); Grunt.registertask (' Default ', [' cssmin:minify ', ' cssmin:combine ']); };


The following is a detailed explanation of the three methods in the above code.

(1) grunt.initconfig

The Grunt.initconfig method is used for module configuration, which accepts an object as an argument. The members of this object correspond to module one by one of the same name used. Because we are configuring the Cssmin module, there is a Cssmin member (attribute) inside.

The Cssmin (property) points to an object that contains more than one member. In addition to some system-set members (such as options), other custom members are called targets. A module can have multiple targets (target), in which the Cssmin module has two goals, one is "minify" for compressing the CSS file, and the other is "combine", which is used to merge multiple CSS files into one file.

Specific settings for each goal need to refer to the template's documentation. In terms of cssmin, the parameters of the minify target are as follows:

Expand: If set to true, it represents the placeholder for the file name below (that is,) is extended to a specific file name.
CWD: The directory where the file (input) is to be processed. src: Represents the file that needs to be processed. If you take an array, each item in the array is a filename, and you can use wildcards.
dest: Represents the processed file name or directory. ext: Represents the file suffix name after processing.
In addition to the above parameters, there are also some parameters are grunt all modules generic.

filter: A function that returns a Boolean value that is used to filter the file name. Only files that return a value of true will be processed by grunt. Dot: whether to match a system file that starts with a point number (.).
makebase: If set to true, only the last part of the file path is matched. For example, A?b can match/XYZ/123/ACB and not match/xyz/acb/123.
For wildcard characters, the meaning is as follows:
: Matches any number of characters, excluding/. ?: Matches a single character, excluding/.
* *: Matches any number of characters, including/. {}: A comma-delimited list is allowed, representing an "or" (or) relationship.
!: Used at the beginning of the pattern, indicating that only mismatches are returned.
For example, foo/
. JS matches the filename under the Foo directory with the. js End file, foo//. JS matches the file name at the end of. js for the Foo directory and all its subdirectories. CSS represents a file that matches all suffix names that are not ". css".

More examples of using wildcard characters to set SRC properties:
(2) Grunt.loadnpmtasks

The Grunt.loadnpmtasks method loads the module file.
(3) Grunt.registertask

The Grunt.registertask method defines how to invoke a specific task. The "Default" task indicates that if you do not supply a parameter and enter the grunt command directly, run "cssmin:minify" and then Run "Cssmin:combine", which is the first to compress and then merge. If you are only performing compression, or if you are only performing a merge, you will need to indicate "module name: Target Name" after the grunt command.
Grunt-contrib-clean: Deletes the file.
*
Grunt-contrib-compass: Compile Sass files using Compass.
*
Grunt-contrib-concat: Merging files.
*
Grunt-contrib-copy: Copies the file.
*
Grunt-contrib-cssmin: Compress and merge CSS files.
*
Grunt-contrib-imagemin: Image compression module.
*
Grunt-contrib-jshint: Check the JavaScript syntax.
*
Grunt-contrib-uglify: Compress and merge JavaScript files.
*
Grunt-contrib-watch: Monitor file changes and make corresponding actions.
The prefix of the module, if it is grunt-contrib, means that the module is maintained by the Grunt development team, and if the prefix is grunt (such as Grunt-pakmanager), it is maintained by a third-party developer.

Select a few modules below to see how their configuration parameters are written, that is, how to configure each module in the Grunt.initconfig method.

### Grunt-contrib-jshint

Jshint is used to check for grammatical errors, such as whether the semicolon is used correctly, has not forgotten to write parentheses, and so on. Its configuration code in the Grunt.initconfig method is as follows.
/. js ']},

The code above specifies the Jshint check item, EQEQEQ represents the substitution of the equality operator with the strict equality operator, and trailing indicates that there must be no extra space at the end of the line. Then, specify the Files property, which indicates that the check target is the Gruntfile.js file, and the JavaScript file below all subdirectories of the Lib directory.

### Grunt-contrib-concat

Concat is used to merge similar files, not only to merge JavaScript files, but also to merge CSS files.
. js ', dest: ' js/'}},

The options attribute in the above code specifies the file header for the compressed file, as well as the Sourcemap setting; the target target specifies the input and output files.

### grunt-contrib-copy

The copy module is used to copy files and directories.


Copy: {main: {src: ' src/', dest: ' dest/',},},


The code above will have the SRC subdirectory (containing only the first layer of files and subdirectories below it) and copied under the Dest subdirectory (that is, the DEST/SRC directory). If you want more accurate control over copy behavior, such as copying only files, not copying directories, and not keeping the directory structure, you can write the following:


Copy: {main: {expand:true, CWD: ' src/', src: ' * ', dest: ' dest/', flatten:true, filter: ' Isfile ',},},

Grunt-contrib-watch

The Watch module is used to run in the background, listen for the specified event, and then run the specified task automatically.


Watch: {scripts: {files: '/*.js ', tasks: ' Jshint ', options: {Livereload:true,},}, CSS: {files: '/. Sass ', tasks: [' sass '], options: {Livereload:true,},},} ,


Set up the code above, open another process, and run grunt watch. Thereafter, any JS code changes, the file will automatically run the Jshint task after saving, any sass file changes, the file will automatically run Sass task after saving.

It should be noted that the options parameters for both of these tasks are set to Livereload, indicating that the task is automatically overloaded (reload) in the browser after it has finished running. This requires the Livereload plug-in to be installed in the browser. After installation, the default port for Livereload is localhost:35729, but you can also reset the port (localhost:1337) in livereload:1337 form.

### other Modules

Here are some other useful modules.

(1) Grunt-contrib-clean

This module is used to delete files or directories.


Clean: {build: {src: [' path/to/dir/one ', ' Path/to/dir/two ']}}


(2) grunt-autoprefixer

This module is used to add a browser prefix to the CSS statement.


Autoprefixer: {build: {expand:true, CWD: ' Builds ', src: [' **/.css '], dest: ' Build '}},


(3) Grunt-contrib-connect

This module is used to run a Web Server on this computer.


Connect: {server: {options: {port:4000, Base: ' Build ', hostname: ' }}}


The Connect module ends with the end of the grunt run and can be run before the Watch module in order to keep it running. The Connect module will run all the time because the watch module needs to be aborted manually.

(4) Grunt-htmlhint

This module is used to check HTML syntax.


Htmlhint: {build: {options: {' Tag-pair ': true, ' tagname-lowercase ': true, ' attr-lowercase ': true, ' Attr-value-double-qu OTEs ': True, ' spec-char-escape ': true, ' id-unique ': true, ' head-script-disabled ': true,}, src: [' index.html ']}}


The code above is used to check the index.html file: whether the HTML tag is paired, whether the tag name and property name are lowercase, whether the property value is included in double quotes, whether the special character is escaped, whether the HTML element's ID attribute is unique, and whether the head part does not have a script tag.

(5) Grunt-contrib-sass module

This module is used to convert SASS files to CSS files.


Sass: {build: {options: {style: ' compressed '}, files: {' build/css/master.css ': ' Assets/sass/master.scss '}}}


The above code specifies that the output file is build/css/master.css and the input file is assets/sass/master.scss.

(6) Grunt-markdown

This module is used to convert markdown documents into HTML documents.


Markdown: {All: {files: [{expand:true, src: '. MD ', dest: ' docs/html/', ext: '. html '}], options: {Template: ' Templa Tes/index.html ',}}},


The code above specifies that the file for the MD suffix name be converted to an HTML file in the docs/html/directory. The template property specifies the template to use when converting, and the template style is as follows.


<! DOCTYPE html> 


{src: ' foo/th. js '}grunt-contrib-uglify {src: ' foo/{a,b}. js '} {src: [' foo/a. js ', ' foo/b. js ']}


As for the combine target, there is only one files parameter, which indicates that the output file is a out.min.css under the CSS subdirectory, and the input file is the PART1.MIN.CSS and part2.min.css under the CSS subdirectory.

The files parameter can be in the form of an object or an array.


Files: {' dest/b.js ': [' src/bb.js ', ' src/bbb.js '], ' dest/b1.js ': [' src/bb1.js ', ' src/bbb1.js '],},//or files: [{src: [] Src/aa.js ', ' src/aaa.js '], dest: ' Dest/a.js '}, {src: [' src/aa1.js ', ' src/aaa1.js '], dest: ' Dest/a1.js '},],


If the minify target and the combine target have overlapping portions of the property settings, you can define a separate options property that is parallel to minify and combine.


 Grunt.initconfig ({cssmin: {options: {//}, Minify: {//}, combine: {//}}});


Grunt # By default, first compress merge grunt Cssmin:minify # only compress not merge grunt Css:combine # only merge uncompressed


If you do not specify a target, only the module indicates that all targets are run in turn.


Grunt Cssmin




# # Common Module setup


Grunt has more than 2000 modules and is growing rapidly. Here are some common modules (sorted alphabetically).

*


Jshint: {options: {eqeqeq:true, trailing:true}, files: [' gruntfile.js ', ' lib/
# # Reference Link

  • Frederic Hemberger, A build tool for front-end projects
  • Mária Jurčovičová, building a JavaScript Library with Grunt.js
  • Ben briggs,speed up Your Web Development Workflow with Grunt
  • Optimizing Images with Grunt
  • Swapnil Mishra, simplifying chores with grunt
  • AJ Oneal, moving to Gruntjs
  • Grunt documentation, Configuring tasks
  • Landon Schropp, writing a Awesome build Script with Grunt
  • Mike Cunsolo, get up and Running with grunt
  • Matt Bailey, A beginner ' s Guide to-Using grunt with Magento
    Turn from: http://javascript.ruanyifeng.com/tool/grunt.html

Also recommended: http://www.w3cplus.com/tools/writing-awesome-build-script-grunt.html


Concat: {js: {src: [' lib/module1.js ', ' lib/module2.js ', ' lib/plugin.js '], dest: ' Dist/script.js '} CSS: {src: [' style/n Ormalize.css ', ' style/base.css ', ' style/theme.css '], dest: ' Dist/screen.css '},


JS Target is used to merge JavaScript files, CSS target language merged CSS file. The SRC attribute of both specifies the file (input) that needs to be merged, and the Dest property specifies the target file (output) to be exported.

### grunt-contrib-uglify

The Uglify module is used to compress code and reduce file size.


Uglify: {options: {banner:bannercontent, Sourcemaproot: '. /', Sourcemap: ' distrib/' +name+ '. Min.js.map ', sourcemapurl:name+ '. Min.js.map '}, Target: {expand:true, CWD: ' Js/origin ', src: '

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.