# Technical Documentation: gruntjs/grunt

> ℹ️ **Provenance:** Hybrid Fusion: `gruntjs/grunt` + DevDocs `grunt` · [CodeWiki Reference](https://codewiki.google/github.com/gruntjs/grunt) · Recency: Active (< 180 days)

## 1. Repository Overview (gruntjs/grunt)

# Grunt: The JavaScript Task Runner

[](https://gruntjs.com/)
[](https://qunitjs.com/)
[](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fgruntjs%2Fgrunt?ref=badge_shield)



### Documentation

Visit the [gruntjs.com](https://gruntjs.com/) website for all the things.

### Support

We support the latest version with security and bug fixes. The previous versions are all end-of-life and will not receive any security or bug fixes.

Our OpenJS Ecosystem Sustainability Program partner [HeroDevs](https://www.herodevs.com/support/grunt-nes) provides drop-in replacements for older versions of Grunt that are kept up-to-date for security and compliance issues. Learn More.

### Version Support

| Version | Supported? | Commercial Support                                                      |
| ------- | ---------- | ----------------------------------------------------------------------- |
| 1.6     | YES        |                                                                         |
| 1.5     | NO         | [Available Here](https://www.herodevs.com/support/grunt-nes) |
| 1.4     | NO         | [Available Here](https://www.herodevs.com/support/grunt-nes) |
| 1.3     | NO         | [Available Here](https://www.herodevs.com/support/grunt-nes) |
| 1.2     | NO         | [Available Here](https://www.herodevs.com/support/grunt-nes) |
| 1.1     | NO         | [Available Here](https://www.herodevs.com/support/grunt-nes) |
| 1.0     | NO         | [Available Here](https://www.herodevs.com/support/grunt-nes) |
| 0.4     | NO         | [Available Here](https://www.herodevs.com/support/grunt-nes) |

### Contributing

Before you make an issue, please read our [Contributing](https://gruntjs.com/contributing) guide.

### Release History

See the [CHANGELOG.md](./CHANGELOG.md).

### License

[MIT](LICENSE)

## 2. Official Technical Reference (DevDocs: Grunt)

# DevDocs Technical Reference: grunt

> Source: DevDocs.io (grunt) | Formatted for AI Agents & Developers | Zero-Egress Edge Persistence


## Section: index

# Grunt

Grunt and Grunt plugins are installed and managed via [npm](https://www.npmjs.org/), the [Node.js](https://nodejs.org/) package manager. Grunt 0.4.x requires stable Node.js versions `>= 0.8.0`.

 

Before setting up Grunt ensure that your [npm](https://www.npmjs.org/) is up-to-date by running `npm update -g npm` (this might require `sudo` on certain systems).

 

If you already have installed Grunt and are now searching for some quick reference, please checkout our [`Gruntfile` example](sample-gruntfile) and how to [configure a task](configuring-tasks).

 

## Installing the CLI

 

**Using Grunt 0.3? Please see [Grunt 0.3 Notes](upgrading-from-0.3-to-0.4#grunt-0.3-notes)**

 

In order to get started, you'll want to install Grunt's command line interface (CLI) globally. You may need to use sudo (for OSX, *nix, BSD etc) or run your command shell as Administrator (for Windows) to do this.

 

```
npm install -g grunt-cli
```

 

This will put the `grunt` command in your system path, allowing it to be run from any directory.

 

Note that installing `grunt-cli` does not install the Grunt task runner! The job of the Grunt CLI is simple: run the version of Grunt which has been installed next to a `Gruntfile`. This allows multiple versions of Grunt to be installed on the same machine simultaneously.

 

## How the CLI works

 

Each time `grunt` is run, it looks for a locally installed Grunt using node's `require()` system. Because of this, you can run `grunt` from any subfolder in your project.

 

If a locally installed Grunt is found, the CLI loads the local installation of the Grunt library, applies the configuration from your `Gruntfile`, and executes any tasks you've requested for it to run. To really understand what is happening, [read the code](https://github.com/gruntjs/grunt-cli/blob/master/bin/grunt).

 

## Working with an existing Grunt project

 

Assuming that the Grunt CLI has been installed and that the project has already been configured with a `package.json` and a `Gruntfile`, it's very easy to start working with Grunt:

 
 - Change to the project's root directory.
 - Install project dependencies with `npm install`.
 - Run Grunt with `grunt`.
 
 

That's really all there is to it. Installed Grunt tasks can be listed by running `grunt --help` but it's usually a good idea to start with the project's documentation.

 

## Preparing a new Grunt project

 

A typical setup will involve adding two files to your project: `package.json` and the `Gruntfile`.

 

**package.json**: This file is used by [npm](https://www.npmjs.org/) to store metadata for projects published as npm modules. You will list grunt and the Grunt plugins your project needs as [devDependencies](https://docs.npmjs.com/files/package.json#devdependencies) in this file.

 

**Gruntfile**: This file is named `Gruntfile.js` or `Gruntfile.coffee` and is used to configure or define tasks and load Grunt plugins. **When this documentation mentions a `Gruntfile` it is talking about a file, which is either a `Gruntfile.js` or a `Gruntfile.coffee`**.

 

## package.json

 

The `package.json` file belongs in the root directory of your project, next to the `Gruntfile`, and should be committed with your project source. Running `npm install` in the same folder as a `package.json` file will install the correct version of each dependency listed therein.

 

There are a few ways to create a `package.json` file for your project:

 
 - Most [grunt-init](project-scaffolding) templates will automatically create a project-specific `package.json` file.
 - The [npm init](https://docs.npmjs.com/cli/init) command will create a basic `package.json` file.
 - Start with the example below, and expand as needed, following this [specification](https://docs.npmjs.com/files/package.json).
 
 

```
{
  "name": "my-project-name",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-jshint": "~0.10.0",
    "grunt-contrib-nodeunit": "~0.4.1",
    "grunt-contrib-uglify": "~0.5.0"
  }
}
```

 

### Installing Grunt and gruntplugins

 

The easiest way to add Grunt and gruntplugins to an existing `package.json` is with the command `npm install  --save-dev`. Not only will this install `` locally, but it will automatically be added to the [devDependencies](https://docs.npmjs.com/files/package.json#devdependencies) section, using a [tilde version range](https://docs.npmjs.com/cli/v6/using-npm/semver#ranges).

 

For example, this will install the latest version of Grunt in your project folder, adding it to your devDependencies:

 

```
npm install grunt --save-dev
```

 

The same can be done for gruntplugins and other node modules. As seen in the following example installing the JSHint task module:

 

```
npm install grunt-contrib-jshint --save-dev
```

 

Checkout the current available gruntplugins to be installed and used on your project at the [plugins](https://gruntjs.com/plugins) page.

 

Be sure to commit the updated `package.json` file with your project when you're done!

 

## The Gruntfile

 

The `Gruntfile.js` or `Gruntfile.coffee` file is a valid JavaScript or CoffeeScript file that belongs in the root directory of your project, next to the `package.json` file, and should be committed with your project source.

 

A `Gruntfile` is comprised of the following parts:

 
 - The "wrapper" function
 - Project and task configuration
 - Loading Grunt plugins and tasks
 - Custom tasks
 
 

### An example Gruntfile

 

In the following `Gruntfile`, project metadata is imported into the Grunt config from the project's `package.json` file and the [grunt-contrib-uglify](https://github.com/gruntjs/grunt-contrib-uglify) plugin's `uglify` task is configured to minify a source file and generate a banner comment dynamically using that metadata. When `grunt` is run on the command line, the `uglify` task will be run by default.

 

```
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/<%= pkg.name %>.js',
        dest: 'build/<%= pkg.name %>.min.js'
      }
    }
  });

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Default task(s).
  grunt.registerTask('default', ['uglify']);

};
```

 

Now that you've seen the whole `Gruntfile`, let's look at its component parts.

 

### The "wrapper" function

 

Every `Gruntfile` (and gruntplugin) uses this basic format, and all of your Grunt code must be specified inside this function:

 

```
module.exports = function(grunt) {
  // Do grunt-related things in here
};
```

 

### Project and task configuration

 

Most Grunt tasks rely on configuration data defined in an object passed to the [grunt.initConfig](https://gruntjs.com/grunt#grunt.initconfig) method.

 

In this example, `grunt.file.readJSON('package.json')` imports the JSON metadata stored in `package.json` into the grunt config. Because `<% %>` template strings may reference any config properties, configuration data like filepaths and file lists may be specified this way to reduce repetition.

 

You may store any arbitrary data inside of the configuration object, and as long as it doesn't conflict with properties your tasks require, it will be otherwise ignored. Also, because this is JavaScript, you're not limited to JSON; you may use any valid JS here. You can even programmatically generate the configuration if necessary.

 

Like most tasks, the [grunt-contrib-uglify](https://github.com/gruntjs/grunt-contrib-uglify) plugin's `uglify` task expects its configuration to be specified in a property of the same name. Here, the `banner` option is specified, along with a single uglify target named `build` that minifies a single source file to a single destination file.

 

```
// Project configuration.
grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  uglify: {
    options: {
      banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
    },
    build: {
      src: 'src/<%= pkg.name %>.js',
      dest: 'build/<%= pkg.name %>.min.js'
    }
  }
});
```

 

### Loading Grunt plugins and tasks

 

Many commonly used tasks like [concatenation](https://github.com/gruntjs/grunt-contrib-concat), [minification](https://github.com/gruntjs/grunt-contrib-uglify) and [linting](https://github.com/gruntjs/grunt-contrib-jshint) are available as [grunt plugins](https://github.com/gruntjs). As long as a plugin is specified in `package.json` as a dependency, and has been installed via `npm install`, it may be enabled inside your `Gruntfile` with a simple command:

 

```
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
```

 

**Note:** the `grunt --help` command will list all available tasks.

 

### Custom tasks

 

You can configure Grunt to run one or more tasks by default by defining a `default` task. In the following example, running `grunt` at the command line without specifying a task will run the `uglify` task. This is functionally the same as explicitly running `grunt uglify` or even `grunt default`. Any number of tasks (with or without arguments) may be specified in the array.

 

```
// Default task(s).
grunt.registerTask('default', ['uglify']);
```

 

If your project requires tasks not provided by a Grunt plugin, you may define custom tasks right inside the `Gruntfile`. For example, this `Gruntfile` defines a completely custom `default` task that doesn't even utilize task configuration:

 

```
module.exports = function(grunt) {

  // A very basic default task.
  grunt.registerTask('default', 'Log some stuff.', function() {
    grunt.log.write('Logging some stuff...').ok();
  });

};
```

 

Custom project-specific tasks don't need to be defined in the `Gruntfile`; they may be defined in external `.js` files and loaded via the [grunt.loadTasks](https://gruntjs.com/grunt#grunt.loadtasks) method.

 

## Further Reading

 
 - The [Installing grunt](https://gruntjs.com/installing-grunt/) guide has detailed information about installing specific, production or in-development, versions of Grunt and grunt-cli.
 - The [Configuring Tasks](https://gruntjs.com/configuring-tasks/) guide has an in-depth explanation on how to configure tasks, targets, options and files inside the `Gruntfile`, along with an explanation of templates, globbing patterns and importing external data.
 - The [Creating Tasks](https://gruntjs.com/creating-tasks/) guide lists the differences between the types of Grunt tasks and shows a number of sample tasks and configurations.
 - For more information about writing custom tasks or Grunt plugins, check out the [developer documentation](https://gruntjs.com/grunt).
 

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/getting-started](https://gruntjs.com/getting-started)

---

## Section: sample-gruntfile

# Sample Gruntfile

In this page we walk you through the creation of a `Gruntfile` that covers the usual needs of a simple project. If you already know how to set up a `Gruntfile` and you're looking for a quick example, here's one:

 

```
module.exports = function(grunt) {

  grunt.initConfig({
    jshint: {
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
      options: {
        globals: {
          jQuery: true
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['jshint']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['jshint']);

};
```

 

## Requirements

 

Every project has its own needs, but most of them have something in common. In this guide we introduce you to a few Grunt plugins to automate basic requirements. The final goal is to teach you how to configure these Grunt plugins so that you can use them in your projects.

 

For the sake of the example, let's say that you're creating a JavaScript library. The typical folder structure features the following folders: `src`, `dist`, and `test`. The `src` folder (sometimes called `app`) contains the source code of the library as you author it. The `dist` folder (sometimes called `build`) contains the distribution, a minified version of the source code. A minified file is one where all unnecessary characters, such as spaces, new lines, comments are removed, without affecting the functionality of the source code. Minified source code is especially useful for users of the project because it reduces the amount of data that needs to be transferred. Finally, the `test` folder contains the code to test the project. This set up will be used in the next sections when creating the `Gruntfile` configuration.

 

While developing the library and releasing new versions there are a few tasks that you need to perform on a regular basis. For example, you might want to ensure that the code you write adheres to best practices, or that the code you've written doesn't result in unexpected behaviors. To do that, you can employ a tool called [JSHint](http://jshint.com/about/). Grunt has an official plugin for it called [grunt-contrib-jshint](https://github.com/gruntjs/grunt-contrib-jshint) which we'll adopt in this example. In particular, you might want to ensure that as you modify your code, you don't break any rules or best practices. So, a good strategy is to check the code at every change you perform. To do that, we'll cover a Grunt plugin called [grunt-contrib-watch](https://github.com/gruntjs/grunt-contrib-watch). The latter runs predefined tasks, such as `grunt-contrib-jshint`, whenever files are added, changed, or deleted.

 

Checking that your source code follows best practices is not enough to guarantee that it's stable and doesn't contain bugs. To create a robust project, you need to test it. There are several libraries you can adopt such as [QUnit](https://qunitjs.com/) or [Jasmine](http://jasmine.github.io/). In this guide, we describe how to configure QUnit, and specifically [grunt-contrib-qunit](https://github.com/gruntjs/grunt-contrib-qunit), to test your code.

 

When it comes to distributing your work, you want to offer a version as small in size as possible. To create a minified version you need a Grunt plugin like [grunt-contrib-uglify](https://github.com/gruntjs/grunt-contrib-uglify). Moreover, unless the project you're developing is very small, chances are that you've split the code in multiple files. While this is a good practice for the developer, you want users to include only one file. So, before minifying the code, you should concatenate the source files to create a single one. To achieve this goal you need a Grunt plugin like [grunt-contrib-concat](https://github.com/gruntjs/grunt-contrib-concat).

 

To sum up, in this guide we'll use the following five Grunt plugins:

 
 - [grunt-contrib-uglify](https://github.com/gruntjs/grunt-contrib-uglify)
 - [grunt-contrib-qunit](https://github.com/gruntjs/grunt-contrib-qunit)
 - [grunt-contrib-concat](https://github.com/gruntjs/grunt-contrib-concat)
 - [grunt-contrib-jshint](https://github.com/gruntjs/grunt-contrib-jshint)
 - [grunt-contrib-watch](https://github.com/gruntjs/grunt-contrib-watch)
 
 

If you're curious about what the final result looks like, the entire `Gruntfile` can be found at the bottom of this page.

 

## Setting up the `Gruntfile`

 

The first part is the "wrapper" function, which encapsulates your Grunt configuration.

 

```
module.exports = function(grunt) {
};
```

 

Within that function we can initialize our configuration object:

 

```
grunt.initConfig({
});
```

 

Next, we can store the project settings from the `package.json` file into the `pkg` property. This allows us to refer to the values of properties within our `package.json` file, as we'll see shortly.

 

```
pkg: grunt.file.readJSON('package.json')
```

 

This leaves us with this so far:

 

```
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json')
  });
};
```

 

Now we can define a configuration for each of the tasks we mentioned. The configuration object for a plugin lives as a property on the configuration object, that often shares the same name as its plugin. The configuration for `grunt-contrib-concat` goes in the configuration object under the `concat` key as shown below:

 

```
concat: {
  options: {
    // define a string to put between each file in the concatenated output
    separator: ';'
  },
  dist: {
    // the files to concatenate
    src: ['src/**/*.js'],
    // the location of the resulting JS file
    dest: 'dist/<%= pkg.name %>.js'
  }
}
```

 

Note how in the snippet above we refer to the `name` property that's in the JSON file. We access it by using `pkg.name` as earlier we defined the `pkg` property to be the result of loading the `package.json` file, which is then parsed to a JavaScript object. Grunt has a simple template engine to output the values of properties in the configuration object. Here we tell the `concat` task to concatenate all files that exist within `src/` and end in `.js`.

 

Now let's configure the `grunt-contrib-uglify` plugin, which minifies the JavaScript code:

 

```
uglify: {
  options: {
    // the banner is inserted at the top of the output
    banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
  },
  dist: {
    files: {
      'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
    }
  }
}
```

 

This snippet tells `grunt-contrib-uglify` to create a file within `dist/` that contains the result of minifying the JavaScript files. Here we use `<%= concat.dist.dest %>` so uglify will minify the file that the concat task produces.

 

Up to this point, we have configured the plugins to create the distribution version the library. It's now time to use `grunt-contrib-qunit` to automate the testing of the code. To do that, we need to give to specify the location of the test runner files, which are the HTML files QUnit runs on. The resulting code is reported below:

 

```
qunit: {
  files: ['test/**/*.html']
},
```

 

Once done, it's time to set up the configuration to ensure that the code of the project adheres to best practices. JSHint is a tool that can detect issues or potential issues like a high cyclomatic complexity, the use of the equality operator instead of the strict equality operator, and the definition of unused variables and functions.

 

We advise you to analyze with `grunt-contrib-jshint` all the JavaScript files of your project, including `Gruntfile` and the test files. An example of configuration of `grunt-contrib-jshint` is the following:

 

```
jshint: {
  // define the files to lint
  files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
  // configure JSHint (documented at http://www.jshint.com/docs/)
  options: {
    // more options here if you want to override JSHint defaults
    globals: {
      jQuery: true,
      console: true,
      module: true
    }
  }
}
```

 

This plugin takes an array of files and then an object of options. These are all [documented on the JSHint site](http://www.jshint.com/docs/). If you're happy with the plugin defaults, there's no need to redefine them in the Gruntfile.

 

The last plugin left to configure is `grunt-contrib-watch`. We'll use it to run the `jshint` and the `qunit` tasks as soon as a JavaScript file is added, deleted, or modified. When it detects any of the files specified have changed (here, we use the same files we told JSHint to check), it will run the tasks you specify, in the order they appear. This can be run on the command line with `grunt watch`.

 

Turning the previous description into a configuration for `grunt-contrib-watch` results in the snippet below:

 

```
watch: {
  files: ['<%= jshint.files %>'],
  tasks: ['jshint', 'qunit']
}
```

 

With this snippet, we've set up the configuration for all the plugins mentioned in the introduction. The last step to perform is to load in the Grunt plugins we need. All of these should have been previously installed through npm.

 

```
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
```

 

And finally set up some tasks. The most important of these tasks is the default task:

 

```
// this would be run by typing "grunt test" on the command line
grunt.registerTask('test', ['jshint', 'qunit']);

// the default task can be run just by typing "grunt" on the command line
grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);
```

 

The default task is executed when you invoke `Grunt` without specifying a task to execute (`grunt`).

 

## The resulting `Gruntfile`

 

If you've followed this guide correctly you should have the following `Gruntfile`:

 

```
module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';'
      },
      dist: {
        src: ['src/**/*.js'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    qunit: {
      files: ['test/**/*.html']
    },
    jshint: {
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
      options: {
        // options here to override JSHint defaults
        globals: {
          jQuery: true,
          console: true,
          module: true,
          document: true
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['jshint', 'qunit']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-concat');

  grunt.registerTask('test', ['jshint', 'qunit']);

  grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);

};
```

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/sample-gruntfile](https://gruntjs.com/sample-gruntfile)

---

## Section: creating-plugins

# Creating plugins

 - Install [grunt-init](https://github.com/gruntjs/grunt-init) with `npm install grunt-init`

 - Install the gruntplugin template with `git clone git://github.com/gruntjs/grunt-init-gruntplugin.git ~/.grunt-init/gruntplugin` (`%USERPROFILE%\.grunt-init\gruntplugin` on Windows).
 - Run `grunt-init gruntplugin` in an empty directory.
 - Run `npm install` to prepare the development environment.
 - Author your plugin.
 - Run `npm publish` to publish the Grunt plugin to npm!
 
 

## Notes

 

### Naming your task

 

The "grunt-contrib" namespace is reserved for tasks maintained by the Grunt team, please name your task something appropriate that avoids that naming scheme.

 

### Debugging

 

Grunt hides error stack traces by default, but they can be enabled for easier task debugging with the `--stack` option. If you want Grunt to always log stack traces on errors, create an alias in your shell. Eg, in bash, you could do `alias grunt='grunt --stack'`.

 

### Storing task files

 

Only store data files in a .grunt/[npm-module-name]/ directory at the project's root and clean up after yourself when appropriate. This is not a solution for temporary scratch files, use one of the common npm modules (eg [temporary](https://www.npmjs.org/package/temporary), [tmp](https://www.npmjs.org/package/tmp)) that take advantage of the OS level temporary directories for that case.

 

### Avoid Changing the Current Working Directory: `process.cwd()`

 

By default, the current working directory is set to be the directory that contains the gruntfile. The user can change it using `grunt.file.setBase()` in their gruntfile, but plugins should take care to not change it.

 

`path.resolve('foo')` can be used to get the absolute path of the filepath 'foo' relative to the `Gruntfile`.

 

### Creating your task

 

You might also want to know how to [create your own tasks](creating-tasks) or take a look at the [API](https://gruntjs.com/api) reference.

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/creating-plugins](https://gruntjs.com/creating-plugins)

---

## Section: using-the-cli

# Using the CLI

## Installing the CLI

 

Run `sudo npm install grunt-cli` (Windows users should omit "sudo ", and may need to run the command-line with elevated privileges).

 

The `grunt` command-line interface comes with a series of options. Use `grunt -h` from your terminal to show these options.

 

### --help, -h

 

Display help text

 

### --base, -b

 

Specify an alternate base path. By default, all file paths are relative to the `Gruntfile`.

 

Alternative to `grunt.file.setBase(...)`

 

### --no-color

 

Disable colored output.

 

### --gruntfile

 

Specify an alternate `Gruntfile`.

 

By default, grunt looks in the current or parent directories for the nearest `Gruntfile.js` or `Gruntfile.[ext]` file.

 

### --debug, -d

 

Enable debugging mode for tasks that support it.

 

### --stack

 

Print a stack trace when exiting with a warning or fatal error.

 

### --force, -f

 

A way to force your way past warnings.

 

Want a suggestion? Don't use this option, fix your code.

 

### --tasks

 

Additional directory paths to scan for task and "extra" files.

 

Alternative to `grunt.loadTasks(...)`

 

### --npm

 

Npm-installed grunt plugins to scan for task and "extra" files.

 

Alternative to `grunt.loadNpmTasks(...)`

 

### --no-write

 

Disable writing files (dry run).

 

### --verbose, -v

 

Verbose mode. A lot more information output.

 

### --version, -V

 

Print the grunt version. Combine with --verbose for more info.

 

### --completion

 

Output shell auto-completion rules. See the grunt-cli documentation for more information.

 

### --preload

 

Specify a language interpreter to require first if you are writing your Gruntfile in a language Grunt doesn't support by default.

 

### --require (Grunt 1.3.0 and below)

 

Specify a language interpreter to require first if you are writing your Gruntfile in a language Grunt doesn't support by default.

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/using-the-cli](https://gruntjs.com/using-the-cli)

---

## Section: installing-grunt

# Installing grunt

This document explains how to install specific versions of Grunt and Grunt plugins. If you haven't read the [Getting Started](https://gruntjs.com/getting-started/) guide, you should check that out first.

 

## Overview

 

Grunt and Grunt plugins should be defined as [devDependencies](https://docs.npmjs.com/files/package.json#devdependencies) in your project's [package.json](https://docs.npmjs.com/files/package.json). This will allow you to install all of your project's dependencies with a single command: `npm install`. The current stable and development versions of Grunt are always listed on the wiki's [home page](https://github.com/gruntjs/grunt/wiki/).

 

## Installing a specific version

 

If you need a specific version of Grunt or a Grunt plugin, run `npm install grunt@VERSION --save-dev` where `VERSION` is the version you need. This will install the specified version, adding it to your package.json devDependencies.

 

Note that a [tilde version range](https://docs.npmjs.com/cli/v6/using-npm/semver#ranges) will be used in your `package.json` when you add the `--save-dev` flag to `npm install`. This is typically good, as new patch releases of the specified version will automatically be upgraded as development continues, per [semver](http://semver.org).

 

## Installing a published development version

 

Periodically, as new functionality is being developed, Grunt builds may be published to npm. These builds will *never* be installable without explicitly specifying a version number, and will typically have a build number or alpha/beta/release candidate designation.

 

Like installing a specific version of grunt, run `npm install grunt@VERSION --save-dev` where `VERSION` is the version you need, and npm will install that version of Grunt in your project folder, adding it to your `package.json` devDependencies.

 

Note that regardless of the version you specify, a [tilde version range](https://docs.npmjs.com/cli/v6/using-npm/semver#ranges) will be specified in `package.json`. **This is very bad**, as new, possibly incompatible, patch releases of the specified development version may be installed by npm, breaking your build.

 

*In this case it is **very important** that you manually edit your `package.json` and remove the ~ (tilde) from the version number. This will lock in the exact development version that you have specified.*

 

The same process may be used to install a published development version of a Grunt plugin.

 

## Installing directly from GitHub

 

If you want to install a bleeding-edge, unpublished version of Grunt or Grunt plugin, follow the instructions for specifying a [git URL as a dependency](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies) and be sure to specify an actual commit SHA (not a branch name) as the `commit-ish`. This will guarantee that your project always uses that exact version of grunt.

 

The specified git URL may be that of the official Grunt repo or a fork.

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/installing-grunt](https://gruntjs.com/installing-grunt)

---

## Section: api/grunt

# grunt

Grunt exposes all of its methods and properties on the `grunt` object that gets passed into the `module.exports` function exported in your [Gruntfile](../index), Grunt plugin or in a [tasks file](../creating-tasks).

 

Nearly all of the following methods are defined elsewhere, but are provided directly on the `grunt` object for convenience. See the individual api section docs for detailed explanations and examples.

 

## Config

 

### grunt.initConfig

 

*This method is an alias for the [grunt.config.init](https://gruntjs.com/grunt.config#grunt.config.init) method.*

 

## Creating Tasks

 

### grunt.registerTask

 

*This method is an alias for the [grunt.task.registerTask](https://gruntjs.com/grunt.task#grunt.task.registertask) method.*

 

### grunt.registerMultiTask

 

*This method is an alias for the [grunt.task.registerMultiTask](https://gruntjs.com/grunt.task#grunt.task.registermultitask) method.*

 

### grunt.renameTask

 

*This method is an alias for the [grunt.task.renameTask](https://gruntjs.com/grunt.task#grunt.task.renametask) method.*

 

## Loading Externally-Defined Tasks

 

### grunt.loadTasks

 

*This method is an alias for the [grunt.task.loadTasks](https://gruntjs.com/grunt.task#grunt.task.loadtasks) method.*

 

### grunt.loadNpmTasks

 

*This method is an alias for the [grunt.task.loadNpmTasks](https://gruntjs.com/grunt.task#grunt.task.loadnpmtasks) method.*

 

## Warnings and Fatal Errors

 

### grunt.warn

 

*This method is an alias for the [grunt.fail.warn](https://gruntjs.com/grunt.fail#grunt.fail.warn) method.*

 

### grunt.fatal

 

*This method is an alias for the [grunt.fail.fatal](https://gruntjs.com/grunt.fail#grunt.fail.fatal) method.*

 

## Command-line Options

 

### grunt.option

 

Retrieve the value of a command-line option, eg. `debug`. Note that for each command-line option, the inverse can be tested, eg. `no-debug`.

 

```
grunt.option(optionName)
```

 

## Miscellaneous

 

### grunt.package

 

The current Grunt `package.json` metadata, as an object.

 

```
grunt.package
```

 

### grunt.version

 

The current Grunt version, as a string. This is just a shortcut to the `grunt.package.version` property.

 

```
grunt.version
```

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt](https://gruntjs.com/api/grunt)

---

## Section: creating-tasks

# Creating tasks

Tasks are grunt's bread and butter. The stuff you do most often, like `jshint` or `nodeunit`. Every time Grunt is run, you specify one or more tasks to run, which tells Grunt what you'd like it to do.

 

If you don't specify a task, but a task named "default" has been defined, that task will run (unsurprisingly) by default.

 

## Alias Tasks

 

If 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 tasks in `taskList` will be run, in the order specified. The `taskList` argument must be an array of tasks.

 

```
grunt.registerTask(taskName, [description, ] taskList)
```

 

This example alias task defines a "default" task whereby the "jshint", "qunit", "concat" and "uglify" tasks are run automatically if Grunt is executed without specifying any tasks:

 

```
grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);
```

 

Task arguments can be specified as well. In this example, the alias "dist" runs both the "concat" and "uglify" tasks, each with a "dist" argument:

 

```
grunt.registerTask('dist', ['concat:dist', 'uglify:dist']);
```

 

## Multi Tasks

 

When a multi task is run, Grunt looks for a property of the same name in the Grunt configuration. Multi-tasks can have multiple configurations, defined using arbitrarily named "targets."

 

Specifying both a task and target like `grunt concat:foo` or `grunt concat:bar` will process just the specified target's configuration, while running `grunt concat` will iterate over *all* targets, processing each in turn. Note that if a task has been renamed with [grunt.task.renameTask](https://gruntjs.com/grunt.task#grunt.task.renametask), Grunt will look for a property with the *new* task name in the config object.

 

Most of the contrib tasks, including the [grunt-contrib-jshint plugin jshint task](https://github.com/gruntjs/grunt-contrib-jshint#jshint-task) and [grunt-contrib-concat plugin concat task](https://github.com/gruntjs/grunt-contrib-concat#concat-task) are multi tasks.

 

```
grunt.registerMultiTask(taskName, [description, ] taskFunction)
```

 

Given 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`.

 

```
grunt.initConfig({
  log: {
    foo: [1, 2, 3],
    bar: 'hello world',
    baz: false
  }
});

grunt.registerMultiTask('log', 'Log stuff.', function() {
  grunt.log.writeln(this.target + ': ' + this.data);
});
```

 

## "Basic" Tasks

 

When a basic task is run, Grunt doesn't look at the configuration or environment—it just runs the specified task function, passing any specified colon-separated arguments in as function arguments.

 

```
grunt.registerTask(taskName, [description, ] taskFunction)
```

 

This 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`.

 

```
grunt.registerTask('foo', 'A sample task that logs stuff.', function(arg1, arg2) {
  if (arguments.length === 0) {
    grunt.log.writeln(this.name + ", no args");
  } else {
    grunt.log.writeln(this.name + ", " + arg1 + " " + arg2);
  }
});
```

 

## Custom tasks

 

You can go crazy with tasks. If your tasks don't follow the "multi task" structure, use a custom task.

 

```
grunt.registerTask('default', 'My "default" task description.', function() {
  grunt.log.writeln('Currently running the "default" task.');
});
```

 

Inside a task, you can run other tasks.

 

```
grunt.registerTask('foo', 'My "foo" task.', function() {
  // Enqueue "bar" and "baz" tasks, to run after "foo" finishes, in-order.
  grunt.task.run('bar', 'baz');
  // Or:
  grunt.task.run(['bar', 'baz']);
});
```

 

Tasks can be asynchronous.

 

```
grunt.registerTask('asyncfoo', 'My "asyncfoo" task.', function() {
  // Force task into async mode and grab a handle to the "done" function.
  var done = this.async();
  // Run some sync stuff.
  grunt.log.writeln('Processing task...');
  // And some async stuff.
  setTimeout(function() {
    grunt.log.writeln('All done!');
    done();
  }, 1000);
});
```

 

Tasks can access their own name and arguments.

 

```
grunt.registerTask('foo', 'My "foo" task.', function(a, b) {
  grunt.log.writeln(this.name, a, b);
});

// Usage:
// grunt foo
//   logs: "foo", undefined, undefined
// grunt foo:bar
//   logs: "foo", "bar", undefined
// grunt foo:bar:baz
//   logs: "foo", "bar", "baz"
```

 

Tasks can fail if any errors were logged.

 

```
grunt.registerTask('foo', 'My "foo" task.', function() {
  if (failureOfSomeKind) {
    grunt.log.error('This is an error message.');
  }

  // Fail by returning false if this task had errors
  if (ifErrors) { return false; }

  grunt.log.writeln('This is the success message');
});
```

 

When tasks fail, all subsequent tasks will be aborted unless `--force` was specified.

 

```
grunt.registerTask('foo', 'My "foo" task.', function() {
  // Fail synchronously.
  return false;
});

grunt.registerTask('bar', 'My "bar" task.', function() {
  var done = this.async();
  setTimeout(function() {
    // Fail asynchronously.
    done(false);
  }, 1000);
});
```

 

Tasks can be dependent on the successful execution of other tasks. Note that `grunt.task.requires` won't actually RUN the other task(s). It'll just check to see that it has run and not failed.

 

```
grunt.registerTask('foo', 'My "foo" task.', function() {
  return false;
});

grunt.registerTask('bar', 'My "bar" task.', function() {
  // Fail task if "foo" task failed or never ran.
  grunt.task.requires('foo');
  // This code executes if the "foo" task ran successfully.
  grunt.log.writeln('Hello, world.');
});

// Usage:
// grunt foo bar
//   doesn't log, because foo failed.
//   ***Note: This is an example of space-separated sequential commands,
//   (similar to executing two lines of code: `grunt foo` then `grunt bar`)
// grunt bar
//   doesn't log, because foo never ran.
```

 

Tasks can fail if required configuration properties don't exist.

 

```
grunt.registerTask('foo', 'My "foo" task.', function() {
  // Fail task if "meta.name" config prop is missing
  // Format 1: String
  grunt.config.requires('meta.name');
  // or Format 2: Array
  grunt.config.requires(['meta', 'name']);
  // Log... conditionally.
  grunt.log.writeln('This will only log if meta.name is defined in the config.');
});
```

 

Tasks can access configuration properties.

 

```
grunt.registerTask('foo', 'My "foo" task.', function() {
  // Log the property value. Returns null if the property is undefined.
  grunt.log.writeln('The meta.name property is: ' + grunt.config('meta.name'));
  // Also logs the property value. Returns null if the property is undefined.
  grunt.log.writeln('The meta.name property is: ' + grunt.config(['meta', 'name']));
});
```

 

Take a look at the [contrib tasks](https://github.com/gruntjs/) for more examples.

 

## CLI options / environment

 

Use `process.env` to access the [environment variables](https://en.wikipedia.org/wiki/Environment_variable).

 

Read more about the available command-line options on the [Using the CLI](using-the-cli) page.

 

## Why doesn't my asynchronous task complete?

 

Chances are this is happening because you have forgotten to call the [this.async](api/inside-tasks#this.async) method to tell Grunt that your task is asynchronous. For simplicity's sake, Grunt uses a synchronous coding style, which can be switched to asynchronous by calling `this.async()` within the task body.

 

Note that passing `false` to the `done()` function tells Grunt that the task has failed.

 

For example:

 

```
grunt.registerTask('asyncme', 'My asynchronous task.', function() {
  var done = this.async();
  doSomethingAsync(done);
});
```

 

## Extra Reference

 

Checkout the [API](https://gruntjs.com/api) documentation if you need extra reference to create your tasks.

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/creating-tasks](https://gruntjs.com/creating-tasks)

---

## Section: configuring-tasks

# Configuring tasks

This guide explains how to configure tasks for your project using a `Gruntfile`. If you don't know what a `Gruntfile` is, please read the [Getting Started](https://gruntjs.com/getting-started/) guide and check out a [Sample Gruntfile](https://gruntjs.com/sample-gruntfile/).

 

## Grunt Configuration

 

Task configuration is specified in your `Gruntfile` via the `grunt.initConfig` method. This configuration will mostly be under task-named properties, but may contain any arbitrary data. As long as properties don't conflict with properties your tasks require, they will be otherwise ignored.

 

Also, because this is JavaScript, you're not limited to JSON; you may use any valid JavaScript here. You may even programmatically generate the configuration if necessary.

 

```
grunt.initConfig({
  concat: {
    // concat task configuration goes here.
  },
  uglify: {
    // uglify task configuration goes here.
  },
  // Arbitrary non-task-specific properties.
  my_property: 'whatever',
  my_src_files: ['foo/*.js', 'bar/*.js'],
});
```

 

## Task Configuration and Targets

 

When a task is run, Grunt looks for its configuration under a property of the same name. Multi-tasks can have multiple configurations, defined using arbitrarily named "targets." In the example below, the `concat` task has `foo` and `bar` targets, while the `uglify` task only has a `bar` target.

 

```
grunt.initConfig({
  concat: {
    foo: {
      // concat task "foo" target options and files go here.
    },
    bar: {
      // concat task "bar" target options and files go here.
    },
  },
  uglify: {
    bar: {
      // uglify task "bar" target options and files go here.
    },
  },
});
```

 

Specifying both a task and target like `grunt concat:foo` or `grunt concat:bar` will process just the specified target's configuration, while running `grunt concat` will iterate over *all* targets, processing each in turn. Note that if a task has been renamed with [grunt.task.renameTask](https://gruntjs.com/grunt.task#grunt.task.renametask), Grunt will look for a property with the *new* task name in the config object.

 

## Options

 

Inside a task configuration, an `options` property may be specified to override built-in defaults. In addition, each target may have an `options` property which is specific to that target. Target-level options will override task-level options.

 

The `options` object is optional and may be omitted if not needed.

 

```
grunt.initConfig({
  concat: {
    options: {
      // Task-level options may go here, overriding task defaults.
    },
    foo: {
      options: {
        // "foo" target options may go here, overriding task-level options.
      },
    },
    bar: {
      // No options specified; this target will use task-level options.
    },
  },
});
```

 

## Files

 

Because most tasks perform file operations, Grunt has powerful abstractions for declaring on which files the task should operate. There are several ways to define **src-dest** (source-destination) file mappings, offering varying degrees of verbosity and control. Any multi task will understand all the following formats, so choose whichever format best meets your needs.

 

All file formats support `src` and `dest` but the [Compact](configuring-tasks#compact-format) and [Files Array](configuring-tasks#files-array-format) formats support a few additional properties:

 
 - 
`filter` Either a valid [fs.Stats method name](https://nodejs.org/docs/latest/api/fs.html#fs_class_fs_stats) or a function that is passed the matched `src` filepath and returns `true` or `false`. [See examples](configuring-tasks#custom-filter-function)

 - 
`nonull` If set to `true` then the operation will include non-matching patterns. Combined with grunt's `--verbose` flag, this option can help debug file path issues.
 - 
`dot` Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot.
 - 
`matchBase` If set, patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
 - 
`expand` Process a dynamic src-dest file mapping, see ["Building the files object dynamically"](configuring-tasks#building-the-files-object-dynamically) for more information.
 - Other properties will be passed into the underlying libs as matching options. See the [node-glob](https://github.com/isaacs/node-glob) and [minimatch](https://github.com/isaacs/minimatch) documentation for more options.
 
 

### Difference Between Grunt and Task Options

 

Most tasks perform file operations, so Grunt provides a built-in infrastructure to retrieve the files a task should process. The advantage is that this logic doesn't have to be implemented again by tasks authors. To allow a user to specify these files, Grunt provides options such as `nonull` and `filter`.

 

In addition to the files to work on, each task has its own specific needs. A task author may want to allow its user to configure some options to override the default behavior. These task-specific options shall not be confused with the Grunt options described before.

 

To further clarify this difference, let's see an example that uses [grunt-contrib-jshint](https://github.com/gruntjs/grunt-contrib-jshint):

 

```
grunt.initConfig({
  jshint: {
    ignore_warning: {
      options: {
        '-W015': true,
      },
      src: 'js/**',
      filter: 'isFile'
    }
  }
});
```

 

This configuration employs the Grunt options `src` and `filter` to specify the files to process. It also uses the grunt-contrib-jshint task-specific option `-W015` to ignore a specific warning (the one having code `W015`).

 

### Compact Format

 

This form allows a single **src-dest** (source-destination) file mapping per-target. It is most commonly used for read-only tasks, like [grunt-contrib-jshint](https://github.com/gruntjs/grunt-contrib-jshint), where a single `src` property is needed, and no `dest` key is relevant. This format also supports additional properties per src-dest file mapping.

 

```
grunt.initConfig({
  jshint: {
    foo: {
      src: ['src/aa.js', 'src/aaa.js']
    },
  },
  concat: {
    bar: {
      src: ['src/bb.js', 'src/bbb.js'],
      dest: 'dest/b.js',
    },
  },
});
```

 

### Files Object Format

 

This form supports multiple src-dest mappings per-target, where the property name is the destination file, and its value is the source file(s). Any number of src-dest file mappings may be specified in this way, but additional properties may not be specified per mapping.

 

```
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'],
      },
    },
  },
});
```

 

### Files Array Format

 

This form supports multiple src-dest file mappings per-target, while also allowing additional properties per mapping.

 

```
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: ['src/bb.js', 'src/bbb.js'], dest: 'dest/b/', nonull: true},
        {src: ['src/bb1.js', 'src/bbb1.js'], dest: 'dest/b1/', filter: 'isFile'},
      ],
    },
  },
});
```

 

### Older Formats

 

The **dest-as-target** file format is a holdover from before multi tasks and targets existed, where the destination filepath is actually the target name. Unfortunately, because target names are filepaths, running `grunt task:target` can be awkward. Also, you can't specify target-level options or additional properties per src-dest file mapping.

 

Consider this format deprecated, and avoid it where possible.

 

```
grunt.initConfig({
  concat: {
    'dest/a.js': ['src/aa.js', 'src/aaa.js'],
    'dest/b.js': ['src/bb.js', 'src/bbb.js'],
  },
});
```

 

### Custom Filter Function

 

The `filter` property can help you target files with a greater level of detail. Simply use a valid [fs.Stats method name](https://nodejs.org/docs/latest/api/fs.html#fs_class_fs_stats). The following will clean only if the pattern matches an actual file:

 

```
grunt.initConfig({
  clean: {
    foo: {
      src: ['tmp/**/*'],
      filter: 'isFile',
    },
  },
});
```

 

Or create your own `filter` function and return `true` or `false` whether the file should be matched. For example the following will only clean folders that are empty:

 

```
grunt.initConfig({
  clean: {
    foo: {
      src: ['tmp/**/*'],
      filter: function(filepath) {
        return (grunt.file.isDir(filepath) && require('fs').readdirSync(filepath).length === 0);
      },
    },
  },
});
```

 

Another example—which utilizes the [globbing](configuring-tasks#globbing-patterns) and [expand: true](configuring-tasks#building-the-files-object-dynamically) features—allows you to avoid overwriting files which already exist in the destination:

 

```
grunt.initConfig({
  copy: {
    templates: {
      files: [{
        expand: true,
        cwd: ['templates/css/'],     // Parent folder of original CSS templates
        src: '**/*.css',             // Collects all `*.css` files within the parent folder (and its subfolders)
        dest: 'src/css/',            // Stores the collected `*.css` files in your `src/css/` folder
        filter: function (dest) {    // `dest`, in this instance, is the filepath of each matched `src`
          var cwd = this.cwd,        // Configures variables (these are documented for your convenience only)
              src = dest.replace(new RegExp('^' + cwd), '');
              dest = grunt.task.current.data.files[0].dest;
          return (!grunt.file.exists(dest + src));    // Copies `src` files ONLY if their destinations are unoccupied
        }
      }]
    }
  }
});
```

 

Keep in mind the above technique does not account for the [rename property](configuring-tasks#building-the-files-object-dynamically) when checking if the destination exists.

 

### Globbing patterns

 

It is often impractical to specify all source filepaths individually, so Grunt supports filename expansion (also known as globbing) via the built-in [node-glob](https://github.com/isaacs/node-glob) and [minimatch](https://github.com/isaacs/minimatch) libraries.

 

While this isn't a comprehensive tutorial on globbing patterns, know that in a filepath:

 
 - 
`*` matches any number of characters, but not `/`

 - 
`?` matches a single character, but not `/`

 - 
`**` matches any number of characters, including `/`, as long as it's the only thing in a path part
 - 
`{}` allows for a comma-separated list of "or" expressions
 - 
`!` at the beginning of a pattern will negate the match
 
 

All most people need to know is that `foo/*.js` will match all files ending with `.js` in the `foo/` subdirectory, but `foo/**/*.js` will match all files ending with `.js` in the `foo/` subdirectory *and all of its subdirectories*.

 

Also, in order to simplify otherwise complicated globbing patterns, Grunt allows arrays of file paths or globbing patterns to be specified. Patterns are processed in-order, with `!`-prefixed matches excluding matched files from the result set. The result set is uniqued.

 

For example:

 

```
// You can specify single files:
{src: 'foo/this.js', dest: ...}
// Or arrays of files:
{src: ['foo/this.js', 'foo/that.js', 'foo/the-other.js'], dest: ...}
// Or you can generalize with a glob pattern:
{src: 'foo/th*.js', dest: ...}

// This single node-glob pattern:
{src: 'foo/{a,b}*.js', dest: ...}
// Could also be written like this:
{src: ['foo/a*.js', 'foo/b*.js'], dest: ...}

// All .js files, in foo/, in alpha order:
{src: ['foo/*.js'], dest: ...}
// Here, bar.js is first, followed by the remaining files, in alpha order:
{src: ['foo/bar.js', 'foo/*.js'], dest: ...}

// All files except for bar.js, in alpha order:
{src: ['foo/*.js', '!foo/bar.js'], dest: ...}
// All files in alpha order, but with bar.js at the end.
{src: ['foo/*.js', '!foo/bar.js', 'foo/bar.js'], dest: ...}

// Templates may be used in filepaths or glob patterns:
{src: ['src/<%= basename %>.js'], dest: 'build/<%= basename %>.min.js'}
// But they may also reference file lists defined elsewhere in the config:
{src: ['foo/*.js', '<%= jshint.all.src %>'], dest: ...}
```

 

For more on glob pattern syntax, see the [node-glob](https://github.com/isaacs/node-glob) and [minimatch](https://github.com/isaacs/minimatch) documentation.

 

### Building the files object dynamically

 

When you want to process many individual files, a few additional properties may be used to build a files list dynamically. These properties may be specified in both [Compact](configuring-tasks#compact-format) and [Files Array](configuring-tasks#files-array-format) mapping formats.

 

`expand` Set to `true` will enable the following properties:

 
 - 
`cwd` All `src` matches are relative to (but don't include) this path.
 - 
`src` Pattern(s) to match, relative to the `cwd`.
 - 
`dest` Destination path prefix.
 - 
`ext` Replace any existing extension with this value in generated `dest` paths.
 - 
`extDot` Used to indicate where the period indicating the extension is located. Can take either `'first'` (extension begins after the first period in the file name) or `'last'` (extension begins after the last period), and is set by default to `'first'` *[Added in 0.4.3]*

 - 
`flatten` Remove all path parts from generated `dest` paths.
 - 
`rename` Embeds a customized function, which returns a string containing the new destination and filename. This function is called for each matched `src` file (after extension renaming and flattening). [More information](configuring-tasks#the-rename-property)

 
 

In the following example, the `uglify` task will see the same list of src-dest file mappings for both the `static_mappings` and `dynamic_mappings` targets, because Grunt will automatically expand the `dynamic_mappings` files object into 4 individual static src-dest file mappings—assuming 4 files are found—when the task runs.

 

Any combination of static src-dest and dynamic src-dest file mappings may be specified.

 

```
grunt.initConfig({
  uglify: {
    static_mappings: {
      // Because these src-dest file mappings are manually specified, every
      // time a new file is added or removed, the Gruntfile has 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 will search for "**/*.js" under "lib/" when the "uglify" task
      // runs and build the appropriate src-dest file mappings then, so you
      // don't need to update the Gruntfile when files are added or removed.
      files: [
        {
          expand: true,     // Enable dynamic expansion.
          cwd: 'lib/',      // Src matches are relative to this path.
          src: ['**/*.js'], // Actual pattern(s) to match.
          dest: 'build/',   // Destination path prefix.
          ext: '.min.js',   // Dest filepaths will have this extension.
          extDot: 'first'   // Extensions in filenames begin after the first dot
        },
      ],
    },
  },
});
```

 

#### The rename Property

 

The `rename` property is unique, as the only valid value for it is a JavaScript function. Although the function returns a string, you cannot simply use a string as a value for `rename` (doing so results in an error: `Property 'rename' of object # is not a function`). In the following example, the `copy` task will create a backup of README.md.

 

```
grunt.initConfig({
  copy: {
    backup: {
      files: [{
        expand: true,
        src: ['docs/README.md'],    // The README.md file has been specified for backup
        rename: function () {       // The value for rename must be a function
          return 'docs/BACKUP.txt'; // The function must return a string with the complete destination
        }
      }]
    }
  }
});
```

 

When the function is called, the `dest` and matched `src` path are passed in and can be used for returning the output string. In the following example, files are copied from the `dev` folder to the `dist` folder, and renamed to have the word "beta" removed .

 

```
grunt.initConfig({
  copy: {
    production: {
      files: [{
        expand: true,
        cwd: 'dev/',
        src: ['*'],
        dest: 'dist/',
        rename: function (dest, src) {          // The `dest` and `src` values can be passed into the function
          return dest + src.replace('beta',''); // The `src` is being renamed; the `dest` remains the same
        }
      }]
    }
  }
});
```

 

If multiple matched `src` paths are renamed to an identical destination (i.e. if two different files get renamed to the same file), each output will be added to an array of sources for it.

 

## Templates

 

Templates specified using `<% %>` delimiters will be automatically expanded when tasks read them from the config. Templates are expanded recursively until no more remain.

 

The entire config object is the context in which properties are resolved. Additionally, `grunt` and its methods are available inside templates, eg. `<%= grunt.template.today('yyyy-mm-dd') %>`.

 
 - 
`<%= prop.subprop %>` Expand to the value of `prop.subprop` in the config, regardless of type. Templates like this can be used to reference not only string values, but also arrays or other objects.
 - 
`<% %>` Execute arbitrary inline JavaScript code. This is useful with control flow or looping.
 
 

Given the sample `concat` task configuration below, running `grunt concat:sample` will generate a file named `build/abcde.js` by concatenating the banner `/* abcde */` with all files matching `foo/*.js` + `bar/*.js` + `baz/*.js`.

 

```
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'
    },
  },
  // Arbitrary properties used in task configuration templates.
  foo: 'c',
  bar: 'b<%= foo %>d', // 'bcd'
  baz: 'a<%= bar %>e', // 'abcde'
  qux: ['foo/*.js', 'bar/*.js'],
});
```

 

## Importing External Data

 

In the following Gruntfile, project metadata is imported into the Grunt config from a `package.json` file, and the [grunt-contrib-uglify plugin](https://github.com/gruntjs/grunt-contrib-uglify) `uglify` task is configured to minify a source file and generate a banner comment dynamically using that metadata.

 

Grunt has `grunt.file.readJSON` and `grunt.file.readYAML` methods for importing JSON and YAML data.

 

```
grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  uglify: {
    options: {
      banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
    },
    dist: {
      src: 'src/<%= pkg.name %>.js',
      dest: 'dist/<%= pkg.name %>.min.js'
    }
  }
});
```

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/configuring-tasks](https://gruntjs.com/configuring-tasks)

---

## Section: api/grunt.config

# grunt.config

Access project-specific configuration data defined in the `Gruntfile`.

 

Note that any method marked with a ☃ (unicode snowman) is also available directly on the `grunt` object, and any method marked with a ☆ (white star) is also available inside tasks on the `this` object. Just so you know.

 

## Initializing Config Data

 

*Note that the following method is also available on the `grunt` object as `grunt.initConfig`.*

 

### grunt.config.init ☃

 

Initialize a configuration object for the current project. The specified `configObject` is used by tasks and can be accessed using the `grunt.config` method. Nearly every project's `Gruntfile` will call this method.

 

```
grunt.config.init(configObject)
```

 

Note that any specified `<% %>` template strings will be processed when config data is retrieved.

 

This example contains sample config data for the [grunt-contrib-jshint plugin](https://github.com/gruntjs/grunt-contrib-jshint) `jshint` task:

 

```
grunt.config.init({
  jshint: {
    all: ['lib/*.js', 'test/*.js', 'Gruntfile.js']
  }
});
```

 

See the [Getting started](https://gruntjs.com/getting-started/) guide for more configuration examples.

 

*This method is also available as `grunt.initConfig`.*

 

## Accessing Config Data

 

The following methods allow Grunt configuration data to be accessed either via dot-delimited string like `'pkg.author.name'` or via array of property name parts like `['pkg', 'author', 'name']`.

 

Note that if a specified property name contains a `.` dot, it must be escaped with a literal backslash, eg. `'concat.dist/built\\.js'`. If an array of parts is specified, Grunt will handle the escaping internally with the `grunt.config.escape` method.

 

### grunt.config

 

Get or set a value from the project's Grunt configuration. This method serves as an alias to other methods; if two arguments are passed, `grunt.config.set` is called, otherwise `grunt.config.get` is called.

 

```
grunt.config([prop [, value]])
```

 

### grunt.config.get

 

Get a value from the project's Grunt configuration. If `prop` is specified, that property's value is returned, or `null` if that property is not defined. If `prop` isn't specified, a copy of the entire config object is returned. Templates strings will be recursively processed using the `grunt.config.process` method.

 

```
grunt.config.get([prop])
```

 

### grunt.config.process

 

Process a value, recursively expanding `<% %>` templates (via the `grunt.template.process` method) in the context of the Grunt config, as they are encountered. this method is called automatically by `grunt.config.get` but *not* by `grunt.config.getRaw`.

 

```
grunt.config.process(value)
```

 

If any retrieved value is entirely a single `'<%= foo %>'` or `'<%= foo.bar %>'` template string, and the specified `foo` or `foo.bar` property is a non-string (and not `null` or `undefined`) value, it will be expanded to the *actual* value. That, combined with grunt's task system automatically flattening arrays, can be extremely useful.

 

### grunt.config.getRaw

 

Get a raw value from the project's Grunt configuration, without processing `<% %>` template strings. If `prop` is specified, that property's value is returned, or `null` if that property is not defined. If `prop` isn't specified, a copy of the entire config object is returned.

 

```
grunt.config.getRaw([prop])
```

 

### grunt.config.set

 

Set a value into the project's Grunt configuration.

 

```
grunt.config.set(prop, value)
```

 

Note that any specified `<% %>` template strings will only be processed when config data is retrieved.

 

### grunt.config.escape

 

Escape `.` dots in the given `propString`. This should be used for property names that contain dots.

 

```
grunt.config.escape(propString)
```

 

### grunt.config.merge

 

*Added in 0.4.5*

 

Recursively merges properties of the specified `configObject` into the current project configuration. Array and plain object properties are merged recursively while other value types are overridden.

 

```
grunt.config.merge(configObject)
```

 

You can use this method to append configuration options, targets, etc., to already defined tasks, for example:

 

```
grunt.config.merge({
  watch: {
    files: ["path/to/files"],
    tasks: ["task"]
  }
});
```

 

Array values are merged based on their index. Consider the following code:

 

```
grunt.initConfig({
  jshint: {
    files: ['Gruntfile.js', 'src/**/*.js'],
  }
);

var config = {
  jshint: {
    files: ['hello.js'],
  }
};

grunt.config.merge(config);
```

 

It'll result in the configuration shown below:

 

```
jshint: {
  files: ['hello.js', 'src/**/*.js'],
}
```

 

In conclusion, the first value of the `files` array defined in the `config` variable (`hello.js`) overriddes the first value specified in the `initConfig` configuration call (`Gruntfile.js`).

 

## Requiring Config Data

 

*Note that the method listed below is also available inside tasks on the `this` object as `this.requiresConfig`.*

 

### grunt.config.requires ☆

 

Fail the current task if one or more required config properties is missing, `null` or `undefined`. One or more string or array config properties may be specified.

 

```
grunt.config.requires(prop [, prop [, ...]])
```

 

*This method is also available inside tasks as `this.requiresConfig`.*

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.config](https://gruntjs.com/api/grunt.config)

---

## Section: api/grunt.fail

# grunt.fail

For when something goes horribly wrong.

 

See the [fail lib source](https://github.com/gruntjs/grunt/blob/master/lib/grunt/fail.js) for more information.

 

## The fail API

 

If something explodes (or is about to explode) inside a task, it can force Grunt to abort. See the [exit codes documentation](https://gruntjs.com/exit-codes) for a list of all built-in Grunt exit codes.

 

Note 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](https://gruntjs.com/grunt) for more usage information.

 

### grunt.fail.warn ☃

 

Display a warning and abort Grunt immediately. Grunt will continue processing tasks if the `--force` command-line option was specified. The `error` argument can be a string message or an error object.

 

```
grunt.fail.warn(error [, errorcode])
```

 

If `--stack` is specified on the command-line and an error object was specified, a stack trace will be logged.

 

*This method is also available as `grunt.warn`.*

 

### grunt.fail.fatal ☃

 

Display a warning and abort Grunt immediately. The `error` argument can be a string message or an error object.

 

```
grunt.fail.fatal(error [, errorcode])
```

 

If `--stack` is specified on the command-line and an error object was specified, a stack trace will be logged.

 

A beep is emitted on fatal unless the `--no-color` option is specified.

 

*This method is also available as `grunt.fatal`.*

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.fail](https://gruntjs.com/api/grunt.fail)

---

## Section: api/grunt.file

# grunt.file

There are many provided methods for reading and writing files, traversing the filesystem and finding files by matching globbing patterns. Many of these methods are wrappers around built-in Node.js file functionality, but with additional error handling, logging and character encoding normalization.

 

*Note: all file paths are relative to the `Gruntfile` unless the current working directory is changed with `grunt.file.setBase` or the `--base` command-line option.*

 

## Character encoding

 

### grunt.file.defaultEncoding

 

Set this property to change the default encoding used by all `grunt.file` methods. Defaults to `'utf8'`. If you do have to change this value, it's recommended that you change it as early as possible inside your Gruntfile.

 

```
grunt.file.defaultEncoding = 'utf8';
```

 

### grunt.file.preserveBOM

 

*Added in 0.4.2*

 

Whether to preserve the Byte Order Mark (BOM) on `file.read` rather than strip it.

 

```
grunt.file.preserveBOM = false;
```

 

## Reading and writing

 

### grunt.file.read

 

Read and return a file's contents. Returns a string, unless `options.encoding` is `null` in which case it returns a [Buffer](https://nodejs.org/docs/latest/api/buffer.html).

 

```
grunt.file.read(filepath [, options])
```

 

The `options` object has these possible properties:

 

```
var options = {
  // If an encoding is not specified, default to grunt.file.defaultEncoding.
  // If specified as null, returns a non-decoded Buffer instead of a string.
  encoding: encodingName
};
```

 

### grunt.file.readJSON

 

Read a file's contents, parsing the data as JSON and returning the result. See `grunt.file.read` for a list of supported options.

 

```
grunt.file.readJSON(filepath [, options])
```

 

### grunt.file.readYAML

 

Read a file's contents, parsing the data as YAML and returning the result. See `grunt.file.read` for a list of supported options.

 

```
grunt.file.readYAML(filepath [, options])
```

 

### grunt.file.write

 

Write the specified contents to a file, creating intermediate directories if necessary. Strings will be encoded using the specified character encoding, [Buffers](https://nodejs.org/docs/latest/api/buffer.html) will be written to disk as-specified.

 

*If the `--no-write` command-line option is specified, the file won't actually be written.*

 

```
grunt.file.write(filepath, contents [, options])
```

 

The `options` object has these possible properties:

 

```
var options = {
  // If an encoding is not specified, default to grunt.file.defaultEncoding.
  // If `contents` is a Buffer, encoding is ignored.
  encoding: encodingName
};
```

 

### grunt.file.copy

 

Copy a source file to a destination path, creating intermediate directories if necessary.

 

*If the `--no-write` command-line option is specified, the file won't actually be written.*

 

```
grunt.file.copy(srcpath, destpath [, options])
```

 

The `options` object has these possible properties:

 

```
var options = {
  // If an encoding is not specified, default to grunt.file.defaultEncoding.
  // If null, the `process` function will receive a Buffer instead of String.
  encoding: encodingName,
  // The source file contents, source file path, and destination file path
  // are passed into this function, whose return value will be used as the
  // destination file's contents. If this function returns `false`, the file
  // copy will be aborted.
  process: processFunction,
  // These optional globbing patterns will be matched against the filepath
  // (not the filename) using grunt.file.isMatch. If any specified globbing
  // pattern matches, the file won't be processed via the `process` function.
  // If `true` is specified, processing will be prevented.
  noProcess: globbingPatterns
};
```

 

### grunt.file.delete

 

Delete the specified filepath. Will delete files and folders recursively.

 

*Will not delete the current working directory or files outside the current working directory unless the `--force` command-line option is specified.*

 

*If the `--no-write` command-line option is specified, the filepath won't actually be deleted.*

 

```
grunt.file.delete(filepath [, options])
```

 

The `options` object has one possible property:

 

```
var options = {
  // Enable deleting outside the current working directory. This option may
  // be overridden by the --force command-line option.
  force: true
};
```

 

## Directories

 

### grunt.file.mkdir

 

Works like `mkdir -p`. Create a directory along with any intermediate directories. If `mode` isn't specified, it defaults to `0777 & (~process.umask())`.

 

*If the `--no-write` command-line option is specified, directories won't actually be created.*

 

```
grunt.file.mkdir(dirpath [, mode])
```

 

### grunt.file.recurse

 

Recurse into a directory, executing `callback` for each file.

 

```
grunt.file.recurse(rootdir, callback)
```

 

The callback function receives the following arguments:

 

```
function callback(abspath, rootdir, subdir, filename) {
  // The full path to the current file, which is nothing more than
  // the rootdir + subdir + filename arguments, joined.
  abspath
  // The root director, as originally specified.
  rootdir
  // The current file's directory, relative to rootdir.
  subdir
  // The filename of the current file, without any directory parts.
  filename
}
```

 

## Globbing patterns

 

It is often impractical to specify all source filepaths individually, so Grunt supports filename expansion (also know as globbing) via the built-in [node-glob](https://github.com/isaacs/node-glob) library.

 

See the "Globbing patterns" section of the [Configuring tasks](https://gruntjs.com/configuring-tasks/) guide for globbing pattern examples.

 

### grunt.file.expand

 

Return a unique array of all file or directory paths that match the given globbing pattern(s). This method accepts either comma separated globbing patterns or an array of globbing patterns. Paths matching patterns that begin with `!` will be excluded from the returned array. Patterns are processed in order, so inclusion and exclusion order is significant.

 

```
grunt.file.expand([options, ] patterns)
```

 

File paths are relative to the `Gruntfile` unless the current working directory is changed with `grunt.file.setBase` or the `--base` command-line option.

 

The `options` object supports all [minimatch library](https://github.com/isaacs/minimatch) options, and a few others. For example:

 
 - 
`filter` Either a valid [fs.Stats method name](https://nodejs.org/docs/latest/api/fs.html#fs_class_fs_stats) or a function that is passed the matched `src` filepath and returns `true` or `false`.
 - 
`nonull` Retain `src` patterns even if they fail to match files. Combined with grunt's `--verbose` flag, this option can help debug file path issues.
 - 
`matchBase` Patterns without slashes will match just the basename part. Eg. this makes `*.js` work like `**/*.js`.
 - 
`cwd` Patterns will be matched relative to this path, and all returned filepaths will also be relative to this path.
 
 

### grunt.file.expandMapping

 

Returns an array of src-dest file mapping objects. For each source file matched by a specified pattern, join that file path to the specified `dest`. This file path may be flattened or renamed, depending on the options specified. See the `grunt.file.expand` method documentation for an explanation of how the `patterns` and `options` arguments may be specified.

 

```
grunt.file.expandMapping(patterns, dest [, options])
```

 

*Note that while this method may be used to programmatically generate a `files` array for a multi task, the declarative syntax for doing this described in the "Building the files object dynamically" section of the [Configuring tasks](https://gruntjs.com/configuring-tasks/) guide is preferred.*

 

In addition to those the `grunt.file.expand` method supports, the `options` object also supports these properties:

 

```
var options = {
  // The directory from which patterns are matched. Any string specified as
  // cwd is effectively stripped from the beginning of all matched paths.
  cwd: String,
  // Remove the path component from all matched src files. The src file path
  // is still joined to the specified dest.
  flatten: Boolean,
  // Remove anything after (and including) either the first or last "." in the
  // destination path (indicated by options.extDot), then append this value.
  ext: String,
  // *Added in 0.4.3*
  // Indicates where the period demarcating the extension is located. Can take:
  // - 'first' (extension begins after the first period in the file name)
  // - 'last' (extension begins after the last period)
  // Default: 'first'
  extDot: String,
  // If specified, this function will be responsible for returning the final
  // dest filepath. By default, it joins dest and matchedSrcPath like so:
  rename: function(dest, matchedSrcPath, options) {
    return path.join(dest, matchedSrcPath);
  }
};
```

 

### grunt.file.match

 

Match one or more globbing patterns against one or more file paths. Returns a uniqued array of all file paths that match any of the specified globbing patterns. Both the `patterns` and `filepaths` argument can be a single string or array of strings. Paths matching patterns that begin with `!` will be excluded from the returned array. Patterns are processed in order, so inclusion and exclusion order is significant.

 

```
grunt.file.match([options, ] patterns, filepaths)
```

 

The `options` object supports all [minimatch library](https://github.com/isaacs/minimatch) options. For example, if `options.matchBase` is true, patterns without slashes will match against the basename of the path even if it contains slashes, eg. pattern `*.js` will match filepath `path/to/file.js`.

 

### grunt.file.isMatch

 

This method contains the same signature and logic as the `grunt.file.match` method, but simply returns `true` if any files were matched, otherwise `false`.

 

## File types

 

### grunt.file.exists

 

Does the given path exist? Returns a boolean.

 

Like the Node.js [path.join](https://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.

 

```
grunt.file.exists(path1 [, path2 [, ...]])
```

 

### grunt.file.isLink

 

Is the given path a symbolic link? Returns a boolean.

 

Like the Node.js [path.join](https://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.

 

```
grunt.file.isLink(path1 [, path2 [, ...]])
```

 

Returns false if the path doesn't exist.

 

### grunt.file.isDir

 

Is the given path a directory? Returns a boolean.

 

Like the Node.js [path.join](https://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.

 

```
grunt.file.isDir(path1 [, path2 [, ...]])
```

 

Returns false if the path doesn't exist.

 

### grunt.file.isFile

 

Is the given path a file? Returns a boolean.

 

Like the Node.js [path.join](https://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.

 

```
grunt.file.isFile(path1 [, path2 [, ...]])
```

 

Returns false if the path doesn't exist.

 

## Paths

 

### grunt.file.isPathAbsolute

 

Is a given file path absolute? Returns a boolean.

 

Like the Node.js [path.join](https://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.

 

```
grunt.file.isPathAbsolute(path1 [, path2 [, ...]])
```

 

### grunt.file.arePathsEquivalent

 

Do all the specified paths refer to the same path? Returns a boolean.

 

```
grunt.file.arePathsEquivalent(path1 [, path2 [, ...]])
```

 

### grunt.file.doesPathContain

 

Are all descendant path(s) contained within the specified ancestor path? Returns a boolean.

 

*Note: does not check to see if paths actually exist.*

 

```
grunt.file.doesPathContain(ancestorPath, descendantPath1 [, descendantPath2 [, ...]])
```

 

### grunt.file.isPathCwd

 

Is a given file path the CWD? Returns a boolean.

 

Like the Node.js [path.join](https://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.

 

```
grunt.file.isPathCwd(path1 [, path2 [, ...]])
```

 

### grunt.file.isPathInCwd

 

Is a given file path inside the CWD? Note: CWD is not *inside* CWD. Returns a boolean.

 

Like the Node.js [path.join](https://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.

 

```
grunt.file.isPathInCwd(path1 [, path2 [, ...]])
```

 

### grunt.file.setBase

 

Change grunt's current working directory (CWD). By default, all file paths are relative to the `Gruntfile`. This works just like the `--base` command-line option.

 

```
grunt.file.setBase(path1 [, path2 [, ...]])
```

 

Like the Node.js [path.join](https://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.

 

## External libraries

 

*Deprecated*

 

**All external libraries that are listed below are now deprecated.**

 

Please use **npm** to manage these external libraries in your project's dependencies.

 

For example if you want use [Lo-Dash](https://www.npmjs.org/package/lodash), install it first `npm install lodash`, then use it in your `Gruntfile`: `var _ = require('lodash');`

 

### grunt.file.glob

 

*Deprecated*

 

[glob](https://github.com/isaacs/node-glob) - File globbing utility.

 

### grunt.file.minimatch

 

*Deprecated*

 

[minimatch](https://github.com/isaacs/minimatch) - File pattern matching utility.

 

### grunt.file.findup

 

*Deprecated*

 

[findup-sync](https://github.com/cowboy/node-findup-sync) - Search upwards for matching file patterns.

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.file](https://gruntjs.com/api/grunt.file)

---

## Section: upgrading-from-0.3-to-0.4

# Upgrading from 0.3 to 0.4

*Note that even if you are familiar with grunt, it would be worthwhile to read the new [Getting started](https://gruntjs.com/getting-started/) guide.*

 

Grunt is now split into three parts: `grunt`, `grunt-cli` and `grunt-init`.

 
 - The npm module `grunt` should be installed locally to your project. It contains the code and logic for running tasks, loading plugins, etc.
 - The npm module `grunt-cli` should be installed globally. It puts the `grunt` command in your PATH so you can execute it anywhere. By itself, it doesn't do anything; its job is to load and run the Grunt that has been installed locally to your project, regardless of the version. For more information about why this has changed, please read [npm 1.0: Global vs Local installation](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation).
 - The `init` task has been broken into its own npm module, `grunt-init`. It should be installed globally with `npm install grunt-init` and run with the `grunt-init` command. In the coming months, [Yeoman](http://yeoman.io/) will completely replace grunt-init. See the [grunt-init project page](https://github.com/gruntjs/grunt-init) for more information.
 
 

## Grunt 0.3 Notes

 

If you are upgrading from Grunt 0.3, make sure to uninstall global `grunt`:

 

```
npm uninstall -g grunt
```

 

*Note that for 0.3.x, plugin names and task configuration options may be different than those shown in "The Gruntfile" section.*

 

*This file was named `grunt.js` for 0.3.x versions of Grunt.*

 

## Pre-existing tasks and plugins

 

All `grunt-contrib-*` series plugins are Grunt 0.4 ready. However, it is highly unlikely that third party plugins written for Grunt 0.3 will continue to work with 0.4 until they have been updated. We are actively working with plugin authors to ensure this happens as swiftly as possible.

 

*A forthcoming Grunt release will be focused on decoupling grunt's architecture so that plugins are not affected by future updates.*

 

## Requirements

 
 - Grunt now requires Node.js version `>= 0.8.0`

 
 

## The Gruntfile

 
 - The "Gruntfile" has changed from `grunt.js` to `Gruntfile.js`.
 - CoffeeScript is supported in your `Gruntfile.coffee` project `Gruntfile` or `*.coffee` task files (transpiling to JS happens automatically).
 
 

See the "The Gruntfile" section of the [Getting started](https://gruntjs.com/getting-started/) guide for more information.

 

## Core Tasks are now Grunt Plugins

 

The eight core tasks that were included in Grunt 0.3 are now separate Grunt plugins. Each is a discrete npm module that must be installed as a plugin per the "Loading Grunt plugins and tasks" section of the [Getting started](https://gruntjs.com/getting-started/) guide.

 
 - concat → [grunt-contrib-concat](https://github.com/gruntjs/grunt-contrib-concat) plugin
 - init → stand-alone [grunt-init](https://github.com/gruntjs/grunt-init) utility
 - lint → [grunt-contrib-jshint](https://github.com/gruntjs/grunt-contrib-jshint) plugin
 - min → [grunt-contrib-uglify](https://github.com/gruntjs/grunt-contrib-uglify) plugin
 - qunit → [grunt-contrib-qunit](https://github.com/gruntjs/grunt-contrib-qunit) plugin
 - server → [grunt-contrib-connect](https://github.com/gruntjs/grunt-contrib-connect) plugin
 - test → [grunt-contrib-nodeunit](https://github.com/gruntjs/grunt-contrib-nodeunit) plugin
 - watch → [grunt-contrib-watch](https://github.com/gruntjs/grunt-contrib-watch) plugin
 
 

Some task names and options have changed. Be sure to see each plugin's documentation as linked above for the latest configuration details.

 

## Configuration

 

The configuration format for Grunt 0.4 tasks has been standardized and greatly enhanced. See the [Configuring tasks](https://gruntjs.com/configuring-tasks/) guide, as well as individual plugin documentation for more information.

 
 - File globbing (wildcard) patterns may now be negated to exclude matched files.
 - Tasks now support a standard `options` object.
 - Tasks now support a standard `files` object.
 
 

`<% %>` style template strings specified as config data inside the `Gruntfile` are automatically expanded, see the [grunt.template](https://gruntjs.com/grunt.template/) documentation for more information.

 

**Directives have been removed**, but their functionality has been retained. These replacements can be made:

 
 - 
`''` → `'<%= prop.subprop %>'`

 - 
`''` → `grunt.file.readJSON('file.json')`

 - 
`''` → `grunt.template.process(grunt.file.read('file.js'))`

 
 

Instead of specifying a banner in a file list with `''` or `''`, the [grunt-contrib-concat](https://github.com/gruntjs/grunt-contrib-concat) and [grunt-contrib-uglify](https://github.com/gruntjs/grunt-contrib-uglify) plugins each have a `banner` option.

 

Instead of stripping banners from files individually with `''`, the [grunt-contrib-concat](https://github.com/gruntjs/grunt-contrib-concat) and [grunt-contrib-uglify](https://github.com/gruntjs/grunt-contrib-uglify) plugins each have an option to strip/preserve banners.

 

## Alias task changes

 

When specifying an alias task, the list of tasks to run must now be specified as an array.

 

```
// v0.3.x (old format)
grunt.registerTask('default', 'jshint nodeunit concat');
// v0.4.x (new format)
grunt.registerTask('default', ['jshint', 'nodeunit', 'concat']);
```

 

## Task arguments may now contain spaces

 

The aforementioned alias task change (task lists must be specified as an array) makes this possible. Just be sure to surround task arguments containing spaces with quotes when specifying them on the command line, so they can be properly parsed.

 

```
grunt my-task:argument-without-spaces "other-task:argument with spaces"
```

 

## Character encodings

 

The [file.defaultEncoding](https://gruntjs.com/grunt.file#wiki-grunt-file-defaultencoding) method was added to normalize character encodings, and all `grunt.file` methods have been updated to support the specified encoding.

 

## Helpers

 

Grunt's helper system has been removed in favor of node `require`. For a concise example on how to share functionality between Grunt plugins, please see [grunt-lib-legacyhelpers](https://github.com/gruntjs/grunt-lib-legacyhelpers). Plugin authors are encouraged to upgrade their plugins.

 

## API

 

The Grunt API saw substantial changes from 0.3 to 0.4.

 
 - 
[grunt](https://gruntjs.com/grunt)
 Removed `grunt.registerHelper` and `grunt.renameHelper` methods.
 
  - 
[grunt.config](https://gruntjs.com/grunt.config)
 Changed [config.get](https://gruntjs.com/grunt.config#wiki-grunt-config-get) method to automatically recursively expand `<% %>` templates.
 - Added [config.getRaw](https://gruntjs.com/grunt.config#wiki-grunt-config-getraw) method that will retrieve raw (unexpanded) config data.
 - Changed [config.process](https://gruntjs.com/grunt.config#wiki-grunt-config-process) method to now process a value as if it had been retrieved from the config, expanding templates recursively. This method is called internally inside of `config.get`, but *not* inside of `config.getRaw`.
 
  - 
[grunt.event](https://gruntjs.com/grunt.event) added so that tasks may emit events.
 - 
[grunt.fail](https://gruntjs.com/grunt.fail)
 Won't emit a beep if `--no-color` option specified.
 - Added `fail.code` exit code map.
 - Removed `fail.warnAlternate` method.
 
  - 
[grunt.file](https://gruntjs.com/grunt.file)
 Tasks are no longer automatically loaded from `~/.grunt/tasks/` directory (install them locally to your project!).
 - Added [file.defaultEncoding](https://gruntjs.com/grunt.file#wiki-grunt-file-defaultencoding) method for normalizing character encoding across all `grunt.file` methods.
 - Added [file.delete](https://gruntjs.com/grunt.file#wiki-grunt-file-delete) method.
 - Added relatively self-explanatory [file.exists](https://gruntjs.com/grunt.file#wiki-grunt-file-exists), [file.isDir](https://gruntjs.com/grunt.file#wiki-grunt-file-isdir), [file.isFile](https://gruntjs.com/grunt.file#wiki-grunt-file-isfile), [file.isLink](https://gruntjs.com/grunt.file#wiki-grunt-file-islink), [file.isPathCwd](https://gruntjs.com/grunt.file#wiki-grunt-file-ispathcwd), [file.isPathInCwd](https://gruntjs.com/grunt.file#wiki-grunt-file-ispathincwd), [file.doesPathContain](https://gruntjs.com/grunt.file#wiki-grunt-file-doespathcontain), [file.arePathsEquivalent](https://gruntjs.com/grunt.file#wiki-grunt-file-arepathsequivalent) testing methods.
 - Added [file.match](https://gruntjs.com/grunt.file#wiki-grunt-file-match) and [file.isMatch](https://gruntjs.com/grunt.file#wiki-grunt-file-ismatch) methods to facilitate matching wildcard patterns against file paths.
 - Added [file.expandMapping](https://gruntjs.com/grunt.file#wiki-grunt-file-expandmapping) method for use in generating 1-to-1 src-dest file mappings.
 - Added [file.readYAML](https://gruntjs.com/grunt.file#wiki-grunt-file-readyaml) method.
 - Changed [file.findup](https://gruntjs.com/grunt.file#wiki-grunt-file-findup) to use the [findup-sync](https://github.com/cowboy/node-findup-sync) module.
 - Changed [file.glob](https://gruntjs.com/grunt.file#wiki-grunt-file-glob) to use the [glob](https://github.com/isaacs/node-glob) module.
 - Added [file.minimatch](https://gruntjs.com/grunt.file#wiki-grunt-file-minimatch) which exposes the [minimatch](https://github.com/isaacs/minimatch) module.
 - Removed `file.userDir` method (moved into [grunt-init](https://github.com/gruntjs/grunt-init)).
 - Removed `file.clearRequireCache` method.
 - Removed `file.expandFiles` and `file.expandDirs` methods, use the `filter` option of `file.expand` instead.
 - Removed `file.expandFileURLs` method. Don't specify URLs where files should be specified (eg. the qunit task now allows for a `urls` option).
 
  - 
[grunt.task](https://gruntjs.com/grunt#wiki-grunt-task)
 Tasks registered with both [task.registerTask](https://gruntjs.com/grunt.task#wiki-grunt-task-registertask) and [task.registerMultiTask](https://gruntjs.com/grunt.task#wiki-grunt-task-registermultitask) get a `this.options` method.
 - Added [task.normalizeMultiTaskFiles](https://gruntjs.com/grunt.task#wiki-grunt-task-normalizemultitaskfiles) method to facilitate the normalization of multi task `files` objects into the `this.file` property.
 - Removed `task.registerHelper` and `task.renameHelper` methods.
 - Removed `task.searchDirs` property.
 - Removed `task.expand` `task.expandDirs` `task.expandFiles` `task.getFile` `task.readDefaults` methods (moved into [grunt-init](https://github.com/gruntjs/grunt-init)).
 
  - 
[grunt.package](https://gruntjs.com/grunt#wiki-grunt-package) reflects the metadata stored in grunt's `package.json`.
 - 
[grunt.version](https://gruntjs.com/grunt#wiki-grunt-version) is the current version of Grunt as a string.
 - 
[grunt.template](https://gruntjs.com/grunt.template)
 Added [template.addDelimiters](https://gruntjs.com/grunt.template#wiki-grunt-template-adddelimiters) method to add new template delimiters.
 - Added [template.setDelimiters](https://gruntjs.com/grunt.template#wiki-grunt-template-setdelimiters) method to select template delimiters.
 - The `init` and `user` template delimiters have been removed, but you can add them in again if you need to with `template.addDelimiters` ([grunt-init](https://github.com/gruntjs/grunt-init) uses this to enable the `{% %}` template delimiters).
 
  - 
[grunt.util](https://gruntjs.com/grunt.util) replaces the now-removed `grunt.utils`.
 Changed `util._` to use [Lo-Dash](http://lodash.com/)

 - Added the [util.callbackify](https://gruntjs.com/grunt.util#wiki-grunt-util-callbackify) method.
 - Changed the [util.spawn](https://gruntjs.com/grunt.util#wiki-grunt-util-spawn) method to be much better behaved and pass more consistent arguments into its callback.
 
  
 

## Task / plugin authors

 

**Plugin authors, please indicate clearly on your repository README which version number of your Grunt plugin breaks compatibility with Grunt 0.3.**

 

### Tasks

 
 - Multi tasks
 Multiple src-dest file mappings may now be specified per target in a `files` object (this is optional).
 
  - 
[this.files / grunt.task.current.files](https://gruntjs.com/grunt.task#wiki-this-files)
 The `this.files` property is an array of src-dest file mapping objects to be iterated over in your multi task. It will always be an array, and you should always iterate over it, even if the most common use case is to specify a single file.
 - Each src-dest file mapping object has a `src` and `dest` property (and possibly others, depending on what the user specified). The `src` property is already expanded from whatever glob pattern the user may have specified.
 
  - 
[this.filesSrc / grunt.task.current.filesSrc](https://gruntjs.com/grunt.task#wiki-this-filessrc)
 The `this.filesSrc` property is a reduced, uniqued array of all files matched by all specified `src` properties. Useful for read-only tasks.
 
  - 
[this.options / grunt.task.current.options](https://gruntjs.com/grunt.task#wiki-this-options)
 The `this.options` method may be used within tasks to normalize options. Inside a task, you may specify options defaults like: `var options = this.options({option: 'defaultvalue', ...});`

 
  
 

### Plugins

 
 - An updated `gruntplugin` template has been created for Grunt 0.4-compatible plugins, and is available in the standalone [grunt-init](https://github.com/gruntjs/grunt-init).
 
 

## Troubleshooting

 
 - If you had previously installed a development version of Grunt 0.4 or any grunt-contrib plugins, be sure to flush your npm cache with `npm cache clean` first to ensure that you are pulling the final version of Grunt and grunt-contrib plugins.
 

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/upgrading-from-0.3-to-0.4](https://gruntjs.com/upgrading-from-0.3-to-0.4)

---

## Section: upgrading-from-0.4-to-1.0

# Upgrading from 0.4 to 1.0

This guide is here to help you update your projects and plugins from Grunt 0.4.x to Grunt 1.0.

 

**Be advised Grunt 1.0.0 no longer supports Node.js v0.8.**

 

## For Projects that use Grunt

 

### Peer Dependencies

 

You might receive `peerDependencies` errors when you install a project with Grunt 1.0. We ask you to send pull requests to your favourite plugins and ask them to update the peerDependencies section of their package.json. See below for details about plugin updates.

 

## For Plugins and Plugin developers

 

### Peer Dependencies

 

If you have a Grunt plugin that includes grunt in the peerDependencies section of your package.json, we recommend tagging with "grunt": "&gt;=0.4.0". Otherwise when grunt@1.0.0 is released, npm@2 users will receive a hard error when trying to install your plugin and npm@3 users will get a warning.

 

Be aware, peer dependencies are no longer installed for users as of npm@3. Users of Grunt plugins are expected to npm install grunt --save-dev alongside any Grunt plugin install.

 

We ask you to update your plugin with `"grunt": ">=0.4.0"` in it and publish that on npm.

 

### Changes in 1.0.0

 
 - Prevent async callback from being called multiple times. Pull #1464.
 - Update copyright to jQuery Foundation and remove redundant headers. Fixes #1478.
 - Update glob to 7.0.x. Fixes #1467.
 - Removing duplicate BOM strip code. Pull #1482.
 - Updated to latest cli ~1.2.0
 - Ensure a grunt bin gets created upon install.
 
 

### Changes in Grunt 1.0 RC1:

 

Be aware, some APIs have changed warranting a major version update:

 
 - 
`coffee-script` is upgraded to `~1.10.0` which could incur breaking changes when using the language with plugins and Gruntfiles.
 - 
`nopt` is upgraded to `~3.0.6` which has fixed many issues, including passing multiple arguments and dealing with numbers as options. Be aware previously `--foo bar` used to pass the value `'bar'` to the option `foo`. It will now set the option `foo` to `true` and run the task `bar`.
 - 
`glob` is upgraded to `~6.0.4` and `minimatch` is upgraded to `~3.0.0`. Results are now sorted by default with `grunt.file.expandMapping()`. Pass the `nosort: true` option if you don't want the results to be sorted.
 - 
`lodash` was upgraded to `~4.3.0`. Many changes have occurred. Some of which that directly effect Grunt are `grunt.util._.template()` returns a compile function and `grunt.util._.flatten` no longer flattens deeply. `grunt.util._` is deprecated and we highly encourage you to `npm install lodash` and `var _ = require('lodash')` to use `lodash`. Please see the lodash changelog for a full list of changes: [https://github.com/lodash/lodash/wiki/Changelog](https://github.com/lodash/lodash/wiki/Changelog)

 - 
`iconv-lite` is upgraded to `~0.4.13` and strips the BOM by default.
 - 
`js-yaml` is upgraded to `~3.5.2` and may affect `grunt.file.readYAML`. We encourage you to please `npm install js-yaml` and use `var YAML = require('js-yaml')` directly in case of future deprecations.
 - A file `mode` option can be passed into [grunt.file.write()](api/grunt.file#grunt.file.write).
 - 
`Done, without errors.` was changed to `Done.` to avoid failing by mistake on the word `errors`.
 

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/upgrading-from-0.4-to-1.0](https://gruntjs.com/upgrading-from-0.4-to-1.0)

---

## Section: api/grunt.event

# grunt.event

Even though only the most relevant methods are listed on this page, the full [EventEmitter2 API](https://github.com/hij1nx/EventEmitter2) is available on the `grunt.event` object. Event namespaces may be specified with the `.` (dot) separator, and namespace wildcards have been enabled.

 

*Note that Grunt doesn't yet emit any events, but can still be useful in your own tasks.*

 

### grunt.event.on

 

Adds a listener to the end of the listeners array for the specified event.

 

```
grunt.event.on(event, listener)
```

 

### grunt.event.once

 

Adds a **one time** listener for the event. The listener is invoked only the first time the event is fired, after which it is removed.

 

```
grunt.event.once(event, listener)
```

 

### grunt.event.many

 

Adds a listener that will execute **n times** for the event before being removed.

 

```
grunt.event.many(event, timesToListen, listener)
```

 

### grunt.event.off

 

Remove a listener from the listener array for the specified event.

 

```
grunt.event.off(event, listener)
```

 

### grunt.event.removeAllListeners

 

Removes all listeners, or those of the specified event.

 

```
grunt.event.removeAllListeners([event])
```

 

### grunt.event.emit

 

Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.

 

```
grunt.event.emit(event, [arg1], [arg2], [...])
```

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.event](https://gruntjs.com/api/grunt.event)

---

## Section: api/grunt.log

# grunt.log

Output messages to the console.

 

See the [log lib source](https://github.com/gruntjs/grunt-legacy-log/blob/master/index.js) for more information.

 

## The log API

 

Grunt output should look consistent, and maybe even pretty. As such, there is a plethora of logging methods, and a few useful patterns. All of the methods that actually log something are chainable.

 

*Note: all methods available under `grunt.verbose` work exactly like `grunt.log` methods, but only log if the `--verbose` command-line option was specified.*

 

### grunt.log.write / grunt.verbose.write

 

Log the specified `msg` string, with no trailing newline.

 

```
grunt.log.write(msg)
```

 

### grunt.log.writeln / grunt.verbose.writeln

 

Log the specified `msg` string, with trailing newline.

 

```
grunt.log.writeln([msg])
```

 

### grunt.log.error / grunt.verbose.error

 

If `msg` string is omitted, logs `ERROR` in red, otherwise logs `>> msg`, with trailing newline.

 

```
grunt.log.error([msg])
```

 

### grunt.log.errorlns / grunt.verbose.errorlns

 

Log an error with `grunt.log.error`, wrapping text to 80 columns using `grunt.log.wraptext`.

 

```
grunt.log.errorlns(msg)
```

 

### grunt.log.ok / grunt.verbose.ok

 

If `msg` string is omitted, logs `OK` in green, otherwise logs `>> msg`, with trailing newline.

 

```
grunt.log.ok([msg])
```

 

### grunt.log.oklns / grunt.verbose.oklns

 

Log an ok message with `grunt.log.ok`, wrapping text to 80 columns using `grunt.log.wraptext`.

 

```
grunt.log.oklns(msg)
```

 

### grunt.log.subhead / grunt.verbose.subhead

 

Log the specified `msg` string in **bold**, with trailing newline.

 

```
grunt.log.subhead(msg)
```

 

### grunt.log.writeflags / grunt.verbose.writeflags

 

Log a list of `obj` properties (good for debugging flags).

 

```
grunt.log.writeflags(obj, prefix)
```

 

### grunt.log.debug / grunt.verbose.debug

 

Logs a debugging message, but only if the `--debug` command-line option was specified.

 

```
grunt.log.debug(msg)
```

 

## Verbose and Notverbose

 

All logging methods available under `grunt.verbose` work exactly like their `grunt.log` counterparts, but only log if the `--verbose` command-line option was specified. There is also a "notverbose" counterpart available at both `grunt.log.notverbose` and `grunt.log.verbose.or`. In fact, the `.or` property can be used on both `verbose` and `notverbose` to effectively toggle between the two.

 

### grunt.verbose / grunt.log.verbose

 

This object contains all methods of `grunt.log` but only logs if the `--verbose` command-line option was specified.

 

```
grunt.verbose
```

 

### grunt.verbose.or / grunt.log.notverbose

 

This object contains all methods of `grunt.log` but only logs if the `--verbose` command-line option was *not* specified.

 

```
grunt.verbose.or
```

 

## Utility Methods

 

These methods don't actually log, they just return strings that can be used in other methods.

 

### grunt.log.wordlist

 

Returns a comma-separated list of `arr` array items.

 

```
grunt.log.wordlist(arr [, options])
```

 

The `options` object has these possible properties, and default values:

 

```
var options = {
  // The separator string (can be colored).
  separator: ', ',
  // The array item color (specify false to not colorize).
  color: 'cyan',
};
```

 

### grunt.log.uncolor

 

Removes all color information from a string, making it suitable for testing `.length` or perhaps logging to a file.

 

```
grunt.log.uncolor(str)
```

 

### grunt.log.wraptext

 

Wrap `text` string to `width` characters with `\n`, ensuring that words are not split in the middle unless absolutely necessary.

 

```
grunt.log.wraptext(width, text)
```

 

### grunt.log.table

 

Wrap `texts` array of strings to columns `widths` characters wide. A wrapper for the `grunt.log.wraptext` method that can be used to generate output in columns.

 

```
grunt.log.table(widths, texts)
```

 

## An Example

 

A common pattern is to only log when in `--verbose` mode OR if an error occurs, like so:

 

```
grunt.registerTask('something', 'Do something interesting.', function(arg) {
  var msg = 'Doing something...';
  grunt.verbose.write(msg);
  try {
    doSomethingThatThrowsAnExceptionOnError(arg);
    // Success!
    grunt.verbose.ok();
  } catch(e) {
    // Something went wrong.
    grunt.verbose.or.write(msg).error().error(e.message);
    grunt.fail.warn('Something went wrong.');
  }
});
```

 

An explanation of the above code:

 
 - 
`grunt.verbose.write(msg);` logs the message (no newline), but only in `--verbose` mode.
 - 
`grunt.verbose.ok();` logs OK in green, with a newline.
 - 
`grunt.verbose.or.write(msg).error().error(e.message);` does a few things:
 
`grunt.verbose.or.write(msg)` logs the message (no newline) if not in `--verbose` mode, and returns the `notverbose` object.
 - 
`.error()` logs ERROR in red, with a newline, and returns the `notverbose` object.
 - 
`.error(e.message);` logs the actual error message (and returns the `notverbose` object).
 
  - 
`grunt.fail.warn('Something went wrong.');` logs a warning in bright yellow, exiting Grunt with exit code 1, unless `--force` was specified.
 
 

Take a look at the [grunt-contrib-* tasks source code](https://github.com/gruntjs) for more examples.

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.log](https://gruntjs.com/api/grunt.log)

---

## Section: api/grunt.option

# grunt.option

The Grunt option API is for sharing parameters across multiple tasks and accessing parameters set on the command line.

 

An example would be a flag to target whether your build is for development or staging. On the command line: `grunt deploy --target=staging` would cause `grunt.option('target')` to return `"staging"`.

 

An example `Gruntfile` to utilize the `target` option could be:

 

```
grunt.initConfig({
  compass: {
    dev: {
      options: {
        /* ... */
        outputStyle: 'expanded'
      },
    },
    staging: {
      options: {
        /* ... */
        outputStyle: 'compressed'
      },
    },
  },
});
var target = grunt.option('target') || 'dev';
grunt.registerTask('deploy', ['compass:' + target]);
```

 

As you run `grunt deploy` your stylesheets would default to the `dev` target and output the CSS in the expanded format. If you ran `grunt deploy --target=staging` the `staging` target would instead be ran and your CSS would be in the compressed format.

 

`grunt.option` can be used within tasks as well, for example:

 

```
grunt.registerTask('upload', 'Upload code to specified target.', function(n) {
  var target = grunt.option('target');
  // do something useful with target here
});
grunt.registerTask('deploy', ['validate', 'upload']);
```

 

*Note that boolean options can be specified using just a key without a value. For example, running `grunt deploy --staging` on the command line would cause `grunt.option('staging')` to return `true`.*

 

### grunt.option ☃

 

Gets or sets an option.

 

```
grunt.option(key[, val])
```

 

Boolean options can be negated by prepending `no-` onto the `key`. For example:

 

```
grunt.option('staging', false);
var isDev = grunt.option('no-staging');
// isDev === true
```

 

### grunt.option.init

 

Initialize `grunt.option`. If `initObject` is omitted option will be initialized to an empty object otherwise will be set to `initObject`.

 

```
grunt.option.init([initObject])
```

 

### grunt.option.flags

 

Returns the options as an array of command line parameters.

 

```
grunt.option.flags()
```

 

### grunt.option.keys

 

@since 1.2.0+

 

Returns all option keys.

 

```
grunt.option.keys()
```

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.option](https://gruntjs.com/api/grunt.option)

---

## Section: project-scaffolding

# Project Scaffolding

## grunt-init

 

Grunt-init is a scaffolding tool used to automate project creation. It will build an entire directory structure based on current environment and answers to some questions. The exact files and contents created depend on the template chosen along with the answers to the questions asked.

 

*Note: This standalone utility used to be built-in to Grunt as the "init" task. See the Grunt [Upgrading from 0.3 to 0.4](upgrading-from-0.3-to-0.4) guide for more information about this change.*

 

## Installation

 

In order to use grunt-init, you'll want to install it globally.

 

```
npm install -g grunt-init
```

 

This will put the `grunt-init` command in your system path, allowing it to be run from anywhere.

 

*Notes: You may need to use sudo or run your command shell as Administrator to do this.*

 

## Usage

 
 - Get program help and a listing of available templates with `grunt-init --help`

 - Create a project based around an available template with `grunt-init TEMPLATE`

 - Create a project based around a arbitrarily-located template with `grunt-init /path/to/TEMPLATE`

 
 

Note that most templates generate their files in the current directory, so be sure to change to a new directory first if you don't want to overwrite existing files.

 

## Installing templates

 

Once templates are installed into your `~/.grunt-init/` directory (`%USERPROFILE%\.grunt-init\` on Windows) they will be available for use via grunt-init. It's recommended that you use git to clone a template into that directory. For example, the [grunt-init-jquery](https://github.com/gruntjs/grunt-init-jquery) template can be installed like so:

 

```
git clone https://github.com/gruntjs/grunt-init-jquery.git ~/.grunt-init/jquery
```

 

*Note: if you want to make the template available locally as "foobarbaz" you could specify `~/.grunt-init/foobarbaz` while cloning. Grunt-init will use the actual template directory name as it exists inside of the `~/.grunt-init/` directory.*

 

A few grunt-init templates are maintained officially:

 
 - 
[grunt-init-commonjs](https://github.com/gruntjs/grunt-init-commonjs) - Create a commonjs module, including Nodeunit unit tests. ([sample "generated" repo](https://github.com/gruntjs/grunt-init-commonjs-sample/tree/generated) | [creation transcript](https://github.com/gruntjs/grunt-init-commonjs-sample#project-creation-transcript))
 - 
[grunt-init-gruntfile](https://github.com/gruntjs/grunt-init-gruntfile) - Create a basic Gruntfile. ([sample "generated" repo](https://github.com/gruntjs/grunt-init-gruntfile-sample/tree/generated) | [creation transcript](https://github.com/gruntjs/grunt-init-gruntfile-sample#project-creation-transcript))
 - 
[grunt-init-gruntplugin](https://github.com/gruntjs/grunt-init-gruntplugin) - Create a Grunt plugin, including Nodeunit unit tests. ([sample "generated" repo](https://github.com/gruntjs/grunt-init-gruntplugin-sample/tree/generated) | [creation transcript](https://github.com/gruntjs/grunt-init-gruntplugin-sample#project-creation-transcript))
 - 
[grunt-init-jquery](https://github.com/gruntjs/grunt-init-jquery) - Create a jQuery plugin, including QUnit unit tests. ([sample "generated" repo](https://github.com/gruntjs/grunt-init-jquery-sample/tree/generated) | [creation transcript](https://github.com/gruntjs/grunt-init-jquery-sample#project-creation-transcript))
 - 
[grunt-init-node](https://github.com/gruntjs/grunt-init-node) - Create a Node.js module, including Nodeunit unit tests. ([sample "generated" repo](https://github.com/gruntjs/grunt-init-node-sample/tree/generated) | [creation transcript](https://github.com/gruntjs/grunt-init-node-sample#project-creation-transcript))
 
 

## Custom templates

 

You can create and use custom templates. Your template must follow the same structure as the aforementioned templates.

 

A sample template named `my-template` would follow this general file structure:

 
 - 
`my-template/template.js` - the main template file.
 - 
`my-template/rename.json` - template-specific rename rules, processed as templates.
 - 
`my-template/root/` - files to be copied into the target location.
 
 

Assuming these files exist at `/path/to/my-template`, the command `grunt-init /path/to/my-template` would be used to process the template. Multiple uniquely-named templates may exist in the same directory.

 

Additionally, if you place this custom template in your `~/.grunt-init/` directory (`%USERPROFILE%\.grunt-init\` on Windows) it will be automatically available to be used with just `grunt-init my-template`.

 

### Copying files

 

As long as a template uses the `init.filesToCopy` and `init.copyAndProcess` methods, any files in the `root/` subdirectory will be copied to the current directory when the init template is run.

 

Note that all copied files will be processed as templates, with any `{% %}` template being processed against the collected `props` data object, unless the `noProcess` option is set. See the [jquery template](https://github.com/gruntjs/grunt-init-jquery) for an example.

 

### Renaming or excluding template files

 

The `rename.json` describes `sourcepath` to `destpath` rename mappings. The `sourcepath` must be the path of the file-to-be-copied relative to the `root/` folder, but the `destpath` value can contain `{% %}` templates, describing what the destination path will be.

 

If `false` is specified as a `destpath` the file will not be copied. Also, glob patterns are supported for `srcpath`.

 

## Specifying default prompt answers

 

Each init prompt either has a default value hard-coded or it looks at the current environment to attempt to determine that default value. If you want to override a particular prompt's default value, you can do so in the optional OS X or Linux `~/.grunt-init/defaults.json` or Windows `%USERPROFILE%\.grunt-init\defaults.json` file.

 

For example, my `defaults.json` file looks like this, because I want to use a slightly different name than the default name, I want to exclude my email address, and I want to specify an author URL automatically.

 

```
{
  "author_name": "\"Cowboy\" Ben Alman",
  "author_email": "none",
  "author_url": "http://benalman.com/"
}
```

 

*Note: until all the built-in prompts have been documented, you can find their names and default values in the [source code](https://github.com/gruntjs/grunt-init/blob/master/tasks/init.js).*

 

## Defining an init template

 

### exports.description

 

This brief template description will be displayed along with the template name when the user runs `grunt init` or `grunt-init` to display a list of all available init templates.

 

```
exports.description = descriptionString;
```

 

### exports.notes

 

If specified, this optional extended description will be displayed before any prompts are displayed. This is a good place to give the user a little help explaining naming conventions, which prompts may be required or optional, etc.

 

```
exports.notes = notesString;
```

 

### exports.warnOn

 

If this optional (but recommended) wildcard pattern or array of wildcard patterns is matched, Grunt will abort with a warning that the user can override with `--force`. This is very useful in cases where the init template could potentially override existing files.

 

```
exports.warnOn = wildcardPattern;
```

 

While the most common value will be `'*'`, matching any file or directory, the [minimatch](https://github.com/isaacs/minimatch) wildcard pattern syntax used allows for a lot of flexibility. For example:

 

```
exports.warnOn = 'Gruntfile.js';    // Warn on a Gruntfile.js file.
exports.warnOn = '*.js';            // Warn on any .js file.
exports.warnOn = '*';               // Warn on any non-dotfile or non-dotdir.
exports.warnOn = '.*';              // Warn on any dotfile or dotdir.
exports.warnOn = '{.*,*}';          // Warn on any file or dir (dot or non-dot).
exports.warnOn = '!*/**';           // Warn on any file (ignoring dirs).
exports.warnOn = '*.{png,gif,jpg}'; // Warn on any image file.

// This is another way of writing the last example.
exports.warnOn = ['*.png', '*.gif', '*.jpg'];
```

 

### exports.template

 

While the `exports` properties are defined outside this function, all the actual init code is specified inside. Three arguments are passed into this function. The `grunt` argument is a reference to grunt, containing all the [grunt methods and libs](api/grunt). The `init` argument is an object containing methods and properties specific to this init template. The `done` argument is a function that must be called when the init template is done executing.

 

```
exports.template = function(grunt, init, done) {
  // See the "Inside an init template" section.
};
```

 

## Inside an init template

 

### init.addLicenseFiles

 

Add properly-named license files to the files object.

 

```
var files = {};
var licenses = ['MIT'];
init.addLicenseFiles(files, licenses);
// files === {'LICENSE-MIT': 'licenses/LICENSE-MIT'}
```

 

### init.availableLicenses

 

Return an array of available licenses.

 

```
var licenses = init.availableLicenses();
// licenses === [ 'Apache-2.0', 'GPL-2.0', 'MIT', 'MPL-2.0' ]
```

 

### init.copy

 

Given an absolute or relative source path, and an optional relative destination path, copy a file, optionally processing it through the passed callback.

 

```
init.copy(srcpath[, destpath], options)
```

 

### init.copyAndProcess

 

Iterate over all files in the passed object, copying the source file to the destination, processing the contents.

 

```
init.copyAndProcess(files, props[, options])
```

 

### init.defaults

 

User-specified default init values from `defaults.json`.

 

```
init.defaults
```

 

### init.destpath

 

Absolute destination file path.

 

```
init.destpath()
```

 

### init.expand

 

Same as [grunt.file.expand](https://github.com/gruntjs/grunt/wiki/grunt.file#wiki-grunt-file-expand).

 

Return a unique array of all file or directory paths that match the given wildcard pattern(s). This method accepts either comma separated wildcard patterns or an array of wildcard patterns. Paths matching patterns that begin with ! will be excluded from the returned array. Patterns are processed in order, so inclusion and exclusion order is significant.

 

```
init.expand([options, ] patterns)
```

 

### init.filesToCopy

 

Return an object containing files to copy with their absolute source path and relative destination path, renamed (or omitted) according to rules in rename.json (if it exists).

 

```
var files = init.filesToCopy(props);
/* files === { '.gitignore': 'template/root/.gitignore',
  '.jshintrc': 'template/root/.jshintrc',
  'Gruntfile.js': 'template/root/Gruntfile.js',
  'README.md': 'template/root/README.md',
  'test/test_test.js': 'template/root/test/name_test.js' } */
```

 

### init.getFile

 

Get a single task file path.

 

```
init.getFile(filepath[, ...])
```

 

### init.getTemplates

 

Returns an object of all the available templates.

 

```
init.getTemplates()
```

 

### init.initSearchDirs

 

Initialize the directories to search for init templates. `template` is the location of a template. Will also include `~/.grunt-init/` and the core init tasks within grunt-init.

 

```
init.initSearchDirs([filename])
```

 

### init.process

 

Start up the process to begin prompting for input.

 

```
init.process(options, prompts, done)
```

 

```
init.process({}, [
  // Prompt for these values
  init.prompt('name'),
  init.prompt('description'),
  init.prompt('version')
], function(err, props) {
  // All finished, do something with the properties
});
```

 

### init.prompt

 

Prompt a user for a value.

 

```
init.prompt(name[, default])
```

 

### init.prompts

 

An object of all the prompts.

 

```
var prompts = init.prompts;
```

 

### init.readDefaults

 

Read JSON defaults from task files (if they exist), merging them into one data object.

 

```
init.readDefaults(filepath[, ...])
```

 

### init.renames

 

The rename rules for the template.

 

```
var renames = init.renames;
// renames === { 'test/name_test.js': 'test/{%= name %}_test.js' }
```

 

### init.searchDirs

 

An array of directories to search for templates in.

 

```
var dirs = init.searchDirs;
/* dirs === [ '/Users/shama/.grunt-init',
  '/usr/local/lib/node_modules/grunt-init/templates' ] */
```

 

### init.srcpath

 

Search init template paths for filename and return an absolute path.

 

```
init.srcpath(filepath[, ...])
```

 

### init.userDir

 

Returns the absolute path to the user's template directory.

 

```
var dir = init.userDir();
// dir === '/Users/shama/.grunt-init'
```

 

### init.writePackageJSON

 

Save a package.json file in the destination directory. The callback can be used to post-process properties to add/remove/whatever.

 

```
init.writePackageJSON(filename, props[, callback])
```

 

## Built-in prompts

 

### author_email

 

Author's email address to use in the `package.json`. Will attempt to find a default value from the user's git config.

 

### author_name

 

Author's full name to use in the `package.json` and copyright notices. Will attempt to find a default value from the user's git config.

 

### author_url

 

A public URL to the author's website to use in the `package.json`.

 

### bin

 

A relative path from the project root for a cli script.

 

### bugs

 

A public URL to the project's issues tracker. Will default to the GitHub issue tracker if the project has a GitHub repository.

 

### description

 

A description of the project. Used in the `package.json` and README files.

 

### grunt_version

 

A valid semantic version range descriptor of Grunt the project requires.

 

### homepage

 

A public URL to the project's home page. Will default to the GitHub URL if a GitHub repository.

 

### jquery_version

 

If a jQuery project, the version of jQuery the project requires. Must be a valid semantic version range descriptor.

 

### licenses

 

The license(s) for the project. Multiple licenses are separated by spaces. The licenses built-in are: `MIT`, `MPL-2.0`, `GPL-2.0`, and `Apache-2.0`. Defaults to `MIT`. Add custom licenses with [init.addLicenseFiles](project-scaffolding#init.addlicensefiles).

 

### main

 

The primary entry point of the project. Defaults to the project name within the `lib` folder.

 

### name

 

The name of the project. Will be used heavily throughout the project template. Defaults to the current working directory.

 

### node_version

 

The version of Node.js the project requires. Must be a valid semantic version range descriptor.

 

### npm_test

 

The command to run tests on your project. Defaults to `grunt`.

 

### repository

 

Project's git repository. Defaults to a guess of a GitHub URL.

 

### title

 

A human readable project name. Defaults to the actual project name altered to be more human readable.

 

### version

 

The version of the project. Defaults to the first valid semantic version, `0.1.0`.

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/project-scaffolding](https://gruntjs.com/project-scaffolding)

---

## Section: api/exit-codes

# Exit Codes

 - 
`0` - No errors!
 - 
`1` - Fatal error
 - 
`2` - Missing gruntfile error
 - 
`3` - Task error
 - 
`4` - Template processing error
 - 
`5` - Invalid shell auto-completion rules error
 - 
`6` - Warning
 

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/exit-codes](https://gruntjs.com/api/exit-codes)

---

## Section: api/grunt.template

# grunt.template

Template strings can be processed manually using the provided template functions. In addition, the `config.get` method (used by many tasks) automatically expands `<% %>` style template strings specified as config data inside the `Gruntfile`.

 

### grunt.template.process

 

Process a [Lo-Dash template](http://lodash.com/docs/#template) string. The `template` argument will be processed recursively until there are no more templates to process.

 

The default data object is the entire config object, but if `options.data` is set, that object will be used instead. The default template delimiters are `<% %>` but if `options.delimiters` is set to a custom delimiter name (set with [`grunt.template.addDelimiters`](https://api/grunt.template#grunt.template.adddelimiters)), those template delimiters will be used instead.

 

```
grunt.template.process(template [, options])
```

 

Inside templates, the `grunt` object is exposed so that you can do things like `<%= grunt.template.today('yyyy') %>`. *Note that if the data object already has a `grunt` property, the `grunt` API will not be accessible in templates.*

 

In this example, the `baz` property is processed recursively until there are no more `<% %>` templates to process.

 

```
var obj = {
  foo: 'c',
  bar: 'b<%= foo %>d',
  baz: 'a<%= bar %>e'
};
grunt.template.process('<%= baz %>', {data: obj}) // 'abcde'
```

 

### grunt.template.setDelimiters

 

Set the [Lo-Dash template](http://lodash.com/docs/#template) delimiters to a predefined set in case `grunt.util._.template` needs to be called manually. The `config` delimiters `<% %>` are included by default.

 

*You probably won't need to use this method, because you'll be using `grunt.template.process` which uses this method internally.*

 

```
grunt.template.setDelimiters(name)
```

 

### grunt.template.addDelimiters

 

Add a named set of [Lo-Dash template](http://lodash.com/docs/#template) delimiters. You probably won't need to use this method, because the built-in delimiters should be sufficient, but you could always add `{% %}` or `[% %]` style delimiters.

 

The `name` argument should be unique since it is how we access the delimiters from `grunt.template.setDelimiters` and as an option for `grunt.template.process`.

 

```
grunt.template.addDelimiters(name, opener, closer)
```

 

In this example, if we were to use the `{% %}` style mentioned above we would use the following:

 

```
grunt.template.addDelimiters('myDelimiters', '{%', '%}')
```

 

## Helpers

 

### grunt.template.date

 

Format a date using the [dateformat library](https://github.com/felixge/node-dateformat).

 

```
grunt.template.date(date, format)
```

 

In this example, a specific date is formatted as month/day/year.

 

```
grunt.template.date(847602000000, 'yyyy-mm-dd') // '1996-11-10'
```

 

### grunt.template.today

 

Format today's date using the [dateformat library](https://github.com/felixge/node-dateformat).

 

```
grunt.template.today(format)
```

 

In this example, today's date is formatted as a 4-digit year.

 

```
grunt.template.today('yyyy') // This returns a year in format such as '2020'
```

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.template](https://gruntjs.com/api/grunt.template)

---

## Section: api/grunt.task

# grunt.task

Register, run and load external tasks.

 

See the [task lib source](https://github.com/gruntjs/grunt/blob/master/lib/grunt/task.js) and [task util lib source](https://github.com/gruntjs/grunt/blob/master/lib/util/task.js) for more information.

 

## The task API

 

While a task is running, Grunt exposes many task-specific utility properties and methods inside the task function via the `this` object. See the [Inside tasks](https://gruntjs.com/inside-tasks/) guide for a list of these properties and methods.

 

Many utility properties and methods are available inside of tasks via the `this` object.

 

Note 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](https://gruntjs.com/grunt) for more usage information.

 

## Creating Tasks

 

### grunt.task.registerTask ☃

 

Register an "alias task" or a task function. This method supports the following two signatures:

 

**Alias task**

 

If 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 must be an array of tasks.

 

```
grunt.task.registerTask(taskName, taskList)
```

 

When the optional `description` string is passed it will be displayed when `grunt --help` is run:

 

```
grunt.task.registerTask(taskName, description, taskList)
```

 

This example alias task defines a "default" task whereby the "jshint", "qunit", "concat" and "uglify" tasks are run automatically if Grunt is executed without any tasks specified:

 

```
task.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);
```

 

Task arguments can be specified as well. In this example, the alias "dist" runs both the "concat" and "uglify" tasks, each with the "dist" argument:

 

```
task.registerTask('dist', ['concat:dist', 'uglify:dist']);
```

 

**Function task**

 

If 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.

 

Note that the `grunt.task.registerMultiTask` method, explained below, can be used to define a special type of task known as a "multi task."

 

```
grunt.task.registerTask(taskName, description, taskFunction)
```

 

This 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`.

 

```
grunt.task.registerTask('foo', 'A sample task that logs stuff.', function(arg1, arg2) {
  if (arguments.length === 0) {
    grunt.log.writeln(this.name + ", no args");
  } else {
    grunt.log.writeln(this.name + ", " + arg1 + " " + arg2);
  }
});
```

 

See the [creating tasks](../creating-tasks) documentation for more examples of tasks and alias tasks.

 

*This method is also available as [grunt.registerTask](https://gruntjs.com/grunt).*

 

### grunt.task.registerMultiTask ☃

 

Register 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.

 

Many of the contrib tasks, including the [jshint task](https://github.com/gruntjs/grunt-contrib-jshint), [concat task](https://github.com/gruntjs/grunt-contrib-concat) and [uglify task](https://github.com/gruntjs/grunt-contrib-uglify) are multi tasks.

 

```
grunt.task.registerMultiTask(taskName, description, taskFunction)
```

 

Given 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`.

 

```
grunt.initConfig({
  log: {
    foo: [1, 2, 3],
    bar: 'hello world',
    baz: false
  }
});

grunt.task.registerMultiTask('log', 'Log stuff.', function() {
  grunt.log.writeln(this.target + ': ' + this.data);
});
```

 

See the [creating tasks](../creating-tasks) documentation for more examples of multi tasks.

 

*This method is also available as [grunt.registerMultiTask](https://gruntjs.com/grunt).*

 

### grunt.task.requires

 

Fail the task if some other task failed or never ran.

 

```
grunt.task.requires(taskName);
```

 

### grunt.task.exists

 

*Added in 0.4.5*

 

Check with the name, if a task exists in the registered tasks. Return a boolean.

 

```
grunt.task.exists(name)
```

 

### grunt.task.renameTask ☃

 

Rename a task. This might be useful if you want to override the default behavior of a task, while retaining the old name.

 

*Note that if a task has been renamed, the [this.name](https://gruntjs.com/inside-tasks#this.name) and [this.nameArgs](https://gruntjs.com/inside-tasks#this.nameargs) properties will change accordingly.*

 

```
grunt.task.renameTask(oldname, newname)
```

 

*This method is also available as [grunt.renameTask](https://gruntjs.com/grunt).*

 

## Loading Externally-Defined Tasks

 

For most projects, tasks will be defined in the [Gruntfile](../index). For larger projects, or in cases where tasks need to be shared across projects, tasks can be loaded from one or more external directories or Npm-installed Grunt plugins.

 

### grunt.task.loadTasks ☃

 

Load task-related files from the specified directory, relative to the [Gruntfile](../index). 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.

 

```
grunt.task.loadTasks(tasksPath)
```

 

*This method is also available as [grunt.loadTasks](https://gruntjs.com/grunt).*

 

### grunt.task.loadNpmTasks ☃

 

Load tasks from the specified Grunt plugin. This plugin must be installed locally via npm, and must be relative to the [Gruntfile](../index). Grunt plugins can be created by using the [grunt-init gruntplugin template](https://github.com/gruntjs/grunt-init): `grunt init:gruntplugin`.

 

```
grunt.task.loadNpmTasks(pluginName)
```

 

*This method is also available as [grunt.loadNpmTasks](https://gruntjs.com/grunt).*

 

## Queueing Tasks

 

Grunt automatically enqueues and runs all tasks specified on the command line, but individual tasks can enqueue additional tasks to be run.

 

### grunt.task.run

 

Enqueue 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 an array of tasks or individual task arguments.

 

```
grunt.task.run(taskList)
```

 

### grunt.task.clearQueue

 

Empty the task queue completely. Unless additional tasks are enqueued, no more tasks will be run.

 

```
grunt.task.clearQueue()
```

 

### grunt.task.normalizeMultiTaskFiles

 

Normalizes a task target configuration object into an array of src-dest file mappings. This method is used internally by the multi task system [this.files / grunt.task.current.files](https://gruntjs.com/grunt.task#wiki-this-files) property.

 

```
grunt.task.normalizeMultiTaskFiles(data [, targetname])
```

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.task](https://gruntjs.com/api/grunt.task)

---

## Section: api/inside-tasks

# Inside Tasks

While a task is running, Grunt exposes many task-specific utility properties and methods inside the task function via the `this` object. This same object is also exposed as `grunt.task.current` for use in [templates](https://gruntjs.com/grunt.template), eg. the property `this.name` is also available as `grunt.task.current.name`.

 

## Inside All Tasks

 

### this.async

 

If 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. Either `false` or an `Error` object may be passed to the done function to instruct Grunt that the task has failed.

 

If the `this.async` method isn't invoked, the task will execute synchronously.

 

```
// Tell Grunt this task is asynchronous.
var done = this.async();
// Your async code.
setTimeout(function() {
  // Let's simulate an error, sometimes.
  var success = Math.random() > 0.5;
  // All done!
  done(success);
}, 1000);
```

 

### this.requires

 

If 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 tasks list can be an array of task names or individual task names, as arguments.

 

Note that this won't actually run the specified task(s), it will just fail the current task if they haven't already run successfully.

 

```
this.requires(tasksList)
```

 

### this.requiresConfig

 

Fail the current task if one or more required [config](https://gruntjs.com/grunt.config) properties is missing. One or more string or array config properties may be specified.

 

```
this.requiresConfig(prop [, prop [, ...]])
```

 

See the [grunt.config documentation](https://gruntjs.com/grunt.config) for more information about config properties.

 

*This method is an alias for the [grunt.config.requires](https://gruntjs.com/grunt.config#grunt.config.requires) method.*

 

### this.name

 

The 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"`.

 

*Note that if a task has been renamed with [grunt.task.renameTask](https://gruntjs.com/grunt.task#grunt.task.renametask) this property will reflect the new name.*

 

### this.nameArgs

 

The name of the task, including any colon-separated arguments or flags specified 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"`.

 

*Note that if a task has been renamed with [grunt.task.renameTask](https://gruntjs.com/grunt.task#grunt.task.renametask) this property will reflect the new name.*

 

### this.args

 

An 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 current target is omitted from the `this.args` array.*

 

### this.flags

 

An 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}`.

 

*Note that inside multi tasks, the target name is **not** set as a flag.*

 

### this.errorCount

 

The number of [grunt.log.error](https://gruntjs.com/grunt.log#grunt.log.error) calls that occurred during this task. This can be used to fail a task if errors were logged during the task.

 

### this.options

 

Returns an options object. Properties of the optional `defaultsObj` argument will be overridden by any task-level `options` object properties, which will be further overridden in multi tasks by any target-level `options` object properties.

 

```
this.options([defaultsObj])
```

 

This example shows how a task might use the `this.options` method:

 

```
var options = this.options({
  enabled: false,
});

doSomething(options.enabled);
```

 

The [Configuring tasks](../configuring-tasks#options) guide shows an example of how options may be specified, from the task user's point of view.

 

## Inside Multi Tasks

 

### this.target

 

In a multi task, this property contains 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"`.

 

### this.files

 

In a multi task, all files specified using any Grunt-supported [file formats and options](../configuring-tasks#files), [globbing patterns](../configuring-tasks#globbing-patterns) or [dynamic mappings](../configuring-tasks#building-the-files-object-dynamically) will automatically be normalized into a single format: the [Files Array file format](../configuring-tasks#files-array-format).

 

What this means is that tasks don't need to contain a ton of boilerplate for explicitly handling custom file formats, globbing patterns, mapping source files to destination files or filtering out files or directories. *A task user can just specify files per the [Configuring tasks](../configuring-tasks#files) guide, and **Grunt will handle all the details.***

 

Your task should iterate over the `this.files` array, utilizing the `src` and `dest` properties of each object in that array. The `this.files` property will always be an array. The `src` property will also always be an array, in case your task cares about multiple source files per destination file.

 

*Note that it's possible that nonexistent files might be included in `src` values, so you may want to explicitly test that source files exist before using them.*

 

This example shows how a simple "concat" task might use the `this.files` property:

 

```
this.files.forEach(function(file) {
  var contents = file.src.filter(function(filepath) {
    // Remove nonexistent files (it's up to you to filter or warn here).
    if (!grunt.file.exists(filepath)) {
      grunt.log.warn('Source file "' + filepath + '" not found.');
      return false;
    } else {
      return true;
    }
  }).map(function(filepath) {
    // Read and return the file's source.
    return grunt.file.read(filepath);
  }).join('\n');
  // Write joined contents to destination filepath.
  grunt.file.write(file.dest, contents);
  // Print a success message.
  grunt.log.writeln('File "' + file.dest + '" created.');
});
```

 

*If you need the original file object properties, they are available on each individual file object under the `orig` property, but there is no known use-case for accessing the original properties.*

 

### this.filesSrc

 

In a multi task, all `src` files specified via any [file format](../configuring-tasks#files) are reduced to a single array. If your task is "read only" and doesn't care about destination filepaths, use this array instead of `this.files`.

 

This example shows how a simple "lint" task might use the `this.filesSrc` property:

 

```
// Lint specified files.
var files = this.filesSrc;
var errorCount = 0;
files.forEach(function(filepath) {
  if (!lint(grunt.file.read(filepath))) {
    errorCount++;
  }
});

// Fail task if errors were logged.
if (errorCount > 0) { return false; }

// Otherwise, print a success message.
grunt.log.ok('Files lint free: ' + files.length);
```

 

### this.data

 

In 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"`.

 

*It is recommended that `this.options` `this.files` and `this.filesSrc` are used instead of `this.data`, as their values are normalized.*

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/inside-tasks](https://gruntjs.com/api/inside-tasks)

---

## Section: api/grunt.util

# grunt.util

Miscellaneous utilities for your Gruntfile and tasks.

 

### grunt.util.kindOf

 

Return the "kind" of a value. Like `typeof` but returns the internal `[Class](Class/)` value. Possible results are `"number"`, `"string"`, `"boolean"`, `"function"`, `"regexp"`, `"array"`, `"date"`, `"error"`, `"null"`, `"undefined"` and the catch-all `"object"`.

 

```
grunt.util.kindOf(value)
```

 

### grunt.util.error

 

Return a new Error instance (that can be thrown) with the appropriate message. If an Error object is specified instead of `message` that object will be returned. Also, if an Error object is specified for `origError` and Grunt was run with the `--stack` option, the original Error stack will be dumped.

 

```
grunt.util.error(message [, origError])
```

 

### grunt.util.linefeed

 

The linefeed character, normalized for the current operating system. (`\r\n` on Windows, `\n` otherwise)

 

### grunt.util.normalizelf

 

Given a string, return a new string with all the linefeeds normalized for the current operating system. (`\r\n` on Windows, `\n` otherwise)

 

```
grunt.util.normalizelf(string)
```

 

### grunt.util.recurse

 

Recurse through nested objects and arrays, executing `callbackFunction` for each non-object value. If `continueFunction` returns `false`, a given object or value will be skipped.

 

```
grunt.util.recurse(object, callbackFunction, continueFunction)
```

 

### grunt.util.repeat

 

Return string `str` repeated `n` times.

 

```
grunt.util.repeat(n, str)
```

 

### grunt.util.pluralize

 

Given `str` of `"a/b"`, If `n` is `1`, return `"a"` otherwise `"b"`. You can specify a custom separator if '/' doesn't work for you.

 

```
grunt.util.pluralize(n, str, separator)
```

 

### grunt.util.spawn

 

Spawn a child process, keeping track of its stdout, stderr and exit code. The method returns a reference to the spawned child. When the child exits, the `doneFunction` is called.

 

```
grunt.util.spawn(options, doneFunction)
```

 

The `options` object has these possible properties:

 

```
var options = {
  // The command to execute. It should be in the system path.
  cmd: commandToExecute,
  // If specified, the same grunt bin that is currently running will be
  // spawned as the child command, instead of the "cmd" option. Defaults
  // to false.
  grunt: boolean,
  // An array of arguments to pass to the command.
  args: arrayOfArguments,
  // Additional options for the Node.js child_process spawn method.
  opts: nodeSpawnOptions,
  // If this value is set and an error occurs, it will be used as the value
  // and null will be passed as the error value.
  fallback: fallbackValue
};
```

 

The `doneFunction` accepts these arguments:

 

```
function doneFunction(error, result, code) {
  // If the exit code was non-zero and a fallback wasn't specified, an Error
  // object, otherwise null.
  error
  // The result object is an object with the properties .stdout, .stderr, and
  // .code (exit code).
  result
  // When result is coerced to a string, the value is stdout if the exit code
  // was zero, the fallback if the exit code was non-zero and a fallback was
  // specified, or stderr if the exit code was non-zero and a fallback was
  // not specified.
  String(result)
  // The numeric exit code.
  code
}
```

 

### grunt.util.toArray

 

Given an array or array-like object, return an array. Great for converting `arguments` objects into arrays.

 

```
grunt.util.toArray(arrayLikeObject)
```

 

### grunt.util.callbackify

 

Normalizes both "returns a value" and "passes result to a callback" functions to always pass a result to the specified callback. If the original function returns a value, that value will now be passed to the callback, which is specified as the last argument, after all other predefined arguments. If the original function passed a value to a callback, it will continue to do so.

 

```
grunt.util.callbackify(syncOrAsyncFunction)
```

 

This example might better illustrate:

 

```
function add1(a, b) {
  return a + b;
}
function add2(a, b, callback) {
  callback(a + b);
}

var fn1 = grunt.util.callbackify(add1);
var fn2 = grunt.util.callbackify(add2);

fn1(1, 2, function(result) {
  console.log('1 plus 2 equals ' + result);
});
fn2(1, 2, function(result) {
  console.log('1 plus 2 equals ' + result);
});
```

 

## Internal libraries

 

### grunt.util.namespace

 

An internal library for resolving deeply-nested properties in objects.

 

### grunt.util.task

 

An internal library for task running.

 

## External libraries

 

*Deprecated*

 

**All external libraries that are listed below are now deprecated.**

 

Please use **npm** to manage these external libraries in your project's dependencies.

 

For example if you want to use [Lo-Dash](https://www.npmjs.org/package/lodash), install it first: `npm install lodash`, then use it in your `Gruntfile`: `var _ = require('lodash');`.

 

#### grunt.util._

 

*Deprecated*

 

[Lo-Dash](http://lodash.com/) and [Underscore.string](https://github.com/epeli/underscore.string)

 

`grunt.util._.str` is available for methods that conflict with existing Lo-Dash methods.

 

#### grunt.util.async

 

*Deprecated*

 

[Async](https://github.com/caolan/async) - Async utilities for node and the browser.

 

#### grunt.util.hooker

 

*Deprecated*

 

[JavaScript Hooker](https://github.com/cowboy/javascript-hooker) - Monkey-patch (hook) functions for debugging and stuff.

  

    &copy; GruntJS Team
Licensed under the MIT License.

    [https://gruntjs.com/api/grunt.util](https://gruntjs.com/api/grunt.util)

--- METRICS ---
- Files Extracted: 2
- Estimated Token Budget: ~36582 tokens
- Recency Window: Active (< 180 days)
- Canonical Reference: https://codewiki.google/github.com/gruntjs/grunt
