Preprocessing with Gulp

Installing Gulp plugin and using them


In the previous article, we have created Gulp file with default task, we will learn to create a Gulp file to compile SASS file into CSS in this article.

First thing first, we need to install gulp plugin called gulp-sass in order to compile SASS file as CSS, this can be done by running the following command from your project root folder using the terminal.

npm install gulp-sass --save-dev

Don’t forget to add –save-dev flag which adds gulp-sass into devDependecies in the package.json file as well we have to add gulp-sass from the node_modules folder as we did with the gulp.

var sass = require('gulp-sass')

Now we’ll create a sample sass file, open a text editor and paste the following code and save as main.sass.

$primary-color: #3570ce 
$secondary-color: #1c9686
$text-color: #ffffff

	border-color: $secondary-color
	border: 1px solid
	background-color: $primary-color
	color: $text-color

All we need to do is creating a gulp task which helps us to compile the SASS file and produce CSS file, open the gulpfile.js that we have created earlier and create a new gulp task with following code, it takes SASS file and with the help of the gulp-sass plugin, it compiles the SASS into CSS.

gulp.task('sass', function(){ 
	return gulp.src('app/sass/main.sass') // Source of the sass file
	    .pipe(sass()) // Using gulp-sass plugin
	    .pipe(gulp.dest('app/css/')) // Compiled code to be saved here

Note: gulp-sass uses LibSASS to use Ruby methods gulp-ruby-sass plugin should be used instead above mentioned gulp plugin. This task is named as sass since we have loaded gulp-sass plugin from node_modules in the variable sass earlier.

Once you have done all the things, start the command prompt from the project root folder and run the sass gulp task using the following command.

gulp sass

For the above-given SASS style, the compiled CSS style will be the following

.heading {
  border-color: #1c9686;
  border: 1px solid;
  background-color: #3570ce;
  color: #ffffff;

When we work on SASS in real time, there would be many modifications on SASS file, modifying SASS file and compiling them into CSS would time consuming task, it would be better if we automate this process, in the coming article, we would look how gulp tasks watch and browserSync helps to automate such tasks.

Happy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *