【问题标题】:Prevent `grunt-watch` from looping when there is a syntax error in less files?当较少文件中存在语法错误时,防止`grunt-watch`循环?
【发布时间】:2013-12-16 03:46:54
【问题描述】:

我正在使用grunt-watch 重新构建我的less 样式表:

    watch: {
        less: {
            files: ['media/less/**/*.less'],
            tasks: ['less'],
            options: {
                atBegin: true,
                spawn: false
            }
        }
    }

但是,如果任何.less 文件中存在语法错误,任务就会循环,尝试每秒重新构建.less 文件……这使得调试相当困难,因为错误消息滚动过去非常很快。

有什么办法可以解决这个问题,所以grunt-watch 只会在再次更改.less 文件后重新运行任务?

这是使用:

grunt@0.4.2
grunt-contrib-less@0.8.3
grunt-contrib-watch@0.5.3

【问题讨论】:

    标签: gruntjs grunt-contrib-watch


    【解决方案1】:

    我认为您描述的问题是this one,它已在 master 中修复但尚未发布(截至 2013 年 12 月 17 日)。

    【讨论】:

    • 是的,就是这样。当我设置spawn: true 时,一切似乎都按预期工作。谢谢!
    【解决方案2】:

    好吧,出于调试目的,您可以使用自定义任务对 less 任务进行简单的封装:

    grunt.registerTask('myless', 'my less task', function() {
      // do whatever debugging you want and stop the loop if needed.
      grunt.task.run(['less']);
    });
    

    然后在watch 中使用您的myless 任务。

    更新:

    这个想法是,由于任何对less 的重复调用现在都会通过您的代码 - 如果失败是“预期”结果并且应该失败,您可以执行任何需要的操作来提供更具体的输出或防止重复调用,但不是循环。

    更新 2:

    类似这样的:

    watch: {
        `less`: {
            files: ['**/*.less'],   // or whatever the extension is
            tasks: ['myless']       // your envelope task
        }
    }
    
    var flag;
    
    grunt.registerTask('myless', 'My LESS task', function() {
        if(flag === true) {
            // if you are here - it means watch just invoked you repeatedly
            // do whatever you need to analyze the issue (includig running an additional task)
    
            flag = false;
            return; // you exit task without altering any less files again - 
                    // that should NOT trigger watch again
        } else {
            flag = true;
            grunt.task.run(['less']);
        }
    });
    

    【讨论】:

    • 请原谅我太密集了(我对 Grunt 和朋友们还是很陌生),但是如果 less 构建失败,这将如何防止 grunt watch 任务循环呢?如何判断 less 编译是否失败?
    • 这个想法是,在 myless 任务的函数处理程序中 - 将被 watch 任务连续调用 - 你可以做任何你需要的打印输出,提供一些关于为什么会发生这种情况的信息.你,因为它是同一个 grunt 进程和实例,理论上可以防止从 你的 任务重复调用less。
    • 对……但是我如何判断less编译是否失败?看起来grunt.task.run(…) 没有返回任何有用的东西。另外,如何防止 grunt-watch 重新运行任务,直到文件再次更改?
    • 查看我的更新。记住 - grunt 和所有的朋友最终都只是 JavaScript - 所以你可以做很多事情,比如动态启用或禁用“监视”任务,使用 grunt.config API。
    • 很抱歉,我认为您描述的解决方案不适合我的问题。具体来说,我遇到的问题似乎是一个错误(请参阅已接受的答案)。
    猜你喜欢
    • 2015-07-30
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    相关资源
    最近更新 更多