Super jednostavan vodič za gutljaj za početnike

U današnje vrijeme upotreba alata za izradu neizostavan je dio vašeg procesa izrade web stranica.

Gulp je jedan od najpopularnijih alata za izgradnju danas - zajedno s Webpackom.

Ali postoji određena krivulja učenja za učenje Gutljaja. Jedna od najvećih prepreka je otkrivanje naizgled stotina različitih dijelova koji ulaze u to.

A povrh svega, morate učiniti sve na naredbenom retku, što može biti nevjerojatno zastrašujuće ako niste puno radili s tim.

Ovaj tutorial vodit će vas kroz osnove npm (Node Package Manager) i postavljanje Gulpa za vaše front-end projekte. Kad završite, osjećat ćete se puno sigurnije u postavljanju procesa rada i upotrebi naredbenog retka!

Pa u čemu je problem s Gulpom?

Gutljaj štedi vrijeme. Korištenjem Gulpa možete računalu dopustiti dosadne zadatke, kao što su:

  • Kompiliranje Sass datoteka u CSS
  • Spajanje (kombiniranje) više JavaScript datoteka
  • Umanjivanje (komprimiranje) CSS i JavaScript datoteka
  • I automatski pokretanje gore navedenih zadataka kada se otkrije promjena datoteke

Gulp može raditi puno složenije zadatke od onih koje sam gore spomenuo. Međutim, ovaj će se vodič fokusirati samo na osnove Gulpa i kako to funkcionira.

Kratki pregled onoga što ćemo raditi

Evo koraka kroz koje će proći ovaj vodič:

  1. Instalirajte Node.js i npm na svoje računalo
  2. Instalirajte Gulp i ostale pakete potrebne za vaš projekt
  3. Konfigurirajte datoteku gulpfile.js za pokretanje zadataka koje želite
  4. Neka vaše računalo radi vaš posao umjesto vas!

Ne brinite ako ne razumijete u potpunosti sve gornje uvjete. Sve ću objasniti korak po korak.

Sad krenimo!

Postavite svoje okruženje

Node.js

Da biste pokrenuli i pokrenuli Gulp na svom računalu, morate instalirati Node.js u svoje lokalno okruženje.

Node.js je sam opisan kao "JavaScript runtime", što se smatra pozadinom JavaScript-a. Gulp se izvodi pomoću Nodea, tako da je razumljivo da morate instalirati Node prije početka.

Možete ga preuzeti s web mjesta Node.js. Kada instalirate Node, on također instalira npm na vaše računalo.

Što je npm, pitate se?

Npm (Upravitelj paketa čvorova)

Npm je kontinuirano ažurirana zbirka JavaScript dodataka (nazvanih paketi), koju su napisali programeri širom svijeta. Gulp je jedan od tih dodataka. Trebat će vam i nekoliko više, o čemu ćemo kasnije.

Ljepota npm-a je u tome što vam omogućuje instaliranje paketa izravno na naredbeni redak. To je sjajno, jer ne morate ručno ići na web mjesto, preuzimati i izvršavati datoteku za instalaciju.

Evo osnovne sintakse za instaliranje paketa:

npm install [Package Name]

Napomena za korisnike Maca:

Ovisno o vašoj postavci, možda ćete na početku morati dodati ključnu riječ "sudo" da biste je pokrenuli s root dopuštenjima.

Dakle, za Macove bi to izgledalo ovako:sudo npm install [Package Name]

Čini se prilično izravno, zar ne?

Mapa node_modules

Treba napomenuti jednu stvar: kada instalirate npm paket, npm stvara mapu zvanu node_modules i tamo pohranjuje sve datoteke paketa.

Ako ste ikad imali projekt s mapom node_modules i usudili se vidjeti što sadrži, vjerojatno ste vidjeli da ima puno (i mislim puno) ugniježđenih mapa i datoteka.

Zašto se to događa?

Pa, to je zato što se npm paketi obično oslanjaju na druge npm pakete kako bi pokrenuli svoju specifičnu funkciju. Ovi ostali paketi poznati su kao ovisnosti.

Ako pišete dodatak, ima smisla iskoristiti funkcije postojećih paketa. Nitko ne želi svaki put izmisliti kotač.

Dakle, kada instalirate dodatak u svoju mapu node_modules, taj će dodatak instalirati dodatne pakete koji su mu potrebni u vlastitu mapu node_modules.

I tako dalje i tako dalje dok ne ugnijezdiš mape u wazoo.

Ne trebate se previše brinuti oko petljanja u mapi node_modules u ovom trenutku - samo sam želio ukratko objasniti što se događa u toj ludoj mapi.

Praćenje paketa pomoću package.json

Još jedna sjajna značajka npm-a je ta što se može sjetiti koje ste specifične pakete instalirali za svoj projekt.

To je važno u slučaju da iz nekog razloga sve morate ponovo instalirati.

Također olakšava život drugim programerima, jer mogu brzo i jednostavno instalirati sve pakete za vaš projekt na svoja računala.

Kako to uspijeva?

Npm koristi datoteku nazvanu package.json da bi pratio koje ste pakete i koje verzije paketa instalirali. Također pohranjuje i druge informacije o projektu, poput imena, autora i Git spremišta.

Izrada vašeg paketa.json

Da biste inicijalizirali ovu datoteku, možete ponovno upotrijebiti naredbeni redak.

Prvo se pomaknite do mape vašeg projekta, ma gdje se nalazila na vašem računalu.

Zatim upišite sljedeću naredbu:

npm init

Npm will then prompt you to enter in information about the project. For the majority of options, you can hit enter and use the default value that’s in parentheses.

When you’re done, npm will generate the package.json file in your project folder! If you open it up in your editor, you should see something like this:

{ "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" }

Of course, for your project you’ll have your own name and information instead of what I have here.

At this point I wouldn’t worry about getting all the fields correct. This informational part is mainly used for packages that get published to npm as public plugins.

Now, what you will be putting into your package.json file is the list of all the packages that you need for running Gulp.

Let’s see just how you can add them in.

Installing packages

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.