Saturday, March 7, 2020

Getting Started With Gulp.js

Gulp is a tool which allows you to automate bits of your workflow which can literally save you hours a day. Whether you’re a developer or a designer who creates HTML wireframes now and then, I encourage you to dig in.

In this article we’ll look at the basics of using Gulp — from installation to basic syntax and a couple of examples. By the end of the article you should be able to find, install and use packages that others have created for Gulp to compile CSS-preprocessors, optimize images, create sprites, concatenate files, and more!

How To Use Grunt To Automate Your Workflow [Tutorials]

How To Use Grunt To Automate Your Workflow [Tutorials]

I’m a huge advocate of automation because it makes life that much simpler. Why spend time on menial,... Read more

Installing Gulp

We’ll use Terminal in OSX and Linux to install Gulp. For Windows, we recommend to use to use Cygwin, Cmder or WSL (Windows Subsystem for Linux). I’ll be referring them simply as as Terminal.

First, we’ll make sure that Node.js and NPM are already installed in our compter. Open up the Terminal and type npm -v and press enter. If you see version number displayed you have them installed already.

NPM version 6.9.0 shown in macOS Terminal applicationNPM version 6.9.0 shown in macOS Terminal application

If you get a “command not found” (or a similar error), head on down to the Node.js downloads page and select the appropriate package for your system. Once installed, the npm command will be available in the Terminal.

Now, we can type the following command in the Terminal, to install the Gulp CLI.

npm install --global gulp-cli

This will allow us to run the gulp command to execute the Gulp tasks.

Adding Gulp package to a Project

This Gulp package will handle and define the Gulp tasks to run in our project. To install, it we can type the following command:

npm install --save-dev gulp

This will install the Gulp package to the node_modules folder in our project folder and register Gulp as the project “Development” dependency. It’s basically telling that Gulp is a tool that we only use on a development environment.

Gulpfile

The Gulpfile is where the magic happens. It’s where you define the automations you require and when you want them to happen. Let’s create an empty default task by creating a file named gulpfile.js and pasting the following code into it.

const gulp = require('gulp');

gulp.task('default', function() {
  // This does nothing for now, we'll add functionality in a moment...
});

Once this file is saved you can go back to your terminal and run the gulp command on its own. Gulp detects which project it is in and runs the default task — the one we just created. You should see something like this:

default taskdefault task

Nothing really happens here, since the task is empty, but it is working fine. Let’s get going with some proper examples!

Copying A File

This is a boring one, I’ll admit as much, but it will help you understand what’s going on easily.

In your project folder create a file named to_copy.txt , and a folder named dev. Let’s go into our Gulpfile and create a new task named copy.

const gulp = require('gulp');
  gulp.task('default', function () {
    return gulp.src('file.txt')
        .pipe( gulp.dest('dist') );
});

The first line defines a task that is named copy. Within this we use gulp.src to specify which files we are targeting with this task — in this case it is a single file named to_copy.txt.

We then pipe these files to the gulp.dest function which specifies where we want to put these files — I’ve used the dev directory.

Go back to your terminal and type gulp copy to run this task, it should copy the specified file to the specified directory, something like this:

gulpjs copygulpjs copy

The pipe command is at the heart of Gulp. It is an efficient way to move data between commands. The src command specifies the files which are piped to the dest command. In more complex scenarios we would pipe our files to other commands before specifying a destination.

You should also be aware that the source can be given as a single file, or multiple files. If we have a folder named src and we want to move all files from our dist folder into it, we could use the following command:

const gulp = require('gulp');
  gulp.task('default', function () {
    return gulp.src('src/*')
        .pipe( gulp.dest('dist') );
});

The star character will match anything within the directory. You could also match all files within all subdirectories, and do all sorts of other fancy matching. Take a look at the node-glob documentation for more info.

Compiling Sass

Compiling a CSS Pre-processors like Sass to CSS is a common task when developing websites. With Gulp, it’s fairly easy to do it with couple of modules namely node-sass and gulp-sass. You can type the following command in Terminal, to install these modules:

npm install node-sass gulp-sass --save-dev

Once done, you can use the syntax the package dictates to compile your code. To do this, create a file named styles.scss with the following content:

$primary: #ff9900;
body {
    background: $primary;
}

Now create the following Gulp task in the Gulpfile.

const sass = require('gulp-sass');
sass.compiler = require('node-sass');
  
gulp.task('sass', function () {
    return gulp.src('*.scss')
        .pipe( sass() )
        .pipe( gulp.dest('css') );
});

When you run gulp sass, all files with the scss extension will be piped to the sass function, which will convert them to css. These are then piped to the destination function which places them in the css folder.

Watching Files And Folders

So far this is all handy, but we still need to type a command each time we want to run a task, which isn’t very efficient, especially when it comes to stylesheet changes. Gulp allows you to watch files for changes and run commands automatically.

In the Gulpfile, create a command named automate which will use the watch command to watch a set of files for changes, and run a specific command when a file changes.

const sass = require('gulp-sass');
sass.compiler = require('node-sass');

gulp.task('sass', function () {
    return gulp.src('*.scss')
        .pipe( sass() )
        .pipe( gulp.dest('css') );
});

gulp.task('automate', function() {
    return gulp.watch('*.scss', gulp.parallel('sass'));
});

If we type gulp automate, it will start and finish the task, but it won’t return to the prompt because it is monitoring for changes. We’ve specified that we want to watch all scss files in the root directory and if they change, we want to run the sass command that we’ve set up previously.

If we change the style.scss file, it will compile to the css file within the css directory automatically.

watchwatch

Running Multiple Tasks

There are many situations where you might want to run multiple tasks. When watching your javascript folder you may want to compile concatenate two files and then proceed to minify them. There are two ways you can get this done.

If tasks are related, I like to chain them. A good example would be the concatenation and minification of javascript files. We first pipe our files to the concat action, then pipe them to gulp-uglify, then use the destination function to output them.

If tasks are unrelated you could call multiple tasks. An example would be a task where we want to concatenate and minify our scripts and also compile our Sass. Here’s he full Gulpfile of how that would look.

const gulp = require('gulp');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const sass = require('gulp-sass');
sass.compiler = require('node-sass');

gulp.task('scripts', function() {
  return gulp.src('js/**/*.js')
    .pipe(concat('scripts.js'))
    .pipe(gulp.dest('js'))
    .pipe(uglify())
    .pipe(gulp.dest('js'))
});

gulp.task('sass', function () {
  return gulp.src('*.scss')
      .pipe( sass() )
      .pipe( gulp.dest('css') );
});

gulp.task('automate', function() {
    gulp.watch(['*.scss', 'js/**/*.js'], gulp.parallel('sass', 'scripts'));
});


gulp.task('default', ['scripts', 'styles']);

If you type gulp scripts into the terminal, all javascript files within the js directory will be concatenated, output to the main directory, then uglified and saved to the main directory.

If you type gulp sass, all your scss files will be compiled and saved to the css directory.

If you type gulp (the default task), your scripts task will be run, followed by your styles task.

The gulp automate task watches multiple folders for changes in our scss and js files and will perform both tasks we’ve defined, if a change is detected.

Overview

Using Gulp is not difficult, in fact, many people prefer it over Grunt because of its simpler syntax. Remember the steps to take when creating a new automation:

  • Search for plugin
  • Install plugin
  • Require plugin in your Gulpfile
  • Use the syntax in the documentation

The five commands available in Gulp (task, run, watch, src, dest) are the only ones you need to know, all third party addons have great documentation. Here’s a list of some things I use which you could get started with right now:

The post Getting Started With Gulp.js appeared first on Hongkiat.

From https://ift.tt/2H0fTCQ, find us on maps: https://bit.ly/31tHUKW

No comments:

Post a Comment