Grunt is an automatic task runner that automatically runs a series of tasks in a preset order. This can simplify the workflow and reduce the burden of repetitive work. During Javascript development, repetitive tasks are often encountered, for example, merging files, compressing code, checking syntax errors, and converting Sass code into CSS code. Generally, we need to use different tools to complete different tasks, which are repetitive and time-consuming. Grunt is a tool invented to solve this problem. It can help us automatically manage and run various tasks.
In short, Grunt is an automatic task runner that automatically runs a series of tasks in a preset order. This simplifies the workflow and reduces the burden of repetitive work.
# Installation
Grunt is based on Node. js. Before installation, you must first install Node. js and then run the following command.
sudo npm install grunt-cli -g
Grunt-cli indicates that grunt's command line interface is installed, and parameter g indicates global installation.
Grunt uses the module structure. In addition to the command line interface, it also installs the corresponding modules as needed. These modules should be locally installed, because different projects may require different versions of the same module.
First, create a text file package. json under the root directory of the project to specify the modules required by the current project. The following is an example.
{ “name”: “my-project-name”, “version”: “0.1.0”, “author”: “Your Name”, “devDependencies”: { “grunt”: “0.x.x”, “grunt-contrib-jshint”: ““, “grunt-contrib-concat”: “~0.1.1”, “grunt-contrib-uglify”: “~0.1.0”, “grunt-contrib-watch”: “~0.1.4” } }
The package above. in the json file, in addition to specifying the project name and version, the grunt module and version of the project dependency are also specified in the devDependencies attribute: The grunt core module is the latest 0. x. version x, jshint plug-in is the latest version, concat plug-in version 0.1.1, uglify plug-in version 0.1.0, watch plug-in version 0.1.4.
Then, run the following commands in the root directory of the project. These plug-ins will be automatically installed in the node_modules subdirectory.
npm install
The above method is applicable to the existing package. json. 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 required module as prompted on the screen.
npm init
If the existing package. json file does not include the Grunt module, you can add the-save-dev parameter when installing the Grunt module directly. This module will be automatically added to the package. json file.
npm install
—save-dev
For example, you need to run the following npm command to correspond to 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 install grunt-contrib-uglify —save-dev npm install grunt-contrib-watch —save-dev
# Command Script File Gruntfile. js
After the module is installed, create the script file Gruntfile. js in the root directory of the project. It is the grunt configuration file, just like package. json is the npm configuration file. Gruntfile. js is the general method of writing Node. js modules.
Module. exports = function (grunt) {// configure Grunt. initConfig ({jshint: {/jshint) parameters for various grunt modules/}, Concat :{/Concat Parameters/}, Uglify :{/Uglify Parameters/}, Watch :{/Watch Parameters//}); // Load the module File grunt from the node_modules directory. loadNpmTasks ('grunt-contrib-jshint'); grunt. loadNpmTasks ('grunt-contrib-concat'); grunt. loadNpmTasks ('grunt-contrib-uglify '); grunt. loadNpmTasks ('grunt-contrib-Watch'); // each registerTask row defines a task grunt. registerTask ('default', ['jshint', 'concat', 'uglify ']); grunt. registerTask ('check', ['jshint']);};
The above Code uses three grunt code methods:Grunt. initConfig: Defines the parameters of various modules. Each member item corresponds to a module with the same name.
Grunt. loadNpmTasks: Load the modules required to complete the task.Grunt. registerTask: Define a specific task. The first parameter is the task name, and the second parameter is an array, indicating the modules that the task needs to use in sequence. Default Task Name: If you directly enter the grunt command without any parameters, then the called module (in this example, jshint, concat, and uglify ); the check task in this example indicates that the jshint plug-in is used to check the code syntax.
The above code is loaded into four modules: jshint (check syntax errors), concat (merge files), uglify (compress code), and watch (Automatic execution ). There are two ways to use it.
(1) execute a module through command lines, such
grunt jshint
The above code indicates running the jshint module.
(2) execute a task through a command line. For example
grunt check
The above code indicates running the check task. If the operation is successful, "Done, without errors." is displayed .".
If the task name is not given and only grunt is entered, the default task is executed.
# Gruntfile. js instance: grunt-contrib-cssmin Module
The following uses the cssmin module to demonstrate how to compile the Gruntfile. js file. The cssmin module minimizes CSS files.
First, install the module in the root directory of the project.
npm install grunt-contrib-cssmin —save-dev
Then, create the Gruntfile. js file.
module.exports = function(grunt) { grunt.initConfig({ cssmin: { minify: { expand: true, cwd: ‘css/‘, src: [‘.css', ‘!.min.css'], dest: ‘css/‘, ext: ‘.min.css' }, combine: { files: { ‘css/out.min.css': [‘css/part1.min.css', ‘css/part2.min.css'] } } } }); grunt.loadNpmTasks(‘grunt-contrib-cssmin'); grunt.registerTask(‘default', [‘cssmin:minify','cssmin:combine']); };
The three methods in the above Code are explained in detail below.
(1) grunt. initConfig
The grunt. initConfig method is used for module configuration. It accepts an object as a parameter. The members of this object correspond to the modules of the same name. Because we want to configure the cssmin module, there is a cssmin member (attribute) in it ).
Cssmin (attribute) points to an object, which contains multiple members. Except for some set members (such as options), other custom members are called targets ). One module can have multiple targets. In the code above, the cssmin module has two targets, one being "minify", used to compress css files, and the other being "combine ", it is used to merge multiple css files into one file.
For specific settings of each target, see the template documentation. As far as cssmin is concerned, the specific meaning of the minify target parameter is as follows:
Expand: If it is set to true, it indicates the placeholder for the following file name (that isTo the specific file name.
Cwd: The Directory of the file (input) to be processed.Src: Indicates the file to be processed. If an array is used, each item of the array is a file name. Wildcards can be used.
Dest: Indicates the processed file name or directory.Ext: Indicates the suffix of the processed file.
In addition to the preceding parameters, some parameters are also common to all grunt modules.
Filter: A function that returns a Boolean value to filter file names. Grunt processes objects whose return value is true.Dot: Whether to match system files starting with the dot.
MakeBase: If it is set to true, only the last part of the file path is matched. For example,? B can match/xyz/123/acb, but not/xyz/acb/123.
Wildcard characters are described as follows:: Match any number of characters, excluding /.? : Match a single character, excluding /.
**: Match any number of characters, including /.{}: List separated by commas (,), indicating the "or" (or) relationship.
! : Used at the beginning of the pattern, indicating that only unmatched results are returned.
For example, foo/. Js matches the file name ending with. js under the foo directory, foo//. Js matches the file name ending with. js under the foo directory and all its subdirectories ,!. CSS matching all files with the suffix "".css.
For more examples of setting the src attribute using wildcards:
(2) grunt. loadNpmTasks
The grunt. loadNpmTasks method loads the module File.(3) grunt. registerTask
The grunt. registerTask method defines how to call a specific task. The "default" task indicates that if no parameter is provided, directly enter the grunt command, Run "cssmin: minify", and then run "cssmin: combine", that is, compress and merge. If you only perform compression or merge, you must specify "module name: Target name" behind the grunt command ".
Grunt-contrib-clean: Delete an object.
*Grunt-contrib-compass: Use compass to compile sass files.
*Grunt-contrib-concat: Merge files.
*Grunt-contrib-copy: Copy an object.
*Grunt-contrib-cssmin: Compress and merge CSS files.
*Grunt-contrib-imagemin: Image compression module.
*Grunt-contrib-jshint: Check JavaScript syntax.
*Grunt-contrib-uglify: Compress and merge JavaScript files.
*Grunt-contrib-watch: Monitors file changes and makes corresponding actions.
If the module prefix is grunt-contrib, it indicates that the module is maintained by the grunt development team. If the prefix is grunt (such as grunt-pakmanager), it indicates that it is maintained by a third-party developer.
The following describes how to configure parameters in the grunt. initConfig method.
### Grunt-contrib-jshint
Jshint is used to check syntax errors, such as whether the use of semicolons is correct or whether parentheses are left blank. The configuration code in the grunt. initConfig method is as follows.
/. Js']},
The code above first specifies the jshint check item. eqeqeq indicates that the strict equality operator should be used to replace the equality operator, and trailing indicates that no extra spaces are allowed at the end of the line. Then, specify the files attribute to check whether the target is the Gruntfile. js file and the JavaScript files under all subdirectories of the lib directory.
### Grunt-contrib-concat
Concat is used to merge similar files. It can merge not only JavaScript files, but also CSS files.
. Js', dest: 'js /'}},
The options attribute in the code above specifies the compressed file header and sourceMap settings; the 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 copies the src sub-directory (including only the first-level files and sub-directories under it) to the dest sub-directory (dest/src directory ). If you want to control the copy behavior more accurately, such as only copying files, not copying directories, and not keeping directory structures, you can write them as follows:
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 to specified events, and then automatically run the specified task.
watch: { scripts: { files: ‘/*.js', tasks: ‘jshint', options: { livereload: true, }, }, css: { files: ‘/.sass', tasks: [‘sass'], options: { livereload: true, }, }, },
Set the above Code, open another process, and run grunt watch. After that, any js Code changes will automatically run the jshint task after the file is saved. If any sass file changes, the sass task will automatically run after the file is saved.
Note that livereload is set in the options parameters of the two tasks, indicating that the task is automatically reloaded in the browser after the task is completed ). This requires installing the livereload plug-in the browser. After installation, the default port of livereload is localhost: 35729, but you can also reset the port (localhost: 1337) in the form of livereload: 1337 ).
### Other modules
The following 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 the browser prefix to CSS statements.
autoprefixer: { build: { expand: true, cwd: ‘build', src: [ ‘**/.css' ], dest: ‘build' } },
(3) grunt-contrib-connect
This module is used to run a Web Server on the local machine.
connect: { server: { options: { port: 4000, base: ‘build', hostname: ‘‘ } } }
The connect module ends with grunt. To keep it running, you can run it before the watch module. Because the watch module needs to be manually aborted, the connect module will continue to run.
(4) grunt-htmlhint
This module is used to check the HTML syntax.
htmlhint: { build: { options: { ‘tag-pair': true, ‘tagname-lowercase': true, ‘attr-lowercase': true, ‘attr-value-double-quotes': true, ‘spec-char-escape': true, ‘id-unique': true, ‘head-script-disabled': true, }, src: [‘index.html'] } }
The Refer code is used to check the index.html file: whether the HTML Tag is paired, whether the Tag Name and attribute name are in lowercase, whether the attribute value is included in double quotation marks, whether special characters are escaped, whether the id attribute of the HTML element is a unique value, and whether the head part is not marked with a script.
(5) grunt-contrib-sass Module
This module is used to convert SASS files into CSS files.
sass: { build: { options: { style: ‘compressed' }, files: { ‘build/css/master.css': ‘assets/sass/master.scss' } } }
The code above 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: ‘templates/index.html', } } },
The code above specifies to convert an md suffix file to an html file under the docs/html/directory. The template attribute specifies the template used for conversion. The template style is as follows.
Document <%=content%>
{src: ‘foo/th.js'}grunt-contrib-uglify {src: ‘foo/{a,b}.js'} {src: [‘foo/a.js', ‘foo/b.js']}
.
The format of the files parameter can be 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 attributes of the minify target and combine target overlap, you can define an options attribute parallel to minify and combine.
grunt.initConfig({ cssmin: { options: { / … / }, minify: { / … / }, combine: { / … / } } });
Grunt # by default, first compress and then merge grunt cssmin: minify # Only compress and not merge grunt css: combine # Only merge and not compress
If the target is not specified but the module is specified, all the targets are run in sequence.
grunt cssmin
# Common Module Settings
The number of grunt modules has exceeded 2000 and is still increasing rapidly. Below are some common modules (sorted by letters ).
*
jshint: { options: { eqeqeq: true, trailing: true }, files: [‘Gruntfile.js', ‘lib/
# Reference
- Frederic Hemberger, A build tool for front-end projects
- Mária Jur javasovi javasov, 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, sorting ing tasks
- Landon Schropp, Writing an Awesome Build Script with Grunt
- Mike Cunsolo, Get Up And Running With Grunt
- Matt Bailey, A Beginner's Guide to Using Grunt With Magento