Korištenje Gulpa 4 u vašem tijeku rada za Sass i JS datoteke

Ovaj je post izvorno objavljen na Coder-Coder.com.

Ovaj će vam vodič korak po korak objasniti kako postaviti Gulp 4 u svom tijeku rada, kao i kako migrirati iz Gulp 3 u Gulp 4 sintaksu.

Trebate li samo brzo navesti svoj Gulp 3 gulpfile.js da radi s Gulp 4? Kliknite ovdje da biste prešli točno na taj dio posta.
  1. Instalirajte gulp-cli na vaš naredbeni redak pokretanjem npm install gulp-cli -g.
  2. Instalirajte Gulp trčanjem npm install gulp.
  3. Instalirajte druge npm pakete za svoj Gulp tijek rada.
  4. Stvorite gulpfile.jsdatoteku u korijenu vašeg projekta.
  5. Uvezite svoje npm pakete kao module u vašu gulp datoteku.
  6. Dodajte svoje zadatke u datoteku gulp da biste sastavili SCSS / JS datoteke i pokrenuli zadatak gledanja.
  7. Pokrenite gulpnaredbu za pokretanje svih zadataka.

Što je Gulp i čime se bavi?

Gulp je alat koji će za vas pokretati razne zadatke u tijeku vašeg web razvoja. Moglo bi se nazvati paketom, alatom za izgradnju ili pokretačem zadataka. Svi oni znače otprilike isto.

Slični alati su Webpack i Grunt (iako Grunt brzo zastarijeva).

Evo što ćemo od Gulpa učiniti za nas:

  1. Sastavite naše Sass datoteke u CSS
  2. Dodajte prefikse dobavljača u naš CSS
  3. Umanjite našu konačnu CSS datoteku
  4. Spojite (tj. Kombinirajte) naše JS datoteke
  5. Zanemarite našu konačnu JS datoteku
  6. Premjestite konačne CSS / JS datoteke u našu /distmapu.

Prilično cool, zar ne ?!

Dakle, način na koji to funkcionira je da su sve vaše postavke i zadaci pohranjeni u gulpfile.jsdatoteku. I pokrenete Gulp na naredbenom retku.

Dobar dio u tome je što nakon što ste postavili gulpfile, lako ga možete ponovno koristiti za druge projekte. Dakle, uštedjeli ste vrijeme!

Prijeđimo na instaliranje i postavljanje Gulpa na računalu.

Instaliranje Gulp-a, pomoću radnog demo projekta

Da biste mogli pokrenuti Gulp, morat ćete instalirati nekoliko stvari:

  • Instalirajte Node.js ako ga još nemate.
  • Instalirajte uslužni program naredbenog retka Gulp pokretanjem npm install --global gulp-cli.

Jednom kada Gulp radi, pogledajte demo projekt koji sam izradio i koji koristi Gulp! To je projekt internetskog uzorka koji bi trebao biti brz način da započnem s bilo kojim jednostavnim web-mjestom.

(U ostatku ovog vodiča također imam dosta isječaka koda, tako da se možete i na njih pozvati!)

Da biste postavili projekt prednjeg kotla:

  • Klonirajte ili preuzmite Git repo ovog projekta na svoje računalo.
  • Otvorite projekt i u osnovnoj mapi projekta idite na naredbeni redak i pokrenite npm install. Ovo će instalirati npm pakete navedene u package.jsondatoteci, posebno Gulp 4.

Sada biste trebali postaviti projektne datoteke i instalirati sve npm pakete koje ćemo koristiti za pokretanje Gulp zadataka.

Budući da su datoteke iz repo-a spremne za rad, ako upišete u gulpnaredbeni redak, trebali biste vidjeti izlaz poput ovog:

> gulp [22:29:48] Using gulpfile ~\Documents\GitHub\frontend-boilerplate\gulpfile.js [22:29:48] Starting 'default'... [22:29:48] Starting 'scssTask'... [22:29:48] Starting 'jsTask'... [22:29:48] Finished 'jsTask' after 340 ms [22:29:48] Finished 'scssTask' after 347 ms [22:29:48] Starting 'watchTask'...

A vi ste pokrenuli Gulp!

Što se događa u projektu kada pokrenete Gulp?

U redu, projekt uspješno radi! Ajmo sada detaljnije o tome što je u projektu i kako to funkcionira.

Prvo, evo kratkog pregleda strukture datoteka našeg projekta:

  • index.html - vaša glavna HTML datoteka
  • package.json - sadrži sve npm pakete koje treba instalirati prilikom pokretanja npm install.
  • gulpfile.js - sadrži config i pokreće sve Gulp zadatke
  • / app - radna mapa, ovdje ćete uređivati ​​SCSS / JS datoteke
  • / dist - Gulp će ovdje prikazati datoteke, nemojte ih uređivati

U svom tijeku rada uređivat ćete HTML, SCSS i JS datoteke. Gulp će tada otkriti sve promjene i sve kompajlirati. Tada ćete konačne CSS / JS datoteke učitati iz /distmape u index.htmldatoteci.

Sad kad imamo Gulp, pogledajmo bliže kako Gulp djeluje.

Što se točno nalazi u gulpfile.js?

Evo detaljnog objašnjenja svakog odjeljka gulpfilea i onoga što oni rade:

Korak 1: Inicijalizirajte npm module

Na samom vrhu gulpfile.js, imamo čitavu hrpu konstanti koje uvoze npm pakete koje smo ranije instalirali, koristeći require()funkciju.

Evo što rade naši paketi:

Gutljaj paket:

  • gulp- pokreće sve u gulpfile.js. Mi smo izvoz samo funkcije specifične progutati da ćemo biti koristi, kao što su src, dest, watch, i drugi. To nam omogućuje da te funkcije zovemo izravno bez gulp, na primjer, možemo jednostavno upisati src()umjesto gulp.src().

CSS paketi:

  • gulp-sourcemaps - preslikava CSS stilove natrag u izvornu SCSS datoteku u razvojnim alatima vašeg preglednika
  • gulp-sass - kompajlira SCSS u CSS
  • gulp-postcss - pokreće autoprefixer i cssnano (vidi dolje)
  • autoprefixer - dodaje prefikse dobavljača u CSS
  • cssnano - umanjuje CSS
If you’ve used Gulp before, you might be wondering why I’m using straight-up autoprefixer and cssnano, instead of gulp-autoprefixer and gulp-cssnano. For some reason, using them will work, but will prevent sourcemaps from working. Read more about that issue here.

JS packages:

  • gulp-concat — concatenates multiple JS files into one file
  • gulp-uglify — minifies JS

Now that we have our modules added, let’s put them to work!

Step 2: Use the modules to run your tasks

A “task” in Gulp is basically a function that performs a specific purpose.

We’re creating a few utility tasks to compile our SCSS and JS files, and also to watch those files for any changes. Then those utility tasks will be run in our default Gulp task when we type gulpon the command line.

Creating constants for file paths

Before writing our tasks, though, we have a few lines of code that save our file paths as constants. This is optional, but I like using path variables so that we don’t have to manually retype them each time:

This code creates scssPath and jsPath constants that we will use to tell Gulp where files are found.

Sass task

Here’s the code for our Sass task:

function scssTask(){ return src(files.scssPath) .pipe(sourcemaps.init()) .pipe(sass()) .pipe(postcss([ autoprefixer(), cssnano() ])) .pipe(sourcemaps.write('.')) .pipe(dest('dist') );}

Our Sass task, called scssTask(), is doing several things. In Gulp, you can chain multiple functions by using the Gulp function pipe() after the first function.

In our task, Gulp is first running src() to load the source directory of the SCSS files. It’s using the constant we created earlier, files.scssPath.

Then after src() we’re piping everything else into the build process. You can think about it like adding more and more sections of pipe onto an existing pipe.

The functions it’s running are:

  • sourcemaps.init() — sourcemaps needs to be added first after src()
  • sass() does the compiling of all the SCSS files to one CSS file
  • postcss() runs two other plugins:
  • - autoprefixer() to add vendor prefixes to the CSS
  • - cssnano() to minify the CSS file
  • sourcemaps.write() creates the sourcemaps file in the same directory.
  • dest() tells Gulp to put the final CSS file and CSS sourcemaps file in the /dist folder.

JS task

Here’s the code for our JavaScript task:

function jsTask(){ return src([files.jsPath]) .pipe(concat('all.js')) .pipe(uglify()) .pipe(dest('dist') );}

Our JavaScript task, called jsTask(), is also running multiple functions:

  • src() to load the JS files from files.jsPath.
  • concat() to concatenate all the JS files into one JS file.
  • uglify() to uglify/minify the JS file.
  • dest() to move the final JS file into the /dist folder.

Watch task

The watch() function is a super handy part of Gulp. When you run it, it will run continuously, waiting to detect any changes to the files you tell it to watch. When it detects changes, it will run any number of tasks you tell it to.

This is great because then you don’t have to keep manually running gulp after every code change.

Here’s the code for our watch task:

function watchTask(){ watch( [files.scssPath, files.jsPath], parallel(scssTask, jsTask) );}

The watch() function takes three parameters, but we’re just using two:

  • globs, meaning the file path strings,
  • options (not used), and
  • tasks, meaning which tasks we want to run.

What we’re having our watch task do is watch the files in our scssPath and jsPath directories. Then if any changes are made in either, run the scssTask and jsTask tasks simultaneously.

Now that we’ve gotten our utility tasks set up, we need to set up our main Gulp task.

Default task

This is the main Gulp task, which will automatically run if you type in gulp on the command line.

exports.default = series( parallel(scssTask, jsTask), watchTask);

Gulp will automatically search for a default task in your gulpfile.js when you use the gulpcommand. So you must export the default task in order for it to work.

Our default task will do the following:

  • Run the scssTask and jsTask simultaneously using parallel()
  • Then run the watchTask

You’ll also notice that we are putting all those tasks inside the series() function.

This is one of the major new changes in Gulp 4 for how it handles tasks– you are required to wrap all tasks (even single ones) either in series() or parallel().

A note on registering tasks: what’s changed in Gulp 4

If you’ve been using the tasks() function to run everything, you may have noticed that there’s a difference now.

Instead of using gulp.task() to contain all your task functions, we’re creating actual functions like scssTask() and watchTask().

This is to follow Gulp’s official guidelines for creating tasks.

The Gulp team recommends using exports rather than tasks():

“In the past, task() was used to register your functions as tasks. While that API is still available, exporting should be the primary registration mechanism, except in edge cases where exports won’t work.” [Gulp Documentation]

So, while they still let you use the task() function, it’s more current to create JS functions for each task and then export them.

If you can, I’d recommend updating your syntax to reflect this, as it’s possible that Gulp will deprecate task() at some point.

Problems Migrating from Gulp 3?

If you’ve been using Gulp 3 and all you want is to get the dang thing working with Gulp 4, you’re in luck!

Before, in Gulp 3, you could simply list a single function or multiple functions in an array. However, in Gulp 4, doing so without wrapping them in either series() or parallel() will throw an error now.

Something like:

AssertionError [ERR_ASSERTION]: Task function must be specified

Gulp 4 introduces two new functions to run tasks: series() and parallel(). It gives you the option of running multiple tasks concurrently, or one after the other.

So to quickly fix the error, put all your tasks into either a series() or parallel()function.

Tasks in (old) Gulp 3 syntax

In Gulp 3, you might have run tasks this way:

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

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

Tasks in Gulp 4 syntax

Put those tasks into a series() function like this:

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

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

And that will fix the task function error with the smallest change possible! ?

Project files download

All the code I’ve displayed here is from a GitHub repository I have for front-end boilerplate. It’s meant as a quick starter kit for any simple front-end website project.

You’re welcome to check it out, customize, and use it for your own projects!

Check out the GitHub repository here.

In closing

I hope that you’ve found this walk-through of how to get Gulp 4 running helpful!

If you enjoyed this post or have a question, feel free to leave a comment below! ?

Want more?

? Read more tutorials on my blog, coder-coder.com.

? Sign up here to get emails about new articles.

? Join 24,000+ others — Follow @thecodercoder on Instagram.

? Check out coding tutorials on my YouTube channel.