在Gruntfile中使用JavaScript库

时间:2014-11-23 16:13:47

标签: node.js gruntjs

我是Grunt的新手,我正在尝试使用grunt-bower-concat节点模块将我的所有bower组件分别连接到单个js文件和css文件中。它工作得很好,除了我想迫使grunt-bower-concat使用我的bower组件的缩小版本而不是未压缩版本。

幸运的是,它带有一个callback feature我可以自定义:

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;
  });
}

我将它添加到我的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;
                    });
                }
            }
        },
...

它失败并出现以下错误:

$ /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

此示例尝试使用underscore's map function,很明显Grunt无权访问此库。

如何加载下划线或在我的Gruntfile中使用它的函数?

2 个答案:

答案 0 :(得分:4)

不需要额外的库,只需替换

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

有了这个:

return mainFiles.map(function(filepath) {

答案 1 :(得分:3)

除非您没有显示整个文件,否则您在任何地方都不需要下划线。

您要在其中使用下划线的任何文件:

var _ = require('underscore');

在使用_之前。

哦,当然你需要在gruntfile所在的文件夹中npm install underscore --save,以便在那里拥有库。