Gulp - 确保文件开头有注释



我在一个文件夹中有多个javascript文件,我想确保每个文件在开头都有注释(这将解释文件的摘要(。

/*
This file will......
*/
function test () {
....
}

那么这可以使用 gulp-contains 或其他东西吗?

我认为这足以确保文件的开头是否是注释首字母字符(/*(

gulp.src('./file.js')
.pipe(map(function(file, callback) {
var startWithComment = file.contents.toString().replace(/n|r/g, "").trim().startsWith("/*");
if (startWithComment){
// DO YOUR CHORES
}
}))

另一种方法是拆分初始文本,以确保它是否是有效的多行注释。

function startsWithValidMultiLineComment(str){
try{
return str.replace(/n|r/g, "").trim().split("/*")[1].split("*/")[1].length > 0         
} catch (e){
return false;
}
}

遵循这种方法str.split("/*")[1].split("*/")[0]将是您的评论文本

通过使用@Sajjad在上一个答案中提供的正则表达式。我已经设法实现了我的目标。我使用了gulp-if和gulp-fail(我发现它更灵活(。

这是我的做法:

var condition = function (file) {
sFile = require('path').parse(file.path).name;
var startWithComment = file.contents.toString().replace(/n|r/g, "").trim().startsWith("/*");
return (!startWithComment);
}

gulp.task('taskName',
function() {
gulp.src('files/*.js')
.pipe(gulpIf(condition, fail(function () {
var message = 'Some message';
return message;
})));
});

最新更新