-->

Using gulp-sass, how do I preserve the folder stru

2019-06-07 16:35发布

问题:

I have a project with multiple folders that contain sass files:

|── src
    └── scripts
        └── app1
            └── sass
                └── base.scss
        └── app2
            └── sass
                └── base.scss

I also have a gulp task that compiles those .scss files using gulp-sass and gulp-concat-css:

gulp.task('build:sass', () =>
    gulp.src([
      'scripts/**/*.scss'
    ])
    .pipe(plugins.sass().on('error', plugins.sass.logError))
    .pipe(plugins.concatCss('bundle.css'))
    .pipe(gulp.dest('dist'))
  );

Right now, the above task just creates bundle.css into the dist folder:

|── dist
    └── bundle.css

What I'd like to have happen is this, where the initial folder structure is preserved, except for the sass folder is now css.

|── dist
    └── scripts
        └── app1
            └── css
                └── bundle.css
        └── app2
            └── css
                └── bundle.css

回答1:

You can use the gulp-flatmap plugin to solve this:

var path = require('path');

gulp.task('build:sass', () =>
  gulp.src('scripts/app*/')
    .pipe(plugins.flatmap((stream, dir) =>
       gulp.src(dir.path + '/**/*.scss')
         .pipe(plugins.sass().on('error', sass.logError))
         .pipe(plugins.concatCss('css/bundle.css'))
         .pipe(gulp.dest('dist/' + path.basename(dir.path)))
    )) 
);

This selects all of your app directories and then maps each of those directories to a new stream in which all .scss files in that particular directory are concatenated into a single bundle.css file.