How to use grunt

Comprehensive grunt code examples:

How to use grunt.unique:

21
22
23
24
25
26
27
28
29
});
options.compareAgainst = options.compareAgainst || '';

var sanitizePath = function (name, patterns) {
  var unwanted = [];
  unwanted = _.unique(_.flatten(_.union([], unwanted, options.srcSanitize || [])));
  var re = new RegExp('(?:' + unwanted.join('|') + ')[-_]?', 'g');
  return name.replace(re, '');
};

How to use grunt.difference:

71
72
73
74
75
76
77
78
79
80
grunt.verbose.writeln(_.flatten(comparison).length);


var discrepancy = {};
var difference = options.namespace || 'difference';
discrepancy[difference] = _.difference(_.flatten(srcMatches.total), _.flatten(comparison)).sort();

grunt.verbose.writeln(discrepancy[difference].length);

grunt.file.write(f.dest, JSON.stringify(discrepancy, null, 2));

How to use grunt.opts:

107
108
109
110
111
112
113
114
115

gr._current = NULL;
gr._noerror = TRUE;

// File base read
var pkgfile = argv.opts.config || gr._packagef;
if(fs.existsSync(pkgfile)) {
  grunt.config(Const.GruntPkg, grunt.file.readJSON(pkgfile));
}

How to use grunt.src:

221
222
223
224
225
226
227
228
229
230
```js
var gulp = require('gulp');
var remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul');

gulp.task('remap-istanbul', function () {
        return gulp.src('coverage-final.json')
                .pipe(remapIstanbul())
                .pipe(gulp.dest('coverage-remapped.json'));
});
```

How to use grunt.warn:

206
207
208
209
210
211
212
213
214
215
  } else {
    combined.errors[prop] = namespace;
  }
} else {
  if (combined.errors[prop] && combined.errors[prop] !== errors[prop]) {
    grunt.warn('[collect-errors] Duplicate minErr codes don\'t match!');
  } else {
    combined.errors[prop] = errors[prop];
  }
}

How to use grunt.help:

100
101
102
103
104
105
106
107
108
109
};

grunt.help.templates = function() {
  grunt.log.header('Available templates');
  if (templates.length > 0) {
    grunt.help.table(templates);
  } else {
    grunt.log.writeln().writeln('(No templates found)');
  }
  grunt.log.writeln().writelns(

How to use grunt.each:

110
111
112
113
114
115
116
117
118
119
    fileDepth = relativeFileDir.split('/').length;
}

var baseDirs = filepath.substr(baseDir.length).split('/');

_.each(assetMap, function(hashed, original) {
    var replace = [
        // abs path
        ['/' + original, '/' + hashed],
        // relative

How to use grunt.utils:

6
7
8
9
10
11
12
13
14
15

grunt.npmTasks([
  'enyo'
]);

var _ = grunt.utils._;
var template = grunt.template.process;

// Draw the help screen.
function displayHelp(withFlags) {

How to use grunt.renameTask:

271
272
273
274
275
276
277
278
279
280

```javascript
var grunt = require('grunt');

module.exports = function() {
  grunt.renameTask('mochaTest', 'mocha');
  return {
    test: ['mocha'],
    w: ['build', 'doStuff', 'mocha', 'watch']
  };

How to use grunt.template:

7
8
9
10
11
12
13
14
15
16
grunt.npmTasks([
  'enyo'
]);

var _ = grunt.utils._;
var template = grunt.template.process;

// Draw the help screen.
function displayHelp(withFlags) {
  var pkg = require(path.normalize(__dirname + '/../package.json'));

How to use grunt.registerMultiTask:

16
17
18
19
20
21
22
23
24
var _ = grunt.util._;
var defaultEnv = {};

function init(grunt)
{
    grunt.registerMultiTask('devcode', 'Remove code blocks based on environment configuration', function()
    {
        var context = _.extend({},defaultEnv,process.env), files;
        context.NODE_ENV = context.NODE_ENV || 'development';

How to use grunt.clone:

36
37
38
39
40
41
42
43
44
45
  'bower_components/angular/angular.js',
  files.source,
  files.allPartialsCombined
);

var demoEnvironment = _.clone(baseEnvironment);
var karmaEnvironment = _.clone(baseEnvironment);

karmaEnvironment.unshift('bower_components/jasmine-moar-matchers/lib/*.js');
karmaEnvironment.push('bower_components/angular-mocks/angular-mocks.js');

How to use grunt.fatal:

36
37
38
39
40
41
42
43
44
45

cachedAngularFiles.forEach(function(f) {
  var filePath = path.join('lib', 'test', 'angular', version, f);

  if (! fs.existsSync(filePath)) {
    grunt.fatal("Angular file " + filePath + " doesn't exist");
  }

  retFiles.push(filePath);
});

How to use grunt.initConfig:

37
38
39
40
41
42
43
44
45
        // Load custom tasks
        grunt.loadTasks('./tasks');

        var config = loadConfig('./tasks/options');

        grunt.initConfig(config);

        console.log(grunt.config());
};

How to use grunt.loadTasks:

30
31
32
33
34
35
36
37
38
39
      outputDirectory: outputDirectory
    }
  }
});

grunt.loadTasks(path.join(__dirname, '..', 'tasks'));

let tasksDone = false;

grunt.registerTask('done', 'done', function () {

How to use grunt.verbose:

62
63
64
65
66
67
68
69
70
71
this.options = function() {
  var args = [{}].concat(grunt.util.toArray(arguments)).concat([
    grunt.config([name, 'options'])
  ]);
  var options = grunt.util._.extend.apply(null, args);
  grunt.verbose.writeflags(options, 'Options');
  return options;
};
// If this task was an alias or a multi task called without a target,
// only log if in verbose mode.

How to use grunt.cli:

44
45
46
47
48
49
50
51
52
53
  grunt.cli.tasks = ['init'];
} else {
  name = grunt.cli.tasks[0];
  // For the specified "task" prepend "init:" so the init task doesn't
  // actually need to be specified on the command line.
  grunt.cli.tasks = ['init:' + name];
}

// Remove grunt options that don't really make any sense for grunt-init.
[

How to use grunt.loadNpmTasks:

26
27
28
29
30
31
32
33
34
35
        return object;
}

module.exports = function(grunt) {
        // Load grunt tasks automatically
        // No need for grunt.loadNpmTasks('some-package');
        require('load-grunt-tasks')(grunt);

        // Time how long tasks take. Can help when optimizing build times
        require('time-grunt')(grunt);

How to use grunt.tasks:

32
33
34
35
36
37
38
39
40
41
  }else{
    fs.exists(filePath, function(result){
      if(result){
        readFromBuild()
      }else{
        grunt.tasks(buildTask, {}, readFromBuild);
      }
    });
  }
}

How to use grunt.fail:

2
3
4
5
6
7
8
9
10

module.exports = {
  execSpecsInNode: function() {
    var exit_code = shell.exec("node spec/node_suite.js --color=true").code;
    if (exit_code !== 0) {
      grunt.fail.fatal("Specs Failed", exit_code);
    }
  }
};

How to use grunt.registerTask:

34
35
36
37
38
39
40
41
42
43

grunt.loadTasks(path.join(__dirname, '..', 'tasks'));

let tasksDone = false;

grunt.registerTask('done', 'done', function () {
  tasksDone = true;
});

grunt.task.run(['create-windows-installer', 'done']).start();

How to use grunt.task:

38
39
40
41
42
43
44
45
46
47

grunt.registerTask('done', 'done', function () {
  tasksDone = true;
});

grunt.task.run(['create-windows-installer', 'done']).start();

waitsFor(30000, function () {
  return tasksDone;
});

How to use grunt.option:

13
14
15
16
17
18
19
20
21

if (options) {
  for (var key in options) {
    baseOptions[key] = options[key];
    if(key != 'base' && key != 'prefix'){
      grunt.option(key, options[key]);
    }
  }
}

How to use grunt.util:

How to use grunt.config:

20
21
22
23
24
25
26
27
28
29

function existsFileInOutput(filename) {
  return fs.existsSync(path.join(outputDirectory, filename));
}

grunt.config.init({
  pkg: grunt.file.readJSON(path.join(__dirname, 'fixtures', 'app', 'resources', 'app', 'package.json')),
  'create-windows-installer': {
    config: {
      appDirectory: path.join(__dirname, 'fixtures', 'app'),

How to use grunt.log:

80
81
82
83
84
85
86
87
88
89
if (loadPath !== '' &&
    !grunt.util._.contains(this.filesLoadedSoFar, loadPath) &&
    !grunt.util._.contains(this.beingLoaded, loadPath)) {
  currentDepth.push(" ");
  if (this.printDepGraph) {
    grunt.log.writeln(currentDepth.join("") + className);
  }
  this.beingLoaded.push(loadPath);
  try {
      eval(grunt.file.read(loadPath));

How to use grunt.file:

51
52
53
54
55
56
57
58
59
60
BowerAssets.prototype = Object.create(Emitter.prototype);
BowerAssets.prototype.constructor = BowerAssets;

BowerAssets.prototype.get = function() {
  var bower = this.bower;
  var bowerConfig = grunt.file.readJSON(path.join(this.cwd, this.config));
  var exportsOverride = bowerConfig.exportsOverride;

  var paths = bower.commands.list({paths: true});
  paths.on('end', function(data) {