在下面的代码中,fileShouldBePreprocessedBySass()
将在console.log('intercepted!');
执行前调用。此外,在 中fileShouldBePreprocessedBySass(targetFileAbsolutePath)
,参数targetFileAbsolutePath
将是undefined
:
let currentSourceFileAbsolutePath;
return gulp.src(entryPointsSourceFilesPathsOrGlobs)
// "gulpPlugins.intercept" is "gulp-intercept"
.pipe(gulpPlugins.intercept( sourceVynilFile => {
console.log('intercepted!');
currentSourceFileAbsolutePath = sourceVynilFile.path;
console.log(currentSourceFileAbsolutePath); // OK here
return sourceVynilFile;
}))
// "gulpPlugins.if" is "gulp-if"
.pipe(gulpPlugins.if(
// currentSourceFileAbsolutePath is undefined !!!
fileShouldBePreprocessedBySass(currentSourceFileAbsolutePath),
gulpPlugins.sass()
));
// ...
fileShouldBePreprocessedBySass(targetFileAbsolutePath) {
console.warn('---');
console.warn(targetFileAbsolutePath); // undefined!
const targetFilenameExtension = Path.extname(targetFileAbsolutePath);
let targetFilenameExtensionIsSupportedBySassPreprocessor = false;
for (const filenameExtension of SUPPORTED_FILENAME_EXTENSIONS__SASS_PREPROCESSOR) {
if (filenameExtension === targetFilenameExtension) {
targetFilenameExtensionIsSupportedBySassPreprocessor = true;
break;
}
}
return targetFilenameExtensionIsSupportedBySassPreprocessor;
}
真的,原始代码是用 TypeScript 编写的,但我将其重写为 JavaScript 以让更多人理解代码。我之所以这么说是因为 TypeScript 编译器以某种方式理解,pipe(gulpPlugins.if(/*...*/))
参数currentSourceFileAbsolutePath
没有初始化,所以发生了TS2454: Variable 'currentSourceFileAbsolutePath' is used before being assigned.
错误。
我很困惑,因为我有类似的任务可以正常工作(按正确的顺序):
let currentSourceFileAbsolutePath: string;
return gulp.src(entryPointsSourceFilesPathsOrGlobs)
.pipe(gulpPlugins.intercept(sourceVynilFile => {
currentSourceFileAbsolutePath = sourceVynilFile.path;
return sourceFile;
}))
.pipe(gulpPlugins.pug())
.pipe(gulpPlugins.intercept(compiledHtmlFile => {
// currentSourceFileAbsolutePath is NOT undefined!
if (shouldValidateCompiledHtmlRespectiveToSourceFile(currentSourceFileAbsolutePath)) {
HtmlValidator.validateHtml(compiledHtmlFile);
}
return compiledHtmlFile;
}))
.pipe(gulp.dest(() => (
// currentSourceFileAbsolutePath is NOT undefined!
getOutputDirectoryForPreprocessedMarkupEntryPointFileByRespectiveSourceFile(currentSourceFileAbsolutePath)
)));
第一个任务有什么问题?我错过了一些异步呼叫?