UNPKG

19.8 kBMarkdownView Raw
1[Grunt homepage](https://github.com/cowboy/grunt) | [Documentation table of contents](toc.md)
2
3# [The grunt API](api.md) / grunt.task
4
5Register and run tasks and helpers, load external tasks.
6
7See the [task lib source](../lib/grunt/task.js) and [task util lib source](../lib/util/task.js) for more information.
8
9## The task API
10
11Note that any method marked with a ☃ (unicode snowman) is also available directly on the `grunt` object. Just so you know. See the [API main page](api.md) for more usage information.
12
13
14## Creating Tasks
15Tasks are grunt's bread and butter. The stuff you do most often, like `lint` or `test`. Every time grunt is run, you specify one more more tasks to run, which tells grunt what you'd like it to do.
16
17If you don't specify a task, but a task named "default" has been defined, that task will run (unsurprisingly) by default.
18
19### grunt.task.registerTask ☃
20Register an "alias task" or a task function. This method supports the following two signatures:
21
22**Alias task**
23
24If a task list is specified, the new task will be an alias for one or more other tasks. Whenever this "alias task" is run, every specified task in `taskList` will be run, in the order specified. The `taskList` argument can be a space-separated string or an array of task names.
25
26```javascript
27grunt.task.registerTask(taskName, taskList)
28```
29
30This example alias task defines a "default" task whereby the "lint", "qunit", "concat" and "min" tasks are run automatically if grunt is executed without any tasks specified:
31
32```javascript
33task.registerTask('default', 'lint qunit concat min');
34```
35
36**Function task**
37
38If a `description` and `taskFunction` are passed, the specified function will be executed whenever the task is run. In addition, the specified description will be shown when `grunt --help` is run. Task-specific properties and methods are available inside the task function as properties of the `this` object. The task function can return `false` to indicate that the task has failed.
39
40Note that the `grunt.task.registerMultiTask` method, explained below, can be used to define a special type of task known as a "multi task."
41
42```javascript
43grunt.task.registerTask(taskName, description, taskFunction)
44```
45
46This example task logs `foo, testing 123` if grunt is run via `grunt foo:testing:123`. If the task is run without arguments as `grunt foo` the task logs `foo, no args`.
47
48```javascript
49grunt.task.registerTask('foo', 'A sample task that logs stuff.', function(arg1, arg2) {
50 if (arguments.length === 0) {
51 grunt.log.writeln(this.name + ", no args");
52 } else {
53 grunt.log.writeln(this.name + ", " + arg1 + " " + arg2);
54 }
55});
56```
57
58See the [creating tasks](types_of_tasks.md) documentation for more examples of tasks and alias tasks.
59
60_This method is also available as [grunt.registerTask](api.md)._
61
62
63### grunt.task.registerMultiTask ☃
64Register a "multi task." A multi task is a task that implicitly iterates over all of its named sub-properties (AKA targets) if no target was specified. In addition to the default properties and methods, extra multi task-specific properties are available inside the task function as properties of the `this` object.
65
66Many of the built-in tasks, including the [lint task](task_lint.md), [concat task](task_concat.md) and [min task](task_min.md) are multi tasks.
67
68```javascript
69grunt.task.registerMultiTask(taskName, description, taskFunction)
70```
71
72Given the specified configuration, this example multi task would log `foo: 1,2,3` if grunt was run via `grunt log:foo`, or it would log `bar: hello world` if grunt was run via `grunt log:bar`. If grunt was run as `grunt log` however, it would log `foo: 1,2,3` then `bar: hello world` then `baz: false`.
73
74```javascript
75grunt.initConfig({
76 log: {
77 foo: [1, 2, 3],
78 bar: 'hello world',
79 baz: false
80 }
81});
82
83grunt.task.registerMultiTask('log', 'Log stuff.', function() {
84 grunt.log.writeln(this.target + ': ' + this.data);
85});
86```
87
88See the [creating tasks](types_of_tasks.md) documentation for more examples of multi tasks.
89
90_This method is also available as [grunt.registerMultiTask](api.md)._
91
92
93### grunt.task.registerInitTask ☃
94Register an "init task." An init task is a task that doesn't require any configuration data, and as such will still run even if grunt can't find a [grunt.js gruntfile](getting_started.md). The included [init task](task_init.md) is an example of an "init task."
95
96```javascript
97grunt.task.registerInitTask(taskName, description, taskFunction)
98```
99
100For an init task example, see the [init task source](../tasks/init.js).
101
102_This method is also available as [grunt.registerInitTask](api.md)._
103
104### grunt.task.renameTask ☃
105Rename a task. This might be useful if you want to override the default behavior of a task, while retaining the old name.
106
107```javascript
108grunt.task.renameTask(oldname, newname)
109```
110
111_This method is also available as [grunt.renameTask](api.md)._
112
113## Inside Tasks
114An object is made available as `this` inside each task function that contains a number of useful task-specific properties and methods. This same object is also exposed as `grunt.task.current` for use in [templates](api_template.md).
115
116### this.async / grunt.task.current.async
117If a task is asynchronous, this method must be invoked to instruct grunt to wait. It returns a handle to a "done" function that should be called when the task has completed. `false` can be passed to the done function to indicate that the task has failed. If this method isn't invoked, the task executes synchronously.
118
119```javascript
120// Tell grunt this task is asynchronous.
121var done = this.async();
122// Your async code.
123setTimeout(function() {
124 // Let's simulate an error, sometimes.
125 var success = Math.random() > 0.5;
126 // All done!
127 done(success);
128}, 1000);
129```
130
131### this.requires / grunt.task.current.requires
132If one task depends on the successful completion of another task (or tasks), this method can be used to force grunt to abort if the other task didn't run, or if the other task failed. The task list can be a space-separated string, an array of task names, or individual task name arguments.
133
134Note that this won't actually run the specified task(s), it will just fail the current task if they haven't already run successfully.
135
136```javascript
137this.requires(taskList)
138```
139
140### this.requiresConfig / grunt.task.current.requiresConfig
141Fail the current task if one or more required [config](api_config.md) properties is missing. One or more string or array config properties may be specified.
142
143```javascript
144this.requiresConfig(prop [, prop [, ...]])
145```
146
147See the [grunt.config documentation](api_config.md) for more information about config properties.
148
149_This method is an alias for the [grunt.config.requires](api_config.md) method._
150
151### this.name / grunt.task.current.name
152The name of the task, as defined in `grunt.registerTask`. For example, if a "sample" task was run as `grunt sample` or `grunt sample:foo`, inside the task function, `this.name` would be `"sample"`.
153
154### this.nameArgs / grunt.task.current.nameArgs
155The name of the task, as specified with any colon-separated arguments or flags on the command-line. For example, if a "sample" task was run as `grunt sample:foo`, inside the task function, `this.nameArgs` would be `"sample:foo"`.
156
157### this.args / grunt.task.current.args
158An array of arguments passed to the task. For example, if a "sample" task was run as `grunt sample:foo:bar`, inside the task function, `this.args` would be `["foo", "bar"]`. Note that in multi tasks, the target is removed from the `this.args` array and is not passed into the task function.
159
160### this.flags / grunt.task.current.flags
161An object generated from the arguments passed to the task. For example, if a "sample" task was run as `grunt sample:foo:bar`, inside the task function, `this.flags` would be `{foo: true, bar: true}`. In a multi task, the target name is not set as a flag.
162
163### this.errorCount / grunt.task.current.errorCount
164The number of [grunt.log.error](api_log.md) calls that occurred during this task. This can be used to fail a task if errors occurred during the task.
165
166
167## Inside Multi Tasks
168
169### this.target / grunt.task.current.target
170In a multi task, this is the name of the target currently being iterated over. For example, if a "sample" multi task was run as `grunt sample:foo` with the config data `{sample: {foo: "bar"}}`, inside the task function, `this.target` would be `"foo"`.
171
172### this.data / grunt.task.current.data
173In a multi task, this is the actual data stored in the grunt config object for the given target. For example, if a "sample" multi task was run as `grunt sample:foo` with the config data `{sample: {foo: "bar"}}`, inside the task function, `this.data` would be `"bar"`.
174
175### this.file / grunt.task.current.file
176In a multi task, target data can be stored in two different formats. A relatively basic "compact" format and a much more flexible "full" format. When the compact format is used, that key and value are made available as `this.file.dest` and `this.file.src`, respectively. When the full format is used, the specified `src` and `dest` values are used for `this.file.dest` and `this.file.src`.
177
178Note that while grunt supports expanding [templates](api_template.md) for both `src` and `dest`, they only work for the `dest` file path when the _full_ format is used.
179
180```javascript
181grunt.initConfig({
182 concat: {
183 // This is the "compact" format.
184 'dist/built.js': ['src/file1.js', 'src/file2.js'],
185 // This is the "full" format.
186 built: {
187 src: ['src/file1.js', 'src/file2.js'],
188 dest: 'dist/built.js'
189 }
190 }
191});
192```
193
194
195## Loading Externally-Defined Tasks
196For most projects, tasks and helpers will be defined in the [grunt.js gruntfile](getting_started.md). For larger projects, or in cases where tasks and helpers need to be shared across projects, tasks can be loaded from one or more external directories or Npm-installed grunt plugins.
197
198### grunt.task.loadTasks ☃
199Load task-related files from the specified directory, relative to the [grunt.js gruntfile](getting_started.md). This method can be used to load task-related files from a local grunt plugin by specifying the path to that plugin's "tasks" subdirectory.
200
201```javascript
202grunt.task.loadTasks(tasksPath)
203```
204
205_This method is also available as [grunt.loadTasks](api.md)._
206
207
208### grunt.task.loadNpmTasks ☃
209Load tasks and helpers from the specified grunt plugin. This plugin must be installed locally via npm, and must be relative to the [grunt.js gruntfile](getting_started.md). Grunt plugins can be created by using the [gruntplugin init template](task_init.md).
210
211```javascript
212grunt.task.loadNpmTasks(pluginName)
213```
214
215_This method is also available as [grunt.loadNpmTasks](api.md)._
216
217
218## Helpers
219Helpers are utility functions that can be used by any task.
220
221For example, in the [min task](../tasks/min.js), the majority of the actual minification work is done in an `uglify` helper, so that other tasks can utilize that minification code if they want to.
222
223See the list of [built-in helpers](helpers_directives.md) for examples.
224
225### grunt.task.registerHelper ☃
226Register a helper function that can be used by any task. When called as a directive, `this.directive` will be true inside of the helper.
227
228```javascript
229grunt.task.registerHelper(helperName, helperFunction)
230```
231
232In this example helper, the numbers `1` and `2` are passed in and the value `3` is returned.
233
234```javascript
235grunt.task.registerHelper("add_two_nums", function(a, b) {
236 return a + b;
237});
238```
239
240_This method is also available as [grunt.registerHelper](api.md)._
241
242### grunt.task.renameHelper ☃
243Rename a helper. This might be useful if you want to override the default behavior of a helper, while retaining the old name (to avoid having to completely recreate an already-made task just because you needed to override or extend a built-in helper).
244
245```javascript
246grunt.task.renameHelper(oldname, newname)
247```
248
249_This method is also available as [grunt.renameHelper](api.md)._
250
251### grunt.task.helper ☃
252Invoke a registered helper function.
253
254```javascript
255grunt.task.helper(helperName [, arguments...])
256```
257
258In this example, the previously defined `add_two_nums` helper is invoked.
259
260```javascript
261grunt.task.helper("add_two_nums", 1, 2) // 3
262```
263
264_This method is also available as [grunt.helper](api.md)._
265
266## Directives
267Directives are essentially string placeholders for helper functions, specified as values in the [config object](getting_started.md).
268
269A good example of directives would be the `<json:package.json>` and `<config:lint.all>` directives in grunt's own [grunt.js gruntfile](../grunt.js). Or the `<banner>` and `<file_strip_banner:src/grunt-jquery-example.js>` directives in the [sample jQuery plugin gruntfile](https://github.com/cowboy/grunt-jquery-example/blob/master/grunt.js).
270
271See the list of [built-in directives](helpers_directives.md) for examples.
272
273### grunt.task.directive
274Manually execute a helper based on the passed string directive, returning its value. Note that this only works for synchronous helpers. When called as a directive, `this.directive` will be true inside of the helper.
275
276```javascript
277grunt.task.directive(directive)
278```
279
280In this example, note that the arguments passed into the helper must be coerced into numbers because all directive arguments are passed into the helper as strings.
281
282```javascript
283grunt.task.registerHelper('add_two_numbers', function(a, b) {
284 return Number(a) + Number(b);
285});
286
287grunt.task.directive('<add_two_numbers:1:2>') // 3
288```
289
290### grunt.task.getDirectiveParts
291Split a valid directive into its components. Returns `null` if the string can't be parsed as a directive or if the directive doesn't match an existing helper.
292
293```javascript
294grunt.task.getDirectiveParts(directive)
295```
296
297In this example, the directive can't be parsed initially because the appropriate helper hasn't been defined. Once the helper has been defined, the directive can be parsed.
298
299```javascript
300grunt.task.getDirectiveParts('<foo:bar:baz>') // null
301
302grunt.task.registerHelper('foo', function() {});
303grunt.task.getDirectiveParts('<foo:bar:baz>') // ['foo', 'bar', 'baz']
304```
305
306
307## Queueing Tasks
308Grunt automatically enqueues and runs all tasks specified on the command line, but individual tasks can enqueue additional tasks to be run.
309
310### grunt.task.run
311Enqueue one or more tasks. Every specified task in `taskList` will be run immediately after the current task completes, in the order specified. The task list can be a space-separated string, an array of task names, or individual task name arguments.
312
313```javascript
314grunt.task.run(taskList)
315```
316
317See the [watch task source](../tasks/watch.js) for an example.
318
319### grunt.task.clearQueue
320Empty the task queue completely. Unless additional tasks are enqueued, no more tasks will be run.
321
322```javascript
323grunt.task.clearQueue()
324```
325
326See the [watch task source](../tasks/watch.js) for an example.
327
328
329## Search Directories
330For a given tasks file or related task "extra" file, these paths will be searched in this order, aka "task path order," until the first matching file is found.
331
3321. The grunt user tasks directory, ie. `grunt.file.userDir('tasks')`.
3332. Npm-installed [grunt plugins](plugins.md) or tasks directories specified on the command-line via the `--tasks` option.
3343. Npm-installed grunt plugins, tasks directories or individual tasks and helpers specified in the [grunt.js gruntfile](getting_started.md).
3354. Task directories built-in to a Npm-installed grunt plugin run via its `grunt-` named binary.
3365. The [built-in grunt tasks directory](../tasks).
337
338This allows referenced Npm-installed grunt plugins, tasks directories, the [grunt.js gruntfile](getting_started.md) and even the user to override grunt functionality as needed.
339
340For example, a grunt plugin may add a new "foo" task in its `tasks/foo.js`, completely override an existing task like the [concat task](task_concat.md) in its `tasks/concat.js` or add a new "bar" [init task](task_init.md) template with its `tasks/init/bar.js` and "extra" files in its `tasks/init/bar/` directory. In your personal user tasks directory, you can create your own "baz" init task template with a `tasks/init/baz.js` file or even override individual init template "extra" files like `tasks/init/jquery/root/README.md` just by creating them.
341
342**When defining project-specific tasks or "extra" files, it's always a good idea to include those files in a grunt plugin or tasks directory referenced in the [grunt.js gruntfile](getting_started.md), and committed with the project when possible. This will help to guarantee consistent grunt behavior for all contributors to that project.**
343
344### grunt.task.searchDirs
345An array of directory paths that grunt uses to search for task-related files, in "task path order." This array is used by all task-specific file listing methods.
346
347```javascript
348grunt.task.searchDirs
349```
350
351
352## File Lists and Wildcards
353Wildcard patterns are resolved using the [glob-whatev library](https://github.com/cowboy/node-glob-whatev). See the [minimatch](https://github.com/isaacs/minimatch) module documentation for more details on supported wildcard patterns.
354
355There are also a number of [generic file listing methods](api_file.md) that list files relative to the [grunt.js gruntfile](getting_started.md).
356
357### grunt.task.getFile
358Search tasks directories in "task path order" (via `grunt.task.searchDirs`) for a given file path, returning the path of the first matching file.
359
360**This is the primary method used to locate tasks files and extras files.**
361
362_Like the Node.js [path.join](http://nodejs.org/docs/latest/api/path.html#path_path_join_path1_path2) method, this method will join all arguments together and normalize the resulting path._
363
364```javascript
365grunt.task.getFile(path1 [, path2 [, ...]])
366```
367
368### grunt.task.expand
369Search task "search directories" for the given wildcard pattern(s), returning a unique array of all matching file paths as "file objects" in `grunt.task.searchDirs` "task path order." This method accepts one or more comma separated wildcard patterns as well as an array of wildcard patterns.
370
371The `options` object supports all [minimatch](https://github.com/isaacs/minimatch) options.
372
373```javascript
374grunt.task.expand([options, ] patterns)
375```
376
377Each "file object" item in the returned array has the following properties, and if coerced to string via `String(fileobj)` or `fileObj.toString()` returns the absolute file path value. In this way, `.map(String)` can be called on the resulting array to return an array of absolute file path strings.
378
379```javascript
380var fileobj = {
381 // The absolute path of the matched file or directory.
382 abs: absolutePath,
383 // The path of the matched file or directory, relative to the search
384 // directory in which it was found.
385 rel: relativePath,
386 // The search directory in which this file was found.
387 base: basePath
388}
389```
390
391### grunt.task.expandDirs
392This method behaves the same as `grunt.task.expand` except it only returns directory paths.
393
394```javascript
395grunt.task.expandDirs([options, ] patterns)
396```
397
398### grunt.task.expandFiles
399This method behaves the same as `grunt.task.expand` except it only returns file paths.
400
401```javascript
402grunt.task.expandFiles([options, ] patterns)
403```
404
405## JSON Defaults
406
407### grunt.task.readDefaults
408Search tasks directories for a given JSON file, merging the parsed data objects in "task path order" and returning the final merged object.
409
410**This is the primary method used to load task-related JSON default data.**
411
412_Like the Node.js [path.join](http://nodejs.org/docs/latest/api/path.html#path_path_join_path1_path2) method, this method will join all arguments together and normalize the resulting path._
413
414```javascript
415grunt.task.readDefaults(path1 [, path2 [, ...]])
416```