Grunt Tutorial 2: How to configure tasks with Gruntfile

Source: Internet
Author: User
Tags glob

The task configuration for grunt is specified in the Grunt.initconfig method in Gruntfile. This configuration primarily includes attributes named with the task name, and any other data. Once these properties that represent arbitrary data conflict with the properties required by the task, they are ignored.

As an example:


//



My_src_files: [' foo/*.js ', ' bar/*.js ']
});

When you run a task, Grunt automatically finds the property with the same name in the configuration object. Multi-tasking (multi-task) can define multiple configurations with any named target. In the following example, the Concat task is known as Foo and bar two targets, while the uglify task has only one named bar target.

grunt.initconfig ({  concat: {    foo: {      //  concat task "foo" target options and files go he Re.     },    bar: {      //  concat task "bar" target options and files go here.     },  },  uglify: {    bar: {      //  uglify task "bar" target options and Files go here.     },  },});

If you specify both a task (task) and a target, such as grunt Concat:foo or grunt Concat:bar, only the configuration of the specified target will be processed and run grunt Concat will traverse all targets and process them sequentially. Note that if a task is renamed with Grunt.task.renameTask, Grunt will look for a property named after the new task name in the configuration object.

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. The target-level options will override the task-level options. The options object is optional and can be ignored if it is not required.

As an example:

grunt.initconfig ({  concat: {    options: {          //       },    foo: {      Opti ONS: {            //  "foo" target options may go here, overriding task-level options.       }    },    bar: {          //  No options specified; this target would use Task-lev El Options. }}   );

Since most of the tasks are performing file operations, Grunt has a powerful abstraction layer that declares which files the task should manipulate.

There are several ways to define Src-dest (source file-target file) file mappings, all of which provide different degrees of description and control of how they operate. Any multi-tasking (multi-task) can understand the following format, so you just have to choose the format that meets your needs.

Compact format

This form allows each target to correspond to a src-dest file mapping. Typically it is used for read-only tasks, such as Grunt-contrib-jshint, which requires only a single SRC attribute, without the associated dest option. This format also supports assigning additional attributes to each src-dest file map, for example:

grunt.initconfig ({  jshint: {    foo: {      src: [' src/aa.js ', ' src/aaa.js ']    },  },  Concat: {    bar: {      src: [' src/bb.js ', ' src/bbb.js '],      ' dest/b.js ',
...... }, },});
File Object Format

This form supports multiple src-dest forms of file mapping for each target, the property name is the target file, and the source file is its value (the source file list is declared with an array format). You can specify multiple src-dest file mappings in this way, but you cannot specify additional properties for each map. As an example:

grunt.initconfig ({  concat: {    foo: {      files: {        ' dest/a.js ': [' src/aa.js ', ' src/aaa.js '],         ' dest/a1.js ': [' src/aa1.js ', ' src/aaa1.js '],      },    },    bar: {      files: {        ' dest /b.js ': [' src/bb.js ', ' src/bbb.js '],        ' dest/b1.js ': [' src/bb1.js ', ' src/bbb1.js '],      },    },  },});
File Array format

This form supports multiple src-dest file mappings for each target, and also allows each map to have additional attributes, for example:

grunt.initconfig ({  concat: {    foo: {      files: [        {src: [' src/aa.js ', ' src/aaa.js '], dest: ' dest/ A.js '},        {src: [' src/aa1.js ', ' src/aaa1.js '], dest: ' Dest/a1.js '},      ],    },    bar: {      Files: [        {src: [True},        {src: [' src/bb1.js ', ' src/bbb1.js '], dest: ' dest/b1/', Filter: ' Isfile '},      ],    },}  ,});
Older formats

This format is deprecated, please try not to use, so do not explain.

All of the above file formats support the SRC and Dest properties, in addition the "compact" [compact] and "Files array" [file array formats] also support some of the following additional properties:

(1) Filter: It accepts 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.
(2) 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.
(3) Dot: It allows the pattern to match the file name at the beginning of the period, even if the pattern does not specify whether there are periods at the beginning of the file name.
(4) Matchbase: If you set this property, the missing slash pattern (meaning that the pattern cannot use a slash for file path matching) 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.
(5) Expand: Deal with Dynamic src-dest file mapping, more information please see the dynamic construction file object, here do not know, the following is explained in detail.
(6) Other properties are passed as matches to the underlying library. Please see the Node-glob and Minimatch documentation for more information, which is not known here, but is explained in more detail below.

Custom Filter Functions

The Filter property can provide a more advanced, detailed help for your target file. You only need to use a valid FS. The Stats method name. The following configuration simply cleans up a real file that matches the pattern:

grunt.initconfig ({clean  : {    foo: {      src: [' tmp/**/* '],      ' isfile ',    },  },});

or create your own filter function to return or, depending on whether the file matches true false . The following example will simply clean up an empty directory:

grunt.initconfig ({clean  : {    foo: {      src: [' tmp/**/* '],      function( FilePath) {        return (Grunt.file.isDir (filepath) && require (' FS '). Readdirsync (filepath). Length = = 0);},}, (}  );
Wildcard mode

It is often impractical to specify all source file paths separately, so grunt matches filenames (also known as globbing) by using built-in support for Node-glob and minimatch libraries.

You only need to know how to use them in the file path matching process:

*: matches any number of characters, but does not match/
?: Matches a single character, but does not match/
* *: Matches any number of characters, including/, as long as it is the only part of the path
{}: Allow use of a comma-separated "or" expression list
!: At the beginning of the pattern to exclude any files that match a matching pattern
What everyone needs to know is that Foo/*.js will match all the. js files that are located in the foo/directory, and Foo/**/*js will match all files in the foo/directory and its subdirectories that end in. js.

In addition, to simplify the inherently complex wildcard pattern, Grunt allows you to specify a file path in the form of an array or a wildcard pattern. All patterns are processed sequentially, and during the process of pattern processing, the files that match the pattern with the! Prefix are not included in the result set. And every single item in the result set is unique.

For example:

//Specify a single file:{src: ' foo/this.js ', dest: ...}//specify an array of files:{src: [' foo/this.js ', ' foo/that.js ', ' foo/the-other.js '], dest: ...}//use a matching pattern:{src: ' foo/th*.js ', dest: ...}//an independent Node-glob mode:{src: ' foo/{a,b}*.js ', dest: ...}//You can also write this:{src: [' foo/a*.js ', ' foo/b*.js '], dest: ...}//all. js files in the Foo directory, sorted alphabetically:{src: [' foo/*.js '], dest: ...}//The first is bar.js, followed by the remaining. js files, sorted alphabetically:{src: [' foo/bar.js ', ' foo/*.js '], dest: ...}//all. js files except Bar.js, sorted alphabetically:{src: [' foo/*.js ', '!foo/bar.js '], dest: ...}//all. js files sorted alphabetically, but bar.js at the end. {src: [' foo/*.js ', '!foo/bar.js ', ' foo/bar.js '], dest: ...}//templates can also be used in file paths or in matching modes:{src: [' src/<%= basename%>.js '], dest: ' build/<%= basename%>.min.js '}//They can also refer to the list of other files defined in the configuration:{src: [' foo/*.js ', ' <%= jshint.all.src%> '], dest: ...}
Dynamically Building file objects

When you want to work with a large number of individual files, there are some additional properties that you can use to dynamically build a list of files. These properties can be used in a compact format and file-map format for file array formats.

Expand is set to true to enable the following options:

(1) CWD: All SRC-specified matches will be relative to the path specified here (but this path is not included).
(2) src: The matching mode relative to the CWD path.
(3) Dest: Destination file path prefix.
(4) Ext: This attribute value is used to replace the extension for all actual files in the generated dest path.
(5) Flatten: Removes all path parts from the generated dest path.
(6) Rename: This function is called on each of the matching src files (after renaming the suffix and removing the path). Dest and the matching SRC path will be passed in as parameters, and this function should return a new dest value. If the same dest returns more than once, each SRC source that returns this value is added to an array as the source list.

As an example:

Grunt.initconfig ({uglify: {static_mappings: {//Because These src-dest file mappings is manually specified, every      //Time A new file is added or removed, the gruntfile have to be updated.files: [{src:' Lib/a.js ', dest: ' Build/a.min.js '}, {src:' Lib/b.js ', dest: ' Build/b.min.js '}, {src:' Lib/subdir/c.js ', dest: ' Build/subdir/c.min.js '}, {src:' Lib/subdir/d.js ', dest: ' Build/subdir/d.min.js '},],}, Dynamic_mappings: {//Grunt would search for "**/*.js" under "lib/" when the "uglify" task      //runs and build the appropriate src-dest file mappings Then      //don ' t need to update the gruntfile if files are added or removed.files: [{expand:true,//Enable dynamic expansion.CWD: ' lib/',//SRC matches is relative to this path.SRC: [' **/*.js '],//Actual pattern (s) to match.Dest: ' build/',//Destination path prefix.Ext: '. Min.js ',//Dest filepaths 'll has this extension.        },      ],    },  },});

In the example above, the static_mappings and dynamic_mappings two targets in the Uglify task have the same list of src-dest file mappings because grunt automatically expands when the task runs Dynamic_ The Mappings file object is 4 separate static src-dest file mappings--assuming that these 4 files can be found. You can specify any static src-dest and dynamic Src-dest file mappings to combine with each other.

Template

<% %>templates specified using separators automatically expand the scan when the task reads the corresponding data from their configuration. The template is expanded recursively until the remaining template-related information (which matches the template) is no longer present in the configuration.

In addition, the use of the template grunt and its methods are valid, for example: <%= grunt.template.today(‘yyyy-mm-dd‘) %> .

    • <%= prop.subprop %>The value in the configuration information will be expanded automatically prop.subprop , regardless of the type. Templates like this can be used not only to reference string values, but also to reference arrays or other object-type values.
    • <% %>Executes any inline JavaScript code. is very useful for control flows or loops.

As an example:

Grunt.initconfig ({concat: {sample: {options: {banner :'/* <%= baz%> */\n ',//'/* ABCDE */\n '}, src: [' <%= qux%> ', ' baz/*.js '],//[[' Foo/*.js ', ' bar/*.js '], ' baz/*.js ']Dest: ' build/<%= baz%>.js ',//' Build/abcde.js '    },  },  //any property used for the task configuration templateFoo: ' C ', bar:' b<%= foo%>d ',//' BCD 'Baz: ' a<%= bar%>e ',//' ABCDE 'Qux: [' foo/*.js ', ' bar/*.js '],});

As an concat example of the task configuration above, the runtime grunt concat:sample will /* abcde */, foo/*.js bar/*.js baz/*.js generate a build/abcde.js file named by using all of the files in banner, along with + +.

Import External Data

Grunt has a Grunt.file.readJSON and Grunt.file.readYAML two methods for introducing JSON and YAML data.

As an example:

grunt.initconfig ({  Pkg:grunt.file.readJSON (' Package.json '),  uglify: {    options: {       ‘/*! <%= pkg.name%> <%= grunt.template.today ("Yyyy-mm-dd")%> */\n '    },    dist: {      ' src/< %= pkg.name%>.js ',      ' dist/<%= pkg.name%>.min.js '}}  );

In the above gruntfile, the metadata for the project is imported from the Package.json file into the grunt configuration, and the uglify in the Grunt-contrib-uglify plugin A task is configured to compress a source file and generate a banner annotation dynamically using that metadata.

Come on!

Grunt Tutorial 2: How to configure tasks with Gruntfile

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.