Tagbangers Blog

Simple set up for gulp-sass

日本語版はこちら


Hi! It's me again and this time I'll be sharing on how to automatically compile our scss file with gulp, which is very useful for web development.

Ok, let's get started!

Installing gulp, gulp-sass as a dev dependency

$ npm install gulp gulp-sass -D

Sample directory

what we'll need: 

  • source directory
  • output directory
  • gulpfile.js

In my case, my source and my output directory will be ./sass and ./css respectively


Setting up our gulpfile.js

Next, we'll be setting up our gulpfile.js as below

gulpfile.js

const gulp = require('gulp')
const sass = require('gulp-sass')

gulp.task('sass', () => {
  return gulp
    .src('./sass/style.scss')
    .pipe(sass())
    .pipe(gulp.dest('./css'))
})

As we can see, we've written a task to compile our './sass/style.scss' file into './css'

Now, let's try compiling our file!

$ gulp sass

Now that our compiler is working, we'll be adding a new task to automatically compile our file for us.

Adding watcher to our gulpfile.js

Next, we'll be adding a new task to watch any changes that match our wildcard (any scss inside './src' and it's subdirectories) and run the compiler for us.

gulpfile.js

const gulp = require('gulp')
const sass = require('gulp-sass')

gulp.task('sass', () => {
  return gulp
    .src('./sass/style.scss')
    .pipe(sass())
    .pipe(gulp.dest('./css'))
})

gulp.task('watch', () => {
  gulp.watch('./sass/**/*.scss', gulp.series('sass'))
})

Now, let's try running our new task and make some changes to our files.

$ gulp watch


We're done!


Extra

Logging compile error

gulpfile.js

const gulp = require('gulp')
const sass = require('gulp-sass')

gulp.task('sass', () => {
  return gulp
    .src('./sass/style.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'))
})

gulp.task('watch', () => {
  gulp.watch('./sass/**/*.scss', gulp.series('sass'))
})


Task Chaining

We'll be using gulp-print for this example

$ npm i gulp-print -D

gulpfile.js

const gulp = require('gulp')
const sass = require('gulp-sass')
const print = require('gulp-print').default;

gulp.task('print', () => {
 return gulp.src('./sass/**/*.scss')
      .pipe(print(filepath => `matched wildcard: ${filepath}`))
});

gulp.task('sass', () => {
  return gulp
    .src('./sass/style.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'))
})

gulp.task('watch', () => {
  gulp.watch('./sass/**/*.scss', gulp.series(['print', 'sass']))
})