Tutorial de Gulp súper simple para principiantes

En estos días, el uso de una herramienta de construcción es una parte indispensable de su flujo de trabajo de desarrollo web.

Gulp es una de las herramientas de construcción más populares en estos días, junto con Webpack.

Pero hay una curva de aprendizaje definida para aprender Gulp. Uno de los mayores obstáculos es descubrir los aparentemente cientos de partes diferentes que lo componen.

Y además de eso, tienes que hacer todo en la línea de comandos, lo que puede ser increíblemente intimidante si no has trabajado mucho con ella.

Este tutorial lo guiará a través de los conceptos básicos de npm (Node Package Manager) y la configuración de Gulp para sus proyectos de front-end. Una vez que haya terminado, se sentirá mucho más seguro al configurar su flujo de trabajo y usar la línea de comandos.

Entonces, ¿cuál es el problema con Gulp?

Gulp es un gran ahorro de tiempo. Al usar Gulp, puede dejar que su computadora maneje tareas tediosas, como:

  • Compilar archivos Sass en CSS
  • Concatenar (combinar) varios archivos JavaScript
  • Minificar (comprimir) sus archivos CSS y JavaScript
  • Y ejecutar automáticamente las tareas anteriores cuando se detecta un cambio de archivo

Gulp puede realizar tareas mucho más complejas que las que mencioné anteriormente. Sin embargo, este tutorial se centrará solo en los conceptos básicos de Gulp y cómo funciona.

Breve descripción de lo que haremos

Estos son los pasos por los que pasará este tutorial:

  1. Instale Node.js y npm en su computadora
  2. Instale Gulp y otros paquetes necesarios para su proyecto
  3. Configure su archivo gulpfile.js para ejecutar las tareas que desee
  4. ¡Deje que su computadora haga el trabajo por usted!

No se preocupe si no comprende totalmente todos los términos anteriores. Te lo explicaré todo paso a paso.

¡Ahora comencemos!

Configura tu entorno

Node.js

Para poner Gulp en funcionamiento en su computadora, debe instalar Node.js en su entorno local.

Node.js se describe a sí mismo como un "tiempo de ejecución de JavaScript", que se considera el back-end de JavaScript. Gulp se ejecuta con Node, por lo que es comprensible que deba instalar Node antes de comenzar.

Puede descargarlo del sitio web de Node.js. Cuando instala Node, también instala npm en su computadora.

¿Qué es npm, preguntas?

Npm (Administrador de paquetes de nodo)

Npm es una colección continuamente actualizada de complementos de JavaScript (llamados paquetes), escritos por desarrolladores de todo el mundo. Gulp es uno de esos complementos. También necesitará algunos más, que veremos más adelante.

La belleza de npm es que le permite instalar paquetes directamente en su línea de comandos. Esto es genial, porque no tiene que ir manualmente al sitio web, descargar y ejecutar el archivo para instalar.

Aquí está la sintaxis básica para instalar un paquete:

npm install [Package Name]

Nota para usuarios de Mac:

Dependiendo de su configuración, es posible que deba agregar la palabra clave "sudo" al principio para ejecutar esto con permisos de root.

Entonces, para Mac, se vería así:sudo npm install [Package Name]

Parece bastante sencillo, ¿verdad?

La carpeta node_modules

Una cosa a tener en cuenta: cuando instala un paquete npm, npm crea una carpeta llamada node_modules y almacena todos los archivos del paquete allí.

Si alguna vez ha tenido un proyecto con una carpeta node_modules y se atrevió a ver lo que contenía, probablemente vio que tenía muchas (y me refiero MUCHAS) de carpetas y archivos anidados.

¿Por qué pasó esto?

Bueno, esto se debe a que los paquetes npm tienden a depender de otros paquetes npm para ejecutar su función específica. Estos otros paquetes se conocen como dependencias.

Si está escribiendo un complemento, tiene sentido aprovechar las funcionalidades de los paquetes existentes. Nadie quiere reinventar la rueda cada vez.

Así que cuando se instala un plugin en sus node_modules carpeta, ese plugin entonces instalar paquetes adicionales que se necesita en su carpeta propios node_modules.

Y así sucesivamente hasta que haya anidado las carpetas del wazoo.

No necesita preocuparse demasiado por meterse en la carpeta node_modules en este punto; solo quería explicar brevemente lo que está sucediendo en esa carpeta loca.

Hacer un seguimiento de los paquetes con package.json

Otra característica interesante de npm es que puede recordar qué paquetes específicos ha instalado para su proyecto.

Esto es importante en caso de que tenga que reinstalar todo por algún motivo.

También les facilita la vida a otros desarrolladores, ya que pueden instalar rápida y fácilmente todos los paquetes para su proyecto en sus computadoras.

¿Cómo se las arregla para hacer esto?

Npm utiliza un archivo llamado package.json para realizar un seguimiento de los paquetes y las versiones de paquetes que ha instalado. También almacena otra información sobre el proyecto, como su nombre, autor y repositorio de Git.

Creando su package.json

Para inicializar este archivo, puede volver a utilizar la línea de comandos.

Primero, navegue a la carpeta de su proyecto, donde sea que lo tenga ubicado en su computadora.

Luego escribe el siguiente comando:

npm init

Luego, Npm le pedirá que ingrese información sobre el proyecto. Para la mayoría de las opciones, puede presionar enter y usar el valor predeterminado que está entre paréntesis.

Cuando haya terminado, npm generará el archivo package.json en la carpeta de su proyecto. Si lo abre en su editor, debería ver algo como esto:

{ "name": "super-simple-gulp-file", "version": "1.0.0", "description": "Super simple Gulp file", "main": "gulpfile.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+//github.com/thecodercoder/Super-Simple-Gulp-File.git" }, "keywords": [ "gulp" ], "author": "Jessica @thecodercoder", "license": "ISC", "bugs": { "url": "//github.com/thecodercoder/Super-Simple-Gulp-File/issues" }, "homepage": "//github.com/thecodercoder/Super-Simple-Gulp-File#readme" }

Por supuesto, para su proyecto tendrá su propio nombre e información en lugar de lo que tengo aquí.

En este punto, no me preocuparía por corregir todos los campos. Esta parte informativa se utiliza principalmente para paquetes que se publican en npm como complementos públicos.

Ahora, lo que pondrá en su archivo package.json es la lista de todos los paquetes que necesita para ejecutar Gulp.

Veamos cómo puedes agregarlos.

Instalación de paquetes

In the previous section above, we talked about typing: npm install [Package Name] into your command line to download and install the package into your node_modules folder.

It will install the package and automatically save it to your package.json file as a dependency.

Note: Prior to npm version 5.0.0, you had to add the flag “–save” in order for npm to add the package as a dependency. You no longer have to do that with versions 5 and up.

So if we want to install Gulp to our packages, we’d type in: npm install gulp.

It might take a minute or two for your computer to install everything related to Gulp. You will likely see some warning messages, but I wouldn’t worry about those unless the install fails.

Now, if you open your package.json file, you’ll see at the bottom that Gulp has been added as a dependency:

"dependencies": { "gulp": "^3.9.1" }

This list of dependencies will grow as you install additional npm packages.

Other packages needed for Gulp

Initially, we wanted to use Gulp to run tasks like compiling your SCSS/CSS and JavaScript files. To accomplish this, we’ll be using the following packages:

  • gulp-sass — compiles your Sass files into CSS
  • gulp-cssnano — minifies your CSS files
  • gulp-concat — concatenates (combines) multiple JavaScript files into one large file
  • gulp-uglify — minifies your JavaScript files

Just like before, install each package by typing these lines one by one. You’ll have to wait a few seconds while each one installs before going on to the next line.

npm install gulp-sass npm install gulp-cssnano npm install gulp-concat npm install gulp-uglify

Gulp-cli vs global Gulp

In the past, to be able to run “gulp” from your command line, you would have to install Gulp globally on your local computer, using the command:

npm install –global gulp

However, having a single global version of Gulp could cause issues if you have multiple projects all requiring different versions of Gulp.

The current consensus recommends installing a different package, Gulp-cli, globally instead of Gulp itself.

This will allow you to still run the “gulp” command, but you’re able to use different versions of Gulp across your different projects.

Here’s the code for that:

npm install --global gulp-cli

If you’re interested, you can read more context on this Treehouse thread.

All right, once all your packages are installed, you have all the tools you need. Let’s move on to setting up our project files!

Set up your file structure

Before we start creating files and folders, just know that there are many different ways to set up your file structure. The approach that you’ll be using is good for basic projects, but the “right” setup will depend a lot on what your particular needs are.

This basic method will help you get a grasp on the basic functionality of all the moving parts. Then you can build off or change the setup to your own liking in the future!

Here’s what the project tree will look like:

Root Project Folder

  • index.html
  • gulpfile.js
  • package.json
  • node_modules (folder)
  • app (folder)
  • script.js
  • style.scss
  • dist (folder)

We already went over the package.json file and the node_modules folder. And the index.html file will be, of course, your main website file.

The gulpfile.js file is where we’ll configure Gulp to run all the tasks we talked about at the beginning of this article. We’ll get into that in a bit.

But right now I want to mention the two folders, app and dist, as they’re important for the Gulp workflow.

App and dist folders

In the app folder, we have your basic JavaScript file (script.js) and your basic SCSS file (style.scss). Those files are where you will write all your JavaScript and CSS code.

The dist folder exists only to store the final compiled JavaScript and CSS files after Gulp has processed them. You shouldn’t make any changes in the dist files, only the app files. But these files in dist are what will be loaded in index.html, since we want to use the compiled files in the website.

Again, there are lots of ways you can set up your project files and folders. The main important thing to keep in mind is that your structure makes sense and allows you to work the most efficiently.

Now let’s get to the meat of this tutorial: configuring Gulp!

Create and configure your Gulpfile

The Gulpfile contains the code to load installed packages and run different functions. The code performs two basic functions:

  1. Initialize your installed packages as Node modules.
  2. Create and run Gulp tasks.

Initialize packages

In order to take advantage of all the features of the npm packages you added to your project, you need to export them as modules in Node — hence the folder name “node_modules”.

At the top of your Gulpfile, add the modules like this:

var gulp = require('gulp'); var cssnano = require('gulp-cssnano'); var sass = require('gulp-sass'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify');

Now that the packages are added, you can then use their functions and objects in your Gulpfile scripts. You’ll also be using some built-in functions that are part of Node.js.

If you want to read more about npm packages and Node modules, the npm site has a great explanation here.

Create your Gulp tasks

Creating a Gulp task is done by using the following code:

gulp.task('[Function Name]', function(){ // Do stuff here }

This allows you to run the Gulp task by typing in gulp [Function Name] into the command line. This is important because you can then run that named function from other Gulp tasks.

Specifically, we are building several different Gulp tasks, which will all be run when you run the default Gulp task.

Some of the main functions that we’ll be using are:

  • .task() — Creates a task, as mentioned above
  • .src() — identifies what files you will be compiling in a particular task
  • .pipe() — adds a function to the Node stream that Gulp is using; you can pipe multiple functions in the same task (read an excellent write-up on this topic on florian.ec)
  • .dest() — writes the resulting file to a specific location
  • .watch() — identifies the files to detect any changes

If you’re curious, you can read up more on the Gulp documentation here.

All set? Now let’s get down to business (cue Mulan music) and write those tasks!

These are the following tasks that we want Gulp to run:

  • Sass task to compile SCSS to a CSS file and minify
  • JavaScript task to concatenate the JavaScript files and minify/uglify
  • Watch task to detect when SCSS or JavaScript files are changed, and re-run the tasks
  • Default task to run all needed tasks when you type gulp into the command line

Sass task

For the Sass task, first we want to create the task in Gulp using task(), and we will name it “sass.”

Then we add in each component that the task will run. First we will designate that the source will be the app/scss/style.scss file, using src(). Then we will pipe in the additional functions.

The first one runs the sass() function — using the gulp-sass module which we called “sass” at the top of the Gulpfile. It will automatically save the CSS file with the same name as the SCSS file, so ours will be named style.css.

The second one minifies the CSS file with cssnano(). And the last puts the resulting CSS file in the dist/css folder.

Here’s the code for all that:

gulp.task('sass', function(){ return gulp.src('app/style.scss') .pipe(sass()) .pipe(cssnano()) .pipe(gulp.dest('dist/css')); });

To test, I just put in some filler SCSS in the style.scss file:

div { display: block; &.content { position: relative; } } .red { color: red; }

You can run each individual Gulp task on the command line if you type gulp and the name of the task. So to test the Sass task, I typed in gulp sass to check if it works without errors, and generates the minified dist/style.css file.

If everything works correctly, you should see messaging like this in your command line:

[15:04:53] Starting 'sass'... [15:04:53] Finished 'sass' after 121 ms

Checking in the dist folder shows that there is indeed a style.css file, and opening it shows correctly-minified CSS:

div{display:block}div.content{position:relative}.red{color:red}

Ok, our Sass task is now done. On to JavaScript!

JS task

The JS Gulp task is similar to the Sass task, but has a few different elements.

First we’ll create the task and call it “js,” then we’ll identify the source files. In the src() function, you can identify multiple files a couple different ways.

One is to utilize the wildcard (*) to tell Gulp to use all files with the *.js extension like this:

gulp.src('app/*.js')

However this will compile the files in alphabetical order, which could potentially cause errors if you end up loading scripts that are dependent on other scripts before those other script files.

You can control the order by manually designating each JavaScript file if you don’t have too many script files.

The src() function can take an array of values as a parameter, by using the square brackets like this:

gulp.src(['app/script.js', 'app/script2.js'])

If you do have a lot of JavaScript files, you can make sure that you load dependencies first by keeping them in a separate sub-folder, like say “app/js/plugins”. Then keep other JavaScript files in the parent “app/js” folder.

Then you can use the wildcard notation to load all lib (library) scripts, followed by regular scripts:

gulp.src(['app/js/lib/*.js', 'app/js/script/*.js'])

Your approach will vary depending on the number and types of JavaScript files you have.

Once you’ve set your source files, you’ll pipe in the remaining functions. The first is to concatenate the files into one large JavaScript file. The concat() function requires one parameter with the name of the resulting file.

Then you’ll uglify the JavaScript file, and save it in the destination location.

Here’s the complete code for the JS task:

gulp.task('js', function(){ return gulp.src(['app/js/plugins/*.js', 'app/js/*.js']) .pipe(concat('all.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); });

Just like the Sass task, you can test that the JS task works by typing in gulp js into the command line.

[14:38:31] Starting 'js'... [14:38:31] Finished 'js' after 36 ms

Now that we’ve finished our main two worker Gulp tasks, we can move on to the Watch task.

Watch task

The Watch task will watch the files that you tell it to for any changes. Once it detects a change, it will run the tasks that you designate and then continue watching for changes.

We will create two watch functions, one to watch SCSS files and the other to watch JavaScript files.

The watch() function takes two parameters: the source location, and then the tasks to run when a change is detected.

The Sass Watch function will watch any SCSS files in the app folder and then run the Sass task if it detects changes.

The function will look like this:

gulp.watch('app/*.scss', ['sass']);

For the JS Watch function, we’ll have to take advantage of a really useful Node feature called “globbing.” Globbing refers to using the “**” symbols as a kind of wildcard for folders and subfolders. We need it for the JavaScript files, because we have a JavaScript file in the app/js folder, and a JavaScript file in the app/js/plugins folder.

And here’s what that function will look like:

gulp.watch('app/js/**/*.js', ['js']);

The way the glob (“**”) works is it will look for JavaScript files anywhere in the app/js folder. It will look either directly in the folder or in any subsequent child folders, like the plugins folder. Globbing comes in handy so that you don’t have to designate each sub-folder as a separate source in the watch() function.

Here’s the complete Watch task:

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

Now we’re almost done! The last task to create is the default Gulp task.

Default Gulp task

The default Gulp task is what you want to run when you just type in gulp in the command line. When you create the task, you have to call it “default” in order for Gulp to recognize that that’s what you want to run.

What we’d like to do is run the Sass and JS tasks once, then run the Watch task to re-run tasks when files are changed.

gulp.task('default', ['sass', 'js', 'watch']);

You can create other tasks to run your builds, just don’t reuse the “default” name. For instance, let’s say you want to leave your CSS and JavaScript files unminified by default, but you do want to minify them for production.

You could create separate Gulp tasks to minify your CSS and JavaScript files called “minifyCSS” and “minifyJS.” Then you wouldn’t add those tasks to your default Gulp task, but you could create a new Gulp task called “prod” that has everything the default task has, and also has your minify tasks.

References in your index.html

Once you’ve gotten your Gulp process working, make sure that your index.html file references all the correct CSS and JavaScript files.

For the examples I’ve given you here, you’ll want to add a CSS reference to dist/style.css in your :

And add a script tag referencing dist/all.js in your :

In closing

Congrats on making it through! I hope that you found this basic Gulp tutorial helpful.

Like I mentioned at the beginning, this is just a very simple tutorial of the basics of npm and Gulp.

Most devs add many additional tasks to their Gulpfile. Let me know if you’d be interested to see another article on those more advanced topics!

Lastly, you can check out all the code from this tutorial on my GitHub account here.

I hope you found this post helpful! Let me know any thoughts you have in the comments below.

Want more?

  • Read more tutorials on my blog, coder-coder.com.
  • Sign up here to get emails about new articles.
  • Join 25,000+ others — Follow @thecodercoder on Instagram.
  • Check out coding tutorials on my YouTube channel.

This post was originally published on Coder-Coder.com.