gulp用一个命令从多个sass文件夹编译多个css?

时间:2019-03-04 08:05:08

标签: build sass gulp

我具有以下文件结构:

themes
  folder1
    -scss
      -style.scss
  folder2
    -scss
      -style.scss
  foldern
    -scss
      -style.scss

  package.json
  gulpfile.js

需要使用以下格式的输出:

themes
  folder1
    -scss
      -style.scss
    css
      -style.css
  folder2
    -scss
      -style.scss
    css
      -style.css
  foldern
    -scss
      -style.scss
    css
      -style.css

  package.json
  gulpfile.js

gulpfile.js:

(function () {
  'use strict';

var gulp = require('gulp'),
    eslint = require('gulp-eslint'),
  sass = require('gulp-sass'),
  sourcemaps = require('gulp-sourcemaps')

  gulp.task('sass', function () {
    return gulp
      .src('./**/scss/**/*.scss')
      .pipe(sourcemaps.init())
      .pipe(sass({
        outputStyle: 'uncompressed'
      }).on('error', sass.logError))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./**/css'));
  });

  gulp.task('watch', gulp.series('sass', function () {
    gulp.watch('./scss/**/*.scss', gulp.series('sass'));
  }));

})();

当我使用上述gulpfile进行编译时,它将在主题目录中创建** / css / folder1 / stle.css ** / css / folder2 / style.css文件夹。如何以这种格式编译? gulp中是否有针对此的任何特定插件。 预先感谢。

1 个答案:

答案 0 :(得分:1)

尝试一下:

var gulp = require('gulp'),
  sass = require('gulp-sass'),
  // etc.

  // two more plugins
  rename = require('gulp-rename')
  path = require('path');


  gulp.task('sass', function () {
    return gulp
      .src('./**/scss/**/*.scss')
      .pipe(sourcemaps.init())
      .pipe(sass({
        outputStyle: 'uncompressed'
      }).on('error', sass.logError))
      .pipe(sourcemaps.write('./'))

       // rename the current file's parent directory

      .pipe(rename(function (file) {

        // file.dirname = current folder, your "scss"
        // then get the parent of the current folder, e.g., "folder1", "folder2", etc.
        let parentFolder = path.dirname(file.dirname)

        // set each file's folder to "folder1/css", "folder2/css", etc.
        file.dirname = path.join(parentFolder, 'css');
      }))

      .pipe(gulp.dest('.'));
  });