javascript - grunt.registerTask 不能修改全局的 grunt 任务设置

标签 javascript node.js gruntjs

下面的代码读取app/modules/中的每个子目录js的内容(例如app/modules/module1/js/, app/modules/module2/js/, aso.)

此脚本在不使用最后一个命令 grunt.task.run('concat:' + dir); 之前运行。 有一段时间它停止工作,所以我不得不在 forEach 循环内添加对任务 concat 的调用。

通常我会将新配置保存在 concat 配置中,并在稍后调用生成的 concat 任务。

grunt.registerTask('preparemodulejs', 'iterates over all module directories and compiles modules js files', function() {

    // read all subdirectories from your modules folder
    grunt.file.expand('./app/modules/*').forEach(function(dir){

        // get the current concat config
        var concat = grunt.config.get('concat') || {};

        // set the config for this modulename-directory
        concat[dir] = {
            src: [dir + '/js/*.js', '!' + dir + '/js/compiled.js'],
            dest: dir + '/js/compiled.js'
        };

        // save the new concat config
        grunt.config.set('concat', concat); 
        grunt.task.run('concat:' + dir); // this line is new

    });

});

我必须添加显式 task.run 行的最新版本到底发生了什么变化?

有什么方法可以将此任务的设置写入现有 concat 任务的设置中,这样如果我对该配置进行其他手动添加,这些设置将不会针对扫描的每个目录运行?

感谢您的帮助。

最佳答案

grunt.task.run(); 尽管名称如此,但并不运行任务。 Grunt 始终是同步的,因此 grunt.task.run()排队任务以在当前任务完成后运行。

所以我会避免在数组中使用 grunt.task.run() 而是构建一个任务/目标列表以在之后运行:

grunt.registerTask('preparemodulejs', 'iterates over all module directories and compiles modules js files', function() {
  var tasks = [];

  // read all subdirectories from your modules folder
  grunt.file.expand('./app/modules/*').forEach(function(dir){

    // get the current concat config
    var concat = grunt.config.get('concat') || {};

    // set the config for this modulename-directory
    concat[dir] = {
      src: [dir + '/js/*.js', '!' + dir + '/js/compiled.js'],
      dest: dir + '/js/compiled.js'
    };

    // save the new concat config
    grunt.config.set('concat', concat); 
    tasks.push('concat:' + dir);
  });

  // queues the tasks and run when this current task is done
  grunt.task.run(tasks);
});

关于javascript - grunt.registerTask 不能修改全局的 grunt 任务设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20284764/

相关文章:

javascript - 将 div 放置在具有起始 Angular 和结束 Angular 圆周围

javascript - 剑道图表工具提示始终在屏幕上

javascript - 检查元素的祖先是否固定

node.js - 如何将 Angular(前端)和 Node.js(服务器)应用程序打包在一起

javascript - node.js 打开文件覆盖现有文件

node.js - 用于 Mocha 测试的 Grunt : How to correctly setup . html 文件?

javascript - 页面预加载器加载较晚

javascript - 无法创建具有数组作为属性的对象

node.js - 如何使用 grunt 连接 angularjs 文件

node.js - grunt 命令如何工作?