【问题标题】:load-grunt-configs and bower.install() using grunt使用 grunt 加载 grunt-configs 和 bower.install()
【发布时间】:2015-01-25 15:28:52
【问题描述】:

我正在尝试将现有的 Gruntfile 分成更小的文件,以便更轻松地进行概述。然而,我遇到了一个颠簸。我正在使用 bower.install 来安装我的项目依赖项。 我的文件夹结构如下所示:

package.json
bower.json
config
--install.js
--default.js //Empty for now
gruntfile.js

我的 Gruntfile 现在看起来像这样:

'use strict';
module.exports = function(grunt) {
  var npmDependencies = require('./package.json').devDependencies;
  require('load-grunt-tasks')(grunt);

  var configs = {
    config : {
      paths : {
        "build" : ["grunts/*.js*", "package.json", "bower.json", "Gruntfile.js"],
      }
    }
  };

  var loadConfigs = require( 'load-grunt-configs' );
  configs = loadConfigs( grunt, configs );
  // Project configuration.
  grunt.initConfig( configs );
}

我的 install.js 看起来像这样:

module.exports = function(grunt) {
  var done = grunt.async();
  var bower = require('bower').commands;
  bower.install().on('end', function(data) {
    done();
  }).on('data', function(data) {
    console.log(data);
  }).on('error', function(err) {
    console.error(err);
    done();
  });
}

但是这不起作用,因为我收到了错误:

>> TypeError: Object #<Object> has no method 'async'

如果我删除所有异步混乱(我最终想要保留),那么文件看起来会简单很多:

module.exports = function(grunt) {
    var bower = require('bower').commands;
    bower.install();
}

我仍然收到以下错误:

>> TypeError: Cannot call method 'hasOwnProperty' of undefined

我对这个主题相当陌生,到目前为止(将所有内容都放在一个文件中)它运行良好。现在的大问题:我如何回到那个点;)

【问题讨论】:

    标签: javascript node.js gruntjs bower


    【解决方案1】:

    install.js 有几个问题:

    1) grunt 对象没有暴露异步函数,这是第一个错误的原因。 async 函数可用于 grunt 任务,因此应从任务中调用它。
    2) 当using node modules for configuration 时,load-grunt-configs 需要一个返回对象的函数,例如:

    //config/jshint.js
    module.exports = function(grunt, options){
         return {
             gruntfile       : {
                 src : "Gruntfile.js"
             }
         }
     } 
    

    在您的情况下,该函数不返回任何内容,并且 load-grunt-configs 失败并出现 Cannot call method 'hasOwnProperty' of undefined 错误。

    以下应该有效:

    module.exports = function(grunt) {
      return grunt.registerTask("bower", function() {
          var done = this.async();
          var bower = require('bower').commands;
          bower.install().on('end', function(data) {
            done();
          }).on('data', function(data) {
            console.log(data);
          }).on('error', function(err) {
            console.error(err);
            done();
          });
      });
    }
    

    【讨论】:

    • 嘿,很抱歉反馈迟了。你是对的,有几件事是错的。但是:据我了解您链接的文档,您在此处显示的可能性只是一种变体。我指的是返回函数部分正上方的代码示例,示例 js 文件返回对象部分。但是不知何故,这对我不起作用。
    • @stiller_leser 我在发布之前测试了这个样本。你能指定什么不工作吗?
    • 你的代码示例对我来说完全正常(除了他找不到 bower.json 文件的问题 - 现在已修复)。有关我所指的代码示例,请参见此处:pastebin.com/idZgQ0bx - 但我现在切换到 load-grunt-config,这对我来说工作正常。很有可能,我只是在某个地方的配置中出现了一个小错误。不过感谢您的帮助!
    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    • 2014-02-17
    • 2015-05-19
    • 1970-01-01
    • 2013-12-18
    相关资源
    最近更新 更多