简体   繁体   English

如何在Gulp 4中将功能作为任务运行?

[英]How to run function as a task in Gulp 4?

How to run a function during a Gulp execution so that Gulp treats the function as a task (prints it to the log)? 如何在Gulp执行期间运行函数,以便Gulp将函数视为任务(将其打印到日志中)?

Here is an example of my gulpfile.js: 这是我的gulpfile.js的示例:

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  // Some asynchronous logic which gets the subtasks
  const todos = await myAPI.getTodos();

  await Promise.all(todos.map(async todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    await subTask(); // I want it to run as a Gulp task
  }));
};

Expected Gulp output: Gulp预期产量:

Starting 'default'...
Starting 'todo «foo»'...
Starting 'todo «bar»'...
Finished 'todo «foo»' after 1.2s
Finished 'todo «bar»' after 1.5s
Finished 'default' after 2s

Actual Gulp output: Gulp实际输出:

Starting 'default'...
Finished 'default' after 2s

Why: My list of subtasks can't be retrieved synchronously and Gulp doesn't support asynchronous configuration and isn't going to support it. 原因:无法同步检索我的子任务列表,并且Gulp 不支持异步配置 ,也不支持它。 Never the less I want to see the subtasks progress and timing in the Gulp output. 但是我仍然希望在Gulp输出中看到子任务的进度和计时。

Wrap the function into gulp.series or gulp.parallel to make Gulp display its status. 将函数包装到gulp.seriesgulp.parallel以使Gulp显示其状态。 It doesn't look like an elegant solution but it's the best I've found. 它看起来似乎不是一个优雅的解决方案,但这是我发现的最好的解决方案。

Here is a universal example: 这是一个通用示例:

function runGulpTask(func) {
  return new Promise((resolve, reject) => gulp.series(func)(error => {
    if (error) {
      reject(error);
    } else {
      resolve();
    }
  }));

  // The same solution using built-in Node.js functions:
  // const {promisify} = require('util');
  // return promisify(gulp.series(func))();
}

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  const todos = await myAPI.getTodos();

  await Promise.all(todos.map(async todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    await runGulpTask(subTask);
  }));
};

The Gulp output is the same as the expected output. Gulp输出与预期输出相同。

And here is a more specific example: 这是一个更具体的示例:

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  const todos = await myAPI.getTodos();

  const subTasks = todos.map(todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    return subTask;
  });

  await new Promise((resolve, reject) => gulp.parallel(...subTasks)(error => {
    if (error) {
      reject(error);
    } else {
      resolve();
    }
  }));
  // Or using built-in Node.js functions:
  // const {promisify} = require('util');
  // await promisify(gulp.parallel(...subTasks))();
};

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

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