【问题标题】:Grunt.js grunt-contrib-watch event not firing grunt.task.runGrunt.js grunt-contrib-watch 事件未触发 grunt.task.run
【发布时间】:2014-06-17 02:30:01
【问题描述】:

我有一个使用“grunt-contrib-watch”和“grunt-exec”的 Grunt.js 文件,原因是我想以独特的方式使用把手预编译器的一些自定义功能。

代码:

module.exports = function(grunt) {

    grunt.initConfig({
        watch: {
            src: {
                files: ['**/*.hbs']
            }
        },
        exec: {
            preCompileTemplate: {
                cmd: function(inputFile) {

                    grunt.log.writeln('DERP DERP' + inputFile);

                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-exec');

    grunt.event.on('watch', function(action, filepath, target) {
        grunt.task.run('exec:preCompileTemplate:' + filepath);
        grunt.log.writeln('-------> ' + filepath);
        grunt.log.writeln('-------> ' + target);
    });

}

我在运行 grunt watch 然后更改 .hbs 文件时遇到的问题,2 grunt.log.writeln------> 按预期回显到控制台。

问题是grunt.task.run 似乎永远不会运行,因为带有DERP DERP DERP 的控制台日志永远不会出现。

我不能在 grunt-contrib-watcher 中运行任务吗?我做错了吗?

【问题讨论】:

  • 您可以让grunt.event.on 用于监视事件,每次触发时重新配置您的watch 任务的src 选项并使用spawn: false 选项。 here 描述的使用示例。
  • miqid - 我使用了您的解决方案,生成选项很好。想要将其作为答案,以便我可以将其作为找到此页面的人的解决方案?

标签: javascript gruntjs grunt-contrib-watch


【解决方案1】:

我只是想在文件发生变化时上传一些文件,但在你和 miqid 以及那里大量阅读 shama 的 cmets 之间,我确实找到了一种方法。我想它也应该是你想要的,

var watched_files = 'src/**/*';
var my_command = 'echo ';
module.exports = function(grunt) {
  grunt.initConfig({
    watch: {
      scripts: {
        files: watched_files,
        tasks: ['exec:whatever'],
        options: {
          spawn: false,
        },
      },
    },
    exec: {
      whatever: {
        cmd: function() {
          var fn = this.config.get('exec.current_file');
          return my_command + '"' + fn + '"';
        }
      },
    },
  });
  grunt.loadNpmTasks('grunt-exec');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.event.on('watch', function(action, filepath) {
    grunt.config('exec.current_file', filepath);
  });
};

现在,我对 grunt 很陌生(比如,今晚学习它),所以 也许我肯定缺少一些聪明或重要的东西,但这让我有一种方法来运行 curl对刚刚通过运行 grunt watch 更改的文件执行命令。

【讨论】:

    【解决方案2】:

    您需要在grunt.initConfig 中配置您的任务。你可以在他们的官方网站上看到more

    grunt.initConfig({
        jshint: {
          files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
          options: {
            globals: {
              jQuery: true
            }
          }
        },
        watch: {
          files: ['<%= jshint.files %>'],
          tasks: ['jshint', 'yourAwasomeTask']
        }});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多