Gulp 4.x and PostCSS tutorial

Saul Goodman October 30, 2019 Loading...

Go to your project directory.

First, install the necessary packages by running:

npm install --save-dev gulp gulp-postcss gulp-rename 

And:

npm install --save-dev autoprefixer postcss-hexrgba postcss-import postcss-mixins postcss-nested postcss-simple-vars

You can install more PostCSS plugins if you want. After that, create a Javascript file and name it exactly gulpfile.js. Add the following code into the gulpfile.js.

const { gulp, src, dest, series, parallel } = require('gulp');

// rename the css file
const rename = require('gulp-rename');

const postcss = require('gulp-postcss');

// postCSS autoprefixer
const autoprefixer = require('autoprefixer');

// you can use $variable to write postCSS code
const cssVars = require('postcss-simple-vars');

// using @import
const cssImport = require('postcss-import'); 

// you can use rgba($color, opacity)
const hex2rgba = require('postcss-hexrgba');

// mixins
const mixins = require('postcss-mixins');

// nesting
const cssNested = require('postcss-nested');

//------------ CSS ------------------------------------------------------------------------
function cssTask() {

    var plugins = [
        cssImport,
        mixins,
        extendRule,
        cssVars,
        cssNested,
        hex2rgba,
        autoprefixer
    ];
    
    return src(settings.themePath + 'main.css')
        .pipe(postcss(plugins))
        .on('error', function (err) {
            console.log(err.toString());
            this.emit('end');
        })
        .pipe(rename({
            basename: 'style'
        }))
        .pipe(dest(settings.themePath))
        .pipe(browserSync.stream());
}

exports.css = cssTask;

// main.css --> style.css

In order to build your CSS, run:

gulp css

This guide is quite simple and not perfect but from here you are pretty good to go.

avatar
Welcome to KINDACODE. Have a nice day and code well!