Skip to main content
Image
Gulp.js

Installing and using Gulp.js to compile Sass in Drupal

Hello everyone!

Today we are going to turn the tables, and we will move a little to the front side of web development, something atypical in this blog, but hey, it is always important to know a little about everything in this wide world. To learn how to compile Sass, we must first know what it is, so we will start by defining Sass a little.
According to Wikipedia :

Sass (Syntactically Awesome Stylesheets) is a stylesheet language initially designed by Hampton Catlin and developed by Nathan Weizenbaum.

And in reality, it is nothing more than that, a CSS metalanguage, restrictive but very organized and clean , where each block of code is structured according to indentation and shapes to avoid copy & paste of code, avoiding code repeated over and over again. . The structure of a Sass project is typically as follows:

  • base/
  • components/
  • layout/
  • pages/
  • topics/
  • profits/
  • suppliers/

To convert Sass into CSS and thus reflect the changes in our project, it is necessary to compile the Sass files, we can do it one by one with the following command:

sass source/stylesheets/index.scss build/stylesheets/index.css
But of course, why do we want to compile files one by one every time we make a change to the code, having the option of launching a script that is responsible for detecting changes in Sass files and compile them automatically to reflect these changes instantly in our project. This is already another level, we are talking about Gulp.js. Gulp is a construction system whose function is to automate tasks for the developer, such as compilation, validation, syntax errors, among others. It is developed in JavaScript and works on Node.js , which we will proceed to install next.

To install Node.js, we will use NVM, which is the β€œNode.js Version Manager”. With NVM we can install several separate and independent versions of Node.js, which will allow us to control the environment more easily. In our case, we will use NVM to install the latest stable version of Node.js and keep it up to date. First we will update our source packages:

sudo apt-get update sudo apt-get install build-essential libssl-dev

Next, we will download the NVM installation script with cURL from the project page on Github .

curl -sL https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh -o install_nvm.sh

The version number may vary over time, we would only have to go to β€œ Releases ” and change the NVM version if necessary. Now we proceed to execute the script.

 bash install_nvm.sh  

NVM will be installed in a subdirectory of the main ~/.nvm directory. It will also add a few lines to ~/.profile, so we must restart it to apply changes.

 source ~/.profile  

Now that NVM has been installed, we can install standalone versions of Node.js. To find out the stable one among the available versions, we will execute the command:

 nvm ls-remote  

This will print a list on the screen with all the available versions. We must install the latest LTS Stable version , which is currently v8.12.0, but will vary over time.

 nvm install v8.12.0  

We will indicate to NVM that we want to use this version.

 nvm use v8.12.0  

We will check the version of Node.js installed.

 node -v  

We already have Node.js and its NVM version manager installed correctly, which will allow us to easily update it or choose particular versions. Now it's time to install Gulp.js. First of all, we will install gulp-cli, which is a gulp utility which allows us to use gulp in projects or globally.

 npm install gulp-cli -g  

By indicating the -g option we are telling it that we want to install it globally to use it in any project. Now we will install gulp.

 npm install gulp  

This process may take time, but once finished we will have Gulp installed globally. Before we can use it, we must create a new configuration file for gulp, called gulpfile.js . This file must be placed at the root of the project and must have a structure with the following elements:

  • Importing other modules
  • Importing a project configuration file (optional)
  • The definition of the tasks
  • Observers that run based on certain changes (optional)
  • A default task (tasks) to execute

That means that the gulpfile.js should be created depending on the needs of the project. The official gulp website itself provides us with a command to start the gulpfile.js:

npx -p touch nodetouch gulpfile.js

However, here I leave you a basic configuration.

// Gulp.js configuration   var   // modules  gulp = require('gulp'),   // development mode?  devBuild = (process.env.NODE_ENV !== 'production'),   // folders  folder = {  src: 'src/',    build: 'build/'   };    

If we want to create tasks or 'tasks' , we must indicate it in this file. In this entry, we will create two important tasks, but you can create or find many more with interesting functionalities on the internet by Googling.

    gulp.task('watch', function(){
    gulp.watch(srcAssets.styles + '**/*.s+(a|c)ss', ['styles:dev'])
        .on('change', function(event) {
            console.log('');
            console.log('-> File ' + event.path.magenta.bold + ' was ' + event.type.green + ', running tasks css...');
        });

    gulp.watch(distAssets.js + '**/*.js', ['jshint'])
        .on('change', function(event) {
            console.log('');
            console.log('-> File ' + event.path.yellow + ' was ' + event.type.green + ', running tasks js...');
        });
    gulp.watch(srcAssets.images + '**/*', ['imagemin'])
        .on('change', function(event) {
            console.log('');
            console.log('-> File ' + event.path.yellow + ' was ' + event.type.green + ', running tasks images...');
    });
});

Gulp styles:pro. It allows us to generate the CSS in a single line, taking up less disk space, ready for production.

    gulp.task('styles:pro', ['clean:css'], function () {
    return gulp.src([srcAssets.styles + '**/*.s+(a|c)ss'])
        .pipe(sassGlob())
        .pipe(sass({
            errLogToConsole: true,
            outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(postCss([
            autoprefixer({
                browsers: ['> 1%', 'ie 8', 'last 2 versions'] }
            )
        ]))
        .pipe(gulp.dest(distAssets.styles));
    });

In the end, we will end up with a gulpfile.js file with as many tasks as we need in the project.

To proceed to use gulp, just run the command:

 gulp watch

Now it will be on β€œwait” until there are changes in the Sass files of the project. Once you do them, it will compile and detect syntax errors automatically, so you don't have to lose sight of the shell. To perform an efficient CSS build in a production environment, we will run the command:

 gulp styles:pro  

This will compile the CSS changes into a single line.

With Gulp.js up and running , we will notice notable differences when it comes to wasting time on basic and repetitive tasks and using it on what really matters: developing.

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Latest posts

Featured

Last news