javascript - 在方法中调用函数时使用三元运算符

标签 javascript gulp

我正在为 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/

相关文章:

javascript - 我们可以打印/存储 console.time() - console.timeEnd() 的值吗?

javascript - 如何在不刷新页面的情况下使用 ajax/javascript 更新数据库 asp.net mvc

javascript - 在 JavaScript 中创建链接,并将其集成到 createTextNode()

javascript - BrowserSync + gulp : Cross domain Cors Issue

javascript - Gulp 没有正确查看我的 scss 文件

javascript - gulp.src 基本选项应用于一个数组项

javascript - 删除 JavaScript 中不再使用的对象和变量是一种好习惯吗?

javascript - 告诉 jQuery 对哪个(唯一)div 执行操作

javascript - Sass Gulp 损坏

javascript - Gulp-Coveralls 返回 422,找不到 TravisCI 构建