如何创建具有可重用功能的 gulp 文件 - 多个观察点和多个输出目的地

How to create a gulp file with reusable functions - Multiple Watch points & Multiple Output destinations

目标是使用这个 Gulp 文件来执行 'n' 个不同的源和目标。

我们如何传递参数(源、目标),以便 CSS-Generator 任务接受这些源和目标并给出单独的输出文件。

var gulp = require("gulp"),
  sass = require("gulp-sass"),
  postcss = require("gulp-postcss"),
  autoprefixer = require("autoprefixer"),
  cssnano = require("cssnano");

var paths = {
  styles: {
    src1: "scss/slider-one/index.scss",
    src2: "scss/slider-two/index.scss"

    dest1: "slider-one",
    dest2: "slider-two"
  }
};

function style1() {
  return (
    gulp
     .src(paths.styles.src1)
     .pipe(sass())
     .on("error", sass.logError)
     .pipe(postcss([autoprefixer(), cssnano()]))
     .pipe(gulp.dest(paths.styles.dest1))
  );
 }

 exports.style1 = style1;

 function style2() {
  return (
    gulp
      .src(paths.styles.src2)
      .pipe(sass())
      .on("error", sass.logError)
      .pipe(postcss([autoprefixer(), cssnano()]))
      .pipe(gulp.dest(paths.styles.dest2))
  );
 }

 exports.style2 = style2;

 function watch() {

   style1();
   style2();

   gulp.watch("scss/slider-one/*.scss", style1);
   gulp.watch("scss/slider-two/*.scss", style2);
  }

  exports.watch = watch

您的来源是 scss/slider-one/index.scss,目的地是 slider-one,观看是 scss/slider-one/*.scss

slider-one 在源、目标和手表中很常见。

所以你可以将paths数组定义为["slider-one","slider-two"]

并且您正在调用 style1 & style2 作为 watch 函数的回调。所以你可以把它组合起来并在一个函数中定义它。

然后使用参数 (source,destination,watch).

for loop 中调用该函数

完整代码:

var gulp = require("gulp"),
 sass = require("gulp-sass"),
 postcss = require("gulp-postcss"),
 autoprefixer = require("autoprefixer"),
 cssnano = require("cssnano");

function runGulpSass(src,dest,watch) {
 gulp.watch(watch, function() {
   return gulp.src(src)
          .pipe(sass())
          .on("error", sass.logError)
          .pipe(postcss([autoprefixer(), cssnano()]))
          .pipe(gulp.dest(dest))
 });
}

exports.runGulpSass = runGulpSass;

function startGulp() {
 var paths = ["slider-one","slider-two"];
 for(var i=0;i<paths.length;i++) {
   runGulpSass("scss/"+paths[i]+"/index.scss",paths[i],"scss/"+paths[i]+"/*.scss")
 }
}

exports.watch = startGulp

[编辑] 如果source, destination & watch中没有共同值:

像这样定义 paths 数组:

var paths = [
    ["scss/slider-one/index.scss","css/slider-one","slider-one/*.scss"],
    ["scss/slider-two/index.scss","css/slider-two","slider-two/*.scss"]
];

并像这样设置 runGulpSass 函数参数:

runGulpSass(paths[i][0],paths[i][1],paths[i][2])