简体   繁体   English

如何将参数从gulp观察器传递给任务

[英]How to pass an argument from a gulp watcher to a task

If I have a watcher like this: 如果我有这样的观察者:

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

...and task build would look like this: ......并且任务build看起来像这样:

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

How can I pass path argument to the build task? 如何将path参数传递给build任务?

As an exercise I believe I got this working as you wanted. 作为练习,我相信我按照你的意愿工作。 But first let me say that the traditional way of limiting the source pipeline would be with something like gulp-newer . 但首先让我说,限制源管道的传统方式将是像gulp-newer这样的东西。 You should see if that accomplishes what you want. 你应该看看它是否能达到你想要的效果。

But here is something that may work for you [not well tested!]: 但是这里有一些可能对你有用的东西[未经过充分测试!]:

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 watch running multiple times mentioned above in code. gulp watch在代码中运行多次

Output (my js watch src is different than yours) : 输出(我的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM