Search code examples
gulpgulp-sass

Merge multiple scss files into one css file


I'd like to merge all of my scss files into one compressed css file:

Structure:

  • stylesheets/
    • test.scss
    • test2.scss
  • gulpfile.js

I tried this two tasks, which I found in several answers and tutorials, but I always got the scss file into a duplicated css file:

gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/'))
});

and

gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/styles.css'))
});

!!! EFFECTIV RESULT !!!

  • stylesheets/
    • test.scss
    • test2.scss
  • css/
    • test.css
    • test2.css
  • gulpfile.js

or with second tried task:

  • stylesheets/
    • test.scss
    • test2.scss
  • css/styles.css/
    • test.css
    • test2.css
  • gulpfile.js

??? EXPECTED RESULT ???

  • stylesheets/
    • test.scss
    • test2.scss
  • css/
    • styles.css
  • gulpfile.js

Any ideas?


Solution

  • You indicated that you want to merge your files into one file and compress that file, so you need to add two plugins to do each of those.

    Gulp-concat and gulp-uglify

    const concat = require('gulp-concat');
    const uglify = require('gulp-uglify');
    
    gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(concat('styles.css'))
      .pipe(uglify())
    
      // .pipe(rename({
       //  basename: "styles",
       //   suffix: ".min",
       //   extname: ".css"
      //  }))
    
      .pipe(gulp.dest('css'))
    });
    

    In addition, you may want to add gulp-rename to indicate that the file has been uglified/minified via a .min.css extension (and change your html link to point to that filename).