Switch output folder based on filename in gulp tas

2019-06-12 11:43发布

I have different *.scss files in my src folder and I want one file to be compiled in its own separate folder.
Lets assume I have the files normalFile_1.scss, specialFile.scss, normalFile_2.scss. I want the two normal files to be compiled to the folder Public/Css, the special file however should end up in the folder Public/Css/Special.

I have tried to get the current filename in the task with gulp-tap, which works fine.

.pipe($.tap(function (file, t) {
      filename = path.basename(file.path);
      console.log(filename); //outputs normalFile_1.css, specialFile.css, normalFile_2.css
}))

And with gulp-if I then wanted to switch the output folder based on the filename variable (PATHS.dist is the output "root" folder Public):

.pipe($.if(filename == 'specialFile.css', gulp.dest(PATHS.dist + '/Css/Special'), gulp.dest(PATHS.dist + '/Css')));

But everything still ends up in the Public/Css folder. Why does this not work? Is this even a good way of trying to accomplish that or are there better methods?

1条回答
Emotional °昔
2楼-- · 2019-06-12 12:26

There are two ways to do this shown below:

var gulp = require("gulp");
var sass = require("gulp-sass");
var rename = require("gulp-rename");
var path = require('path');

gulp.task('sass', function () {

  return gulp.src('src/*.scss')
    .pipe(sass().on('error', sass.logError))

    .pipe(rename(function (path) {
      if (path.basename == "specialFile") {
        path.dirname = "Special";
      }
    }))

    .pipe(gulp.dest('Public/Css'))

  //   .pipe(gulp.dest(function(file) {
  //     var temp = file.path.split(path.sep);
  //     var baseName = temp[temp.length - 1].split('.')[0];
  //     console.log(baseName);
  //     if (baseName == "specialFile") {
  //       return 'Public/Css/Special';
  //     }
  //     else return 'Public/Css';
  // }))

});

gulp.task('default', ['sass']);

Obviously I suggest the rename version.

[Why a simple file.stem or file.basename doesn't work for me in the gulp.dest(function (file) {} version I don't know - that would certainly be easier but I just get undefined.]

查看更多
登录 后发表回答