mykisscool
mykisscool

Reputation: 872

Use JavaScript libraries inside of Gruntfile

I'm new to Grunt and I'm trying to use the grunt-bower-concat node module to concat all my bower components into a single js file and css file respectively. It's working great, except that I want to force grunt-bower-concat to use the minified versions of my bower components instead of the uncompressed versions.

Luckily, it comes with a callback feature where I can customize this:

callback: function(mainFiles, component) {
  return _.map(mainFiles, function(filepath) {
    // Use minified files if available
    var min = filepath.replace(/\.js$/, '.min.js');
    return grunt.file.exists(min) ? min : filepath;
  });
}

And I added it to my Gruntfile:

module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        bower_concat: {
            all: {
                dest: "src/js/<%= pkg.name %>-bower.js",
                cssDest: "src/css/<%= pkg.name %>-bower.css",
                callback: function(mainFiles) {
                    return _.map(mainFiles, function(filepath) {
                        var min = filepath.replace(/\.js$/, '.min.js');
                        return grunt.file.exists(min) ? min : filepath;
                    });
                }
            }
        },
...

And it fails with the following error:

$ /usr/local/bin/grunt --gruntfile /Applications/MAMP/htdocs/proj/Gruntfile.js bower_concat
Running "bower_concat:all" (bower_concat) task
Fatal error: _ is not defined
Process finished with exit code 3

This example is trying to use underscore's map function and it's clear Grunt does not have access to this library.

How can I load underscore or use it's functions inside of my Gruntfile?

Upvotes: 1

Views: 565

Answers (2)

idbehold
idbehold

Reputation: 17168

Instead of requiring an extra library, simply replace

return _.map(mainFiles, function(filepath) {

With this:

return mainFiles.map(function(filepath) {

Upvotes: 4

Paul
Paul

Reputation: 36319

Doesn't look like you required underscore anywhere, unless you're not showing the whole file.

Any file in which you want to use underscore you need to do:

var _ = require('underscore');

before making use of _.

Oh, and of course you need to npm install underscore --save in the folder the gruntfile is in as well, to have the library there.

Upvotes: 3

Related Questions