我有一些使用plop.js修改特定文件的gulp任务。如果我自己运行任务,它们就可以正常工作。
现在我有一个包装器任务,在此我提示用户他要执行哪些任务,然后我想使用gulp.series()
。
它们都起作用,但是对于那些需要修改相同源文件的任务,它将仅应用第一个修改。好像任务没有真正真正地顺序执行,允许第一个更改完成然后传递给第二个...
这里是一些代码:
const gulp = require('gulp')
const strings = {
polyfill: `polyfill-string-which-is-added-to-file`, // I simplified this one
modernizr: `{ src: '/js/modernizr-custom.js', async: true, defer: true }`
}
/*
* Replace specific comments with a string
* Using plop modify actions
*/
function replaceComment(path, template, pattern) {
console.log(`🧾 Replacing ${pattern} in ${path}...`)
const nodePlop = require('node-plop')
const plop = nodePlop()
const generator = plop.setGenerator('replace', {
prompts: [],
actions: [
{
type: 'modify',
path,
pattern,
template
}
]
})
generator
.runActions()
.then(results => {
console.log(`💾✅ Sucessfully modified ${path} with ${template}`)
})
.catch(err => {
console.log('err', err)
})
}
gulp.task('add-polyfill', function(done) {
console.log('Adding IE11 polyfill to nuxt.config.js ...')
const path = './nuxt.config.js'
const pattern = '\/\*\ setup-autocomment-polyfill\ \*\/' // eslint-disable-line
const template = strings.polyfill
replaceComment(path, template, pattern)
done()
})
gulp.task('add-modernizr', function(done) {
console.log('Adding modernizr script to nuxt.config.js ...')
const path = './nuxt.config.js'
const pattern = '\/\*\ setup-autocomment-modernizr\ \*\/' // eslint-disable-line
const template = strings.modernizr
replaceComment(path, template, pattern)
done()
})
gulp.task('setup', function(done) {
return gulp.series('add-modernizr' , 'add-polyfill')(done)
})
如果有人能在这里给我指点,我将非常高兴。我是否必须更多地履行承诺?还是为什么gulp.series并没有真正做一个系列中的事情-我的意思是任务要自己完成...
预先致谢,谢谢
好吧,我发现了问题所在。确实,这是有希望的事情。函数replaceComment()
已启动,但在done()
完成之前调用了replaceComment()
。因此,我不得不等待replaceComment()
返回一个仅在修改完成后解决的Promise:
function replaceComment(path, template, pattern) {
return new Promise((resolve, reject) => {
console.log(`🧾 Replacing ${pattern} in ${path}...`)
const nodePlop = require('node-plop')
const plop = nodePlop()
const generator = plop.setGenerator('replace', {
prompts: [],
actions: [
{
type: 'modify',
path,
pattern,
template
}
]
})
generator
.runActions()
.then(results => {
console.log(`💾✅ Sucessfully modified ${path} with ${template}`)
resolve()
})
.catch(err => {
console.log('err', err)
reject(err)
})
})
}
然后为每个任务添加异步等待:
gulp.task('add-polyfill', async function(done) {
console.log('Adding IE11 polyfill to nuxt.config.js ...')
const path = './nuxt.config.js'
const pattern = '\/\*\ setup-autocomment-polyfill\ \*\/' // eslint-disable-line
const template = strings.polyfill
await replaceComment(path, template, pattern)
done()
})
欢呼声