我正在为 gulpfile 创建一个函数,代码如下:
var globalSourceMapInit = true;
function makeSaSSTask(taskName, src, isSourceMap, concatFileName, dest){
gulp.task(taskName, function() {
return gulp.src(src) //look for all the files in src
.pipe(plugins.sourcemaps.init()) //init the sourcemap, sourcemap help in viewing the css as it is in the style tab of inspect element
.pipe(plugins.sass().on('error', plugins.sass.logError)) //compile sass
.pipe(plugins.cssmin()) //minify it.
.pipe(plugins.autoprefixer()) //auto prefix tags like -webkit- -moz- -o- etc wherever required
.pipe(plugins.sourcemaps.write()) //write the sourcemap which was inited
.pipe(plugins.concat(concatFileName)) //concatinate all the files in /src to concatFileName
.pipe(gulp.dest(dest)); //save concatFileName to dest
});
}
现在,我想做的是:如果 isSourceMap 和 globalSourceMapInit 为真,那么它应该执行 sourcemap init,否则它不会。
我希望它是这样的:
return gulp.src(src)
(isSourceMap && globalSourceMapInit ? .pipe(plugins.sourcemaps.init()) : null)
.pipe(...)
...
...
...
...
(isSourceMap && globalSourceMapInit ? .pipe(plugins.sourcemaps.write()) : null)
.pipe(gulp.dest(dest));
如果这可能是关于我应该在三元运算符中的第三个操作数中提供什么而不是 null
的可能解决方案,或者它是否有效。
我想知道这是否是可能的解决方案以及实现此目标的其他可能和最佳方法是什么(通过使用三元运算符)。
最佳答案
只是不要试图将所有内容链接在一起。管道返回给你改变的对象。使用它:
gulp.task(taskName, function() {
var p = gulp.src(src); //look for all the files in src
if (isSourceMap && globalSourceMapInit) {
p = p.pipe(plugins.sourcemaps.init()) //init the sourcemap, sourcemap help in viewing the css as it is in the style tab of inspect element
}
p = p.pipe(plugins.sass().on('error', plugins.sass.logError)) //compile sass
.pipe(plugins.cssmin()) //minify it.
.pipe(plugins.autoprefixer()) //auto prefix tags like -webkit- -moz- -o- etc wherever required
if (isSourceMap && globalSourceMapInit) {
p = p.pipe(plugins.sourcemaps.write()) //write the sourcemap which was inited
}
return p.pipe(plugins.concat(concatFileName)) //concatinate all the files in /src to concatFileName
.pipe(gulp.dest(dest)); //save concatFileName to dest
});
当然你也可以将isSourceMap && globalSourceMapInit
存储在一个变量中,避免检查两次,但这是次要的。
关于javascript - 在方法中调用函数时使用三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764804/