Minify css + Gulp

1.5k Views Asked by At

I have this gulpfile.js to compile css but I also want to minify my css. I try to run many different codes that I found in the internet but none of them works. Could any one help me? Thanks

    var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', gulp.series(function() {
    return gulp.src(['scss/*.scss'])
        .pipe(sass()) // converter o Sass em CSS
        .pipe(gulp.dest('css'));
}));

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

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

There are 3 best solutions below

1
Nico Shultz On

Here is my gulp file it compiles and minifies css and js (it also has some data for images and php files but they are unused)

const gulp = require('gulp'),
  gutil = require('gulp-util'),
  touch = require('gulp-touch-cmd'),
  plugin = require('gulp-load-plugins')(),
  merge = require('merge-stream');

// Select Foundation components, remove components project will not use
const SOURCE = {
  scripts: [
    // Place custom JS here, files will be concantonated,
    // minified if ran with --production
    'assets/scripts/**/*.js',
  ],

  // Scss files will be concantonated, minified if ran with --production
  styles: 'assets/style/scss/**/*.scss',

  // Images placed here will be optimized
  images: 'assets/images/src/**/*',

  php: '**/*.php'
};

const ASSETS = {
  styles: 'assets/style/',
  stylesDist: 'assets/dist/style',
  scripts: 'assets/scripts/',
  scriptsDist: 'assets/dist/scripts',
  images: 'assets/images/',
  all: 'assets/dist/'
};

gulp.task('log', function() {
  console.log(ASSETS.styles);
});

// Compile Sass, Autoprefix and minify
gulp.task('styles', function () {

  const bulk = gulp.src(SOURCE.styles);

  return merge(bulk)
    .pipe(plugin.plumber(function (error) {
      gutil.log(gutil.colors.red(error.message));
      this.emit('end');
    }))
    .pipe(plugin.sourcemaps.init())
    .pipe(plugin.sass())
    .pipe(plugin.autoprefixer({
      browsers: [
        'last 2 versions',
        'ie >= 9',
        'ios >= 7'
      ],
      cascade: false
    }))
    .pipe(plugin.cssnano({ safe: true, minifyFontValues: { removeQuotes: false } }))
    .pipe(plugin.sourcemaps.write('.'))
    .pipe(gulp.dest(ASSETS.stylesDist))
    .pipe(touch());
});


// GULP FUNCTIONS
// JSHint, concat, and minify JavaScript
gulp.task('scripts', function () {

  // Use a custom filter so we only lint custom JS

  return gulp.src(SOURCE.scripts)
    .pipe(plugin.plumber(function (error) {
      gutil.log(gutil.colors.red(error.message));
      this.emit('end');
    }))
    .pipe(plugin.sourcemaps.init())
    .pipe(plugin.babel({
      presets: ['es2015'],
      compact: true,
      ignore: ['what-input.js']
    }))
    .pipe(plugin.concat('scripts.js'))
    .pipe(plugin.uglify())
    .pipe(plugin.sourcemaps.write('.')) // Creates sourcemap for minified JS
    .pipe(gulp.dest(ASSETS.scriptsDist))
    .pipe(touch());
});


// Watch files for changes (without Browser-Sync)
gulp.task('watch', function () {
  // Watch .scss files
  gulp.watch(SOURCE.styles, gulp.parallel('styles'));

  // Watch scripts files
  gulp.watch(SOURCE.scripts, gulp.parallel('scripts'));
});

Here is another one I've used :

// Initialize modules
// Importing specific gulp API functions lets us write them below as series()
//  instead of gulp.series()
const { src, dest, watch, series, parallel } = require('gulp');
// Importing all the Gulp-related packages we want to use
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const replace = require('gulp-replace');


// File paths
const files = { 
  scssPath: 'site/templates/styles/sass/**/*.scss',
  jsPath: 'site/templates/scripts/**/*.js'
}

// Sass task: compiles the style.scss file into style.css
function scssTask(){    
  return src(files.scssPath)
    .pipe(sourcemaps.init()) // initialize sourcemaps first
    .pipe(sass()) // compile SCSS to CSS
    .pipe(postcss([ autoprefixer(), cssnano() ])) // PostCSS plugins
    .pipe(sourcemaps.write('.')) // write sourcemaps file in current directory
    .pipe(dest('site/templates/dist')
  ); // put final CSS in site/templates/dist folder
}

// JS task: concatenates and uglifies JS files to script.js
function jsTask(){
  return src([
    files.jsPath
    //,'!' + 'includes/js/jquery.min.js', // to exclude any specific files
    ])
    .pipe(concat('all.js'))
    .pipe(uglify())
    .pipe(dest('site/templates/dist')
  );
}

// Cachebust
const cbString = new Date().getTime();
function cacheBustTask(){
  return src(['index.html'])
    .pipe(replace(/cb=\d+/g, 'cb=' + cbString))
    .pipe(dest('.'));
}

// Watch task: watch SCSS and JS files for changes
// If any change, run scss and js tasks simultaneously
function watchTask(){
  watch([files.scssPath, files.jsPath], 
    series(
      parallel(scssTask, jsTask)
    )
  );    
}

// Export the default Gulp task so it can be run
// Runs the scss and js tasks simultaneously
// then runs cacheBust, then watch task
exports.default = series(
  parallel(scssTask, jsTask), 
  watchTask
);
0
Mark On

To fix your code try:

gulp.task('sass', function() {
    return gulp.src(['scss/*.scss'])
        .pipe(sass()) // converter o Sass em CSS
        .pipe(gulp.dest('css'));
});

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

gulp.task('default', gulp.series('sass', 'watch'));

But this form of functions is better:

     // renamed since your plugin name is apparently `sass` as well
function sass2css() {   
    return gulp.src(['scss/*.scss'])
        .pipe(sass()) // converter o Sass em CSS
        .pipe(gulp.dest('css'));
};

function watch() {
    gulp.watch(['scss/*.scss'], gulp.series(sass2css));
});

gulp.task('default', gulp.series(sass2css, watch));
0
rahul sharma On
Try This
i am sharing two function one for css and and another for sass
run this command
 npm install gulp-concat gulp-autoprefixer gulp-sass gulp-sass-glob node-sass --save-dev 

// and copy this code and set the

const { src, dest } = require("gulp");
const concat = require("gulp-concat");
const autoprefixer = require("gulp-autoprefixer");
const sass = require("gulp-sass");
const sassGlob = require("gulp-sass-glob");
sass.compiler = require("node-sass");



function css() {
    return src("src/css/*.css")
        .pipe(concat("style.css"))
        .pipe(sassGlob())
        .pipe(
            sass({
                outputStyle: "compressed" //expand or compact or compressed
            }).on("error", sass.logError)
        )
        .pipe(
            autoprefixer({
                cascade: true
            })
        )
        .pipe(dest("build/css/"));
}


function scss() {
    return src('src/scss/style.scss') // import your all file in style.scss
        .pipe(sassGlob())
        .pipe(
            sass({
                outputStyle: 'compressed' // you can set "expand or compact or compressed" view 
            })
                .on('error', sass.logError)
        ).pipe(
            autoprefixer({
                cascade: true
            })
        ).pipe(dest('build/scss/'));
}

exports.css = css;
exports.scss= scss;