1

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

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

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
4

1 回答 1

0

您的来源是scss/slider-one/index.scss& 目的地是slider-one并且手表是scss/slider-one/*.scss

slider-one在源、目的地和观察中很常见。

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

你正在调用style1 & style2作为watch函数的回调。因此,您可以使用它并在一个函数中定义它。

for loop并使用参数在内部调用该函数(source,destination,watch)

完整代码:

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])
于 2019-02-08T08:25:41.217 回答