Previous blogs have outlined information such as "front-end Automation builder Grunt" and "Grunt[mismatched:define". However, not in depth; The following will delve into the grunt files processing methods, configuration items, and custom plug-ins.
First, the preparatory work
A. By npm init
creating in the project root directory package.json
;
B. By npm install grunt --save-dev
installing grunt dependencies;
C. Create a folder manually under the project root directoryGruntfile.js
The Gruntfile consists of the following components:
① "wrapper" function
② Project and Task configuration
③ loading grunt plugins and tasks
④ Custom Tasks
1. Wrapper function
Each gruntfile file follows the same format, and all the code must be wrapped in the following function:
function(grunt){ // grunt相关其他信息};
2. Project and Task configuration
The task configuration for grunt is specified in the method in Gruntfile grunt.initConfig
.
grunt.initConfig({ copy: {}});
3. Loading Grunt plugins and tasks
As long as the package.json
file is listed as a dependency (dependent) package, and npm install
after installation, it can be used as a simple command in gruntfile :
// 加载能够提供"copy"任务的插件。grunt.loadNpmTasks(‘grunt-contrib-copy‘);
All plugins can be loaded at once with "Load-grunt-tasks", without the need to introduce them.
require(‘load-grunt-tasks‘)(grunt);
4. Customizing tasks
(1) Custom tasks
grunt.registerTask(taskName[description, ]taskList)grunt.registerMultiTask(taskName[description, ]taskFunction)
Example:
grunt.registerTask(‘cunstom-copy‘, [‘copy:js‘]);grunt.registerMultiTask(‘default‘, [‘clean‘‘copy‘]);
Note : But its custom name ("Cunstom-copy") cannot be the "atomic" task name above, otherwise it will cause a dead loop! Cause "Maximum call stack size exceeded" issue!
(2) Basic tasks
Executes the specified task function and passes any arguments that use a colon split as arguments to the function.
grunt.registerTask(taskName[description, ]taskFunction)
Example :
grunt.registerTask(‘foo‘‘A sample task that logs stuff.‘function(arg1, arg2) { "," + arg2); // 内部通过run执行其他任务 grunt.task.run(‘bar‘‘baz‘);});
Ii.. Configuration Tasks
grunt.initConfig
METHOD specifies a task configuration, primarily a property named with the task name, or any other data that can be included. In the grunt.initConfig({})
properties that are not for any task, grunt will be stored as constants for subsequent <%= %>
reference.
Module.exports = function(grunt){ varConfig = {app:' app ',//source file directoryDest' dest ' //destination file directory}; Grunt.initconfig ({config:config, Pkg:grunt.file.readJSON (' Package.json '), copy: {js: {expand:true, CWD:' <%= config.app%>/', SRC: [' Js/**/*.js '], dest:' <%= config.dest%>/dest/'} } });//Loading pluginsGrunt.loadnpmtasks (' Grunt-contrib-copy ')};
- Config and Pkg are constants, where config is defined conveniently at the beginning of the file and is easy to be modified later.
- Copy as task, load "Grunt-contrib-copy" plugin
- The JS in copy is target and can be executed by grunt Copy:js
A wildcard Description:
wildcard characters |
Description |
* |
Matches any number of characters, but does not match/ |
? |
Matches a single character, but does not match/ |
** |
Match any number of characters, including/, as long as it is the only part of the path |
{} |
Allows you to use a comma-separated "or" expression list |
! |
At the beginning of the pattern is used to exclude any files matching a matching pattern |
A. foo/*.js
will match all files at the end of the foo/directory .js
;
B. foo/**/*js
will match the foo/directory and all of its subdirectories with .js
the ending file.
Template Description:
<%= %>
the templates specified using separators automatically extend the scan when the task reads the corresponding data from their configuration. The use of grunt and its methods in the template are valid, for example:<%= grunt.template.today(‘yyyy-mm-dd‘) %>
1. Task Configuration and Objectives
When you run a task, Grunt automatically finds the property with the same name in the configuration object.
grunt copy
Automatically matches the initConfig()
copy property in the method and, without specifying the target, iterates through all the targets and processes them sequentially. You can also specify both task and target, which grunt copy:js
will only handle the configuration of the specified target.
2. Options Properties
In a task configuration, the Options property can be used to specify a default value that overrides the built-in properties. In addition, each target can also have an options attribute specifically targeted at this target. note that the options object is optional and can be ignored if it is not required.
grunt.initConfig({ concat: { options: { // 这里是任务级的Options,覆盖默认值 }, foo: { options: { //"foo" target options may go here, overriding task-level options. }, }, bar: { //No options specified; this target will use task-level options. }, },});
3. Documents
Since most of the tasks are performing file operations, Grunt has a powerful abstraction layer that declares which files the task should manipulate.
(1) compact format
Each target corresponds to a src-dest file map
copy{ js: { src: [‘<%= config.app %>/js/**/*.js‘], dest: ‘<%= config.dest %>/‘ }, html{ src: ‘<%= config.app %>/html/**/*.html‘, dest: ‘<%= config.dest %>/‘ }}
(2) File Object Format
Each target corresponds to multiple file mappings in src-dest form, the property name is the target file, and the source file is its value (the source file list is declared with an array format).
copy: { ‘<%= config.dest %>/‘: [‘<%= config.app %>/js/**/*.js‘‘<%= config.app %>/html/**/*.html‘]}
(3) file array format
Multiple Src-dest file mappings per target
copy{ bulid: { files: [{ src: [‘<%= config.app %>/js/**/*.js‘], dest: ‘<%= config.dest %>/‘}, { src: ‘<%= config.app %>/html/**/*.html‘, dest: ‘<%= config.dest %>/‘}] }}
The following properties can be supported in compact format and file array format :
Properties |
Description |
Filter |
It is by accepting any one of the valid FS. Stats the method name or a function to match the src file path and returns TRUE or false based on the matching result |
Nonull |
If set to true, the unmatched pattern will also be executed. Combined with Grunt's –verbore flag, this option can help to debug file path problems |
Dot |
It allows the pattern pattern to match the file name at the beginning of the period, even if the pattern does not specify whether the beginning of the file has a period |
Matchbase |
If you set this property, the missing slash pattern (meaning that you cannot match the file path with a slash in the pattern) will not match the file name contained in the slash. For example, A?b will match/XYZ/123/ACB but does not match/xyz/acb/123 |
Expand |
Handling Dynamic Src-dest File mappings |
Example: Filter
clean : {< Span class= "Hljs-attribute" >foo : {src: [ ' tmp/**/* ' ], filter: ' isfile ' , }, bar: {src : [ ' tmp/**/* ' ], filter: function (filepath ) {return (Grunt.file. && require ( ' FS ' ) . readdirsync (filepath) . length = = 0 ) ; ,}}
Where Isfile is the method in Fs.stats, can be directly referenced! Of course, you can also customize the filter, whose function the first parameter is the current file path, the above custom function is the empty folder .
When you want to work with a large number of individual files, you can dynamically build a list of files with some additional properties. As a precondition,expand is set to true:
cwd
|
|
all SRC-specified matches will be relative to the path specified here (but not including this path) |
src< /td> |
|
dest |
|
ext |
|
extdot |
|
flatten |
|
rename |
|
Third, add: 1. Grunt supports asynchronous notation, please refer to its API2. To create an issue, refer to its FAQ 3. Each task execution time can be counted by the plug-in "Time-grunt"
require(‘time-grunt‘)(grunt);
Anatomy Grunt Task Configuration