Как передать аргумент от наблюдателя глотка задаче

Если у меня есть наблюдатель, как это:

gulp.watch('js/**/*.js').on('change', path => {
  gulp.series(build, reload)();
});

... и задача build будет выглядеть так:

const build = done => {
  return gulp
    .src(path) // Use "path" here
    .pipe(
      rename({
        dirname: ''
      })
    )
    .pipe(uglify())
    .pipe(gulp.dest('build'));
};

Как я могу пройти path аргумент build задача?

1 ответ

Как упражнение, я считаю, что я получил это работает, как вы хотели. Но сначала позвольте мне сказать, что традиционный способ ограничения исходного конвейера будет что-то вроде gulp-newer. Вы должны увидеть, выполняет ли это то, что вы хотите.

Но вот кое-что, что может работать для вас [не очень хорошо проверено!]:

function build (path)  {
  return new Promise(resolve => {

    // using setTimeout() to prove async/await is working as expected
    setTimeout(() => {
      resolve('resolved');
    }, 2000);

    // put your gulp.src pipeline here using 'path'
    console.log("2 path = " + path);
  });
};

function anotherTask (path)  {
  return new Promise(resolve => { 

    // put your gulp.src pipeline here
    console.log("4 path = " + path); });
};

function testWatch () {

  console.log("in testWatch");

  // debounceDelay because gulp likes to call the watcher 2 or 3times otherwise
  //  see [gulp watch task running multiple times when a file is saved][2]

  var watcher = gulp.watch('js/**/*.js', { debounceDelay: 2000 });

  // I added the async/await because I wasn't sure those functions would be run in series
  //  as you wanted.

  // With the event listener route I couldn't get gulp.series to work, 
  //  so went with async/await.

  watcher.on('change', async function(path, stats) {

    console.log('1 File ' + path + ' was changed');
    await build(path);
    console.log("3 after build");

    // I would assume that the **last** task in the chain doesn't need 'await'
    // or to return a promise as in anotherTask

    await anotherTask(path);
    console.log("5 after anotherTask");
  });
};

gulp.task('default', gulp.series(testWatch));

Часы gulp работают несколько раз, как указано выше в коде.

Вывод (мой js watch src отличается от вашего):

in testWatch
1 File src\js\main.js was changed
2 path = src\js\main.js
3 after build
4 path = src\js\main.js
5 after anotherTask
1 File src\js\taxonomy.js was changed
2 path = src\js\taxonomy.js
3 after build
4 path = src\js\taxonomy.js
5 after anotherTask
Другие вопросы по тегам