Compressing CSS with the help of Gulp

Can anyone assist me with minifying my css in this gulpfile.js for compiling css? I have tried multiple code snippets from the internet but none of them seem to work. Your help would be greatly appreciated. Thank you.

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

gulp.task('sass', gulp.series(function() {
    return gulp.src(['scss/*.scss'])
        .pipe(sass()) // convert Sass to 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']));

Answer №1

Give this a try:
Here are two functions, one for CSS and another for SASS.
To get started, run the following command:
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" // Options: expand, compact, or compressed
            }).on("error", sass.logError)
        )
        .pipe(
            autoprefixer({
                cascade: true
            })
        )
        .pipe(dest("build/css/"));
}

function scss() {
    return src('src/scss/style.scss') // Include all your files in style.scss
        .pipe(sassGlob())
        .pipe(
            sass({
                outputStyle: 'compressed' // Choose from expand, compact, or compressed
            })
                .on('error', sass.logError)
        ).pipe(
            autoprefixer({
                cascade: true
            })
        ).pipe(dest('build/scss/'));
}

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

Answer №2

To resolve the issues in your code, consider the following adjustments:

gulp.task('compile-sass', function() {
    return gulp.src(['scss/*.scss'])
        .pipe(sass()) // convert Sass to CSS
        .pipe(gulp.dest('css'));
});

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

gulp.task('run-default', gulp.series('compile-sass', 'watch-files'));

Alternatively, you can refactor your functions as shown below:

function compileSass() {   
    return gulp.src(['scss/*.scss'])
        .pipe(sass()) // convert Sass to CSS
        .pipe(gulp.dest('css'));
};

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

gulp.task('default', gulp.series(compileSass, watchChanges));

Answer №3

My gulp file is set up to compile and minify CSS and JS files. It also contains some configurations for images and PHP files, although they are not currently being utilized.

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

// Define paths for different types of assets
const SOURCE = {
  scripts: [
    'assets/scripts/**/*.js',
  ],
  styles: 'assets/style/scss/**/*.scss',
  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 to compile Sass, Autoprefix, and minify CSS
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 task to process JavaScript files
gulp.task('scripts', function () {

  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('.'))
   .pipe(gulp.dest(ASSETS.scriptsDist))
   .pipe(touch());
});

// Watch files for changes
gulp.task('watch', function () {
  gulp.watch(SOURCE.styles, gulp.parallel('styles'));
  gulp.watch(SOURCE.scripts, gulp.parallel('scripts'));
});

Here is another example of a gulp setup:

// Initializing required modules and packages for Gulp tasks
const { src, dest, watch, series, parallel } = require('gulp');
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 for SCSS and JS files
const files = { 
  scssPath: 'site/templates/styles/sass/**/*.scss',
  jsPath: 'site/templates/scripts/**/*.js'
}

// Gulp task for compiling SCSS to CSS
function scssTask(){    
  return src(files.scssPath)
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(postcss([ autoprefixer(), cssnano() ]))
    .pipe(sourcemaps.write('.'))
    .pipe(dest('site/templates/dist')
  );
}

// Gulp task for concatenating and minifying JS files
function jsTask(){
  return src([
    files.jsPath
  ])
    .pipe(concat('all.js'))
    .pipe(uglify())
    .pipe(dest('site/templates/dist')
  );
}

// Generating cache busting string based on current time
const cbString = new Date().getTime();
function cacheBustTask(){
  return src(['index.html'])
    .pipe(replace(/cb=\d+/g, 'cb=' + cbString))
    .pipe(dest('.'));
}

// Watching SCSS and JS files for changes
function watchTask(){
  watch([files.scssPath, files.jsPath], 
    series(
      parallel(scssTask, jsTask)
    )
  );    
}

// Default Gulp task definition
exports.default = series(
  parallel(scssTask, jsTask), 
  watchTask
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Replace the image source with a list of images

I am looking to create a dynamic image list using either an array or an HTML list. When I hover over an image, it should change one by one with a fade or slide effect, and revert back to the default images when I hover out. Question 1: What type of list s ...

What is the best way to align these Iframes in the center?

This is the html <div class="main_content"> <section class="episodio"> <article class="contenedor_episodios"> <h2>Episodios</h2> <div class="episodio_spotify" ...

Tips for shrinking the circumference of a circle

Currently, I have a circular div that has been styled using CSS animations. My goal is to keep the size of the circle consistent when it moves to the bottom, but reduce its size when it bounces back to the top. I am uncertain if this can be achieved solely ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

What is the best way to define file paths in a webpage to ensure that the same file works seamlessly on both server and

Currently, I am working on developing a website locally with the intention of later transferring it via FTP to my server. In my index.php file, there is a line that reads: <?php include($_SERVER['DOCUMENT_ROOT'] . "/includes/header.php");?&g ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

How can I position two divs side by side within an Appbar?

I would like the entire Container to be in a single row, with the Typography centered as it already is, and the toggle-container to float to the right <AppBar className={styles.AppBar}> <Toolbar> <Container> ...

Positioning a sticky footer in a dual-column design

This updated post is a revised version of the one found at this link. I aim to provide a clearer explanation of my issue compared to the previous post. The problem revolves around the placement of the footer in two different scenarios. Scenario 1: The fi ...

"Strategically placing elements on an HTML grid

My current project involves creating a grid layout in HTML using CSS. The goal is to use this layout for various elements such as images, text, and links. What I envision is a visually appealing grid where each object fits together seamlessly with no gaps ...

Guide to implementing a seamless Vue collapse animation with the v-if directive

Struggling with Vue transitions, I am attempting to smoothly show/hide content using v-if. Although I grasp the CSS classes and transitions involved, making the content appear 'smoothly' using techniques like opacity or translation, once the anim ...

Issue with CSS3 gradient display in Firefox and IE, functioning correctly only in Chrome

I recently developed a text gradient class that looks great in Google Chrome but unfortunately doesn't display correctly in Firefox and Internet Explorer. In these browsers, there is a visible background gradient behind the text which is not the desir ...

What causes Firefox (Mobile) to zoom out of my webpage?

After launching my webpage on Google Chrome mobile (android), everything loads perfectly. However, when trying to access the site using Firefox mobile (android), most pages load in a zoomed-out view. The issue is resolved by opening the drop-down menu, but ...

`Some Items Missing from Responsive Navigation Menu`

Hey there! I'm currently diving into the world of responsive design and I'm attempting to create a navigation bar that transforms into a menu when viewed on a mobile device or phone. Everything seems to be working fine, except that not all the na ...

CSS3 pulsating circular Firefox bug

I am currently working on a CSS3 pulsing circle (animating scale to 1.1). To address a jumpy animation issue in Firefox, I have added a slight rotation. animation: button_pulse 2s infinite ease-out; transform: scale(1.1) rotate(0.1deg); Despite this adju ...

Extracting Text from a Span Element Using XPath in Selenium

Here is the HTML code snippet: <div class="a-row a-spacing-small a-size-small"> <div class="a-row"> <a class="a-link-normal a-declarative g-visible-js reviewStarsPopoverLink" href="#" data-action="a-popover" data-a-popover="{"closeButton":" ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

What is needed to enable the functionality of the next and previous buttons? (Carousel Bootstrap)

I'm working on a text-only carousel using Bootstrap, but I'm facing an issue with the slider not functioning properly when I press the "next" and "prev" buttons. Any assistance would be greatly appreciated! <link rel="stylesheet" href="htt ...

Is there a way to alter the footer across all my pages using just one document?

I'm having trouble coming up with a title for my question, so please bear with me. I am working on a Bootstrap website and I want to create a consistent navbar and footer across all pages without duplicating the code in each document. How can I achiev ...

Tips for creating a form-flip, similar to a card-flip effect, using web technologies

Looking to create a card flip effect similar to the one shown here. Once the sign up process is finished, the card will smoothly flip over to reveal the other side with a transitioning effect. ...

The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well! I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example: import { Butto ...