gpt4 book ai didi

javascript - 如何将参数从 gulp 观察者传递给任务

转载 作者:搜寻专家 更新时间:2023-10-31 23:26:07 26 4
gpt4 key购买 nike

如果我有这样的观察者:

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 任务?

最佳答案

作为练习,我相信我已经按照您的要求进行了工作。但首先让我说限制源管道的传统方法是使用类似 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 watch running multiple times上面代码中提到。

输出(我的 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

关于javascript - 如何将参数从 gulp 观察者传递给任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52430858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com