Gulp is a flexible and powerful tool to set up task execution that helps to automate development routines. The following is an explanation of how to automate CSS compilation and processing from Sass files using Gulp for a PHP project in PhpStorm IDE.

I would like to use Sass in a project that I develop in PhpStorm. The project already uses a third-party CSS framework that I would like to keep intact. My customizations will include several style overrides and a few custom CSS style definitions. Because of this, I would like to keep my source and distribution files separate.

Install Gulp

I would like to use Gulp to compile and minify my stylesheets. This will require Node.js npm utility. For more information, read this guide on how to get npm.

Within my project, I first need to initialize a new Node project, install Gulp and Gulp CLI. To type the commands, I open the PhpStorm terminal with Alt + F12:

For my goals, I will need several Gulp plugins:

  • gulp-sass – to compile Sass source files into CSS
  • del – to clean up the distribution directory
  • gulp-clean-css – to minify CSS
  • gulp-rename – to rename minified CSS files
  • gulp-sourcemaps – to add source maps to the minified files

I install these plugins as development dependencies:

Once that is done, I can see them in my projects settings (Ctrl + Alt + S)

Setup Sass processing in the gulpfile.js

Next, I create the gulpfile.js in my project root and add the following constants first:

The first constants represent functions I import from Gulp plugins for build tasks. The last two constants, sourceDir and distDir, are folders (in this project, within a WordPress theme) where I will put my source Sass files and where the distribution files will be placed. This folder structure looks like this:

Next, I add the first task to this file. This task will compile Sass files to CSS:

The next task will clean up the distribution folder. Previous versions of compiled files must be removed before newly compiled can be copied there:

The following task will minify the freshly compiled CSS files and save them with .min.css extension. Also, it writes source maps:

This task will watch over any changes in my source Sass files and execute a series of task to compile, and minify CSS files:

Finally, I will add a default task that is executed every time I run gulp command on my project without specifying a task:

Running Gulp tasks in PhpStorm

To open the Gulp task window, I need to right-click my gulpfile.js and select the Show Gulp Tasks menu. This will open the following window:

If I choose to run the watch task, it will continue executing in the background doing its thing every time I save a source Sass file:

See the official JetBrains documentation on additional information on the use of Gulp in PHPStorm.