【问题标题】:I have a for with a gulp.watch, but it doesnt work correctly我有一个带有 gulp.watch 的 for,但它不能正常工作
【发布时间】:2017-10-17 14:14:05
【问题描述】:

我需要帮助。 我有这个代码。我有很多来源,我不使用 n*source 手表。 我认为 for 可以是一个解决方案,但是手表已实例化并且它不读取我的源 [i]。

你可以说一些解决办法。

谢谢!

var base_source = '../';
var source = ['dir1', 'dir2'];
var allFiles = '/**/*';
var dest = '../dist';

gulp.task('default', function () {

      for(var i = 0; i < source.length ; i++) {
        var watchW = base_source + source[i] + allFiles;

        gulp.watch(watchW, function(obj){
          copyFiles(watchW, dest , obj);
        });

      }
    }

编辑:我需要 copyFiles 函数中的 source[i]

对不起我的英语^^"

【问题讨论】:

    标签: javascript automation gulp task gulp-watch


    【解决方案1】:

    很难解释为什么您的代码不起作用。如您所见,只有最后一个索引“i”绑定到 all 手表功能。这被称为“参考问题”。通过引用,您的所有手表功能都使用相同的索引 i。例如,请参阅referencing last index in loop

    creating gulp tasks in a loop 中使用@OverZealous 的回答作为指导,这是适合您的解决方案:

    var gulp = require('gulp');
    
    // changed to up one directory
    var base_source = './';
    
    // changed variable name slightly for clarity
    var sources = ['dir1', 'dir2'];
    var allFiles = '/**/*';
    
    // changed to up one directory
    var dest = './dist';
    
    var watchSources = Object.keys(sources);
    
    gulp.task('default', function () {
    
      watchSources.forEach(function (index) {
    
        var watchW = base_source + sources[index] + allFiles;
    
        gulp.watch(watchW, function (obj) {
          copyFiles(watchW, dest, obj);
        });
      });
    });
    
    function copyFiles(watched, to, obj)  {
      console.log("watched = " + watched);
    }
    

    【讨论】:

    • 谢谢!!你的回答和@OverZealous 的回答让我大开眼界。
    • 不客气。如果您发现我的回答正确且有帮助,请接受正确,以便其他人知道它有效。谢谢。
    猜你喜欢
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 2013-02-20
    • 2019-11-12
    • 2023-01-21
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多