我正在为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
:在三元运算符中,或者它是否有效。
我想知道这是否是可行的解决方案,以及其他可能的解决方案。实现这一目标的最佳方法(使用三元运算符)。
答案 0 :(得分:2)
不要试图将所有东西连在一起。 Pipe返回更改的对象。使用它:
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
存储在变量中,以避免检查两次,但它是未成年人。
答案 1 :(得分:0)
您可以使用身份转换而不是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));