[英]Use ternary operator while calling function in method
我正在為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為true,則應該執行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
存儲在變量中,以避免再次檢查,但這是次要的。
您可以使用身份轉換代替null
。 說使用through2
軟件包(尚未測試過)
const identity = require('through2')(function(file, _, next){
this.push(file);
next()
})
return gulp.src(src)
.pipe(isSourceMap && globalSourceMapInit ? plugins.sourcemaps.init() : identity)
.pipe(...)
...
...
...
...
.pipe(isSourceMap && globalSourceMapInit ? plugins.sourcemaps.write() : identity)
.pipe(gulp.dest(dest));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.