Gulp 4
Introduction
Gulp is a task manager for automatically performing frequently used tasks.
(e.g. minification, testing, file combining) written in
JavaScript
programming language.
Software uses command line to run tasks defined in the
Gulpfile.js
.
Created as an offshoot of the Grunt project to take best practices from it.
Gulp is distributed through
NPM
package manager under MIT license.
If you copy the code from this page - keep in mind that I put in some places extra
spaces - solely to improve readability on some screens. Feel free to delete them.
This is the main article about using Gulp. At the moment, you can also read articles in addition to this:
How to copy a folder using Gulp | |
How to send files via ftp using Gulp | |
Gulp series | |
Processing only modified files with gulp.watch().on('change') |
Installation
Consider installing using
npm
.
In the follwing manual it is assumed that you have already installed nmp.
Check how to install npm in my article
Installing npm
About how to install an older version of Gulp -
Install an archive version of Gulp
$ npm install gulp-cli --global
C:\Users\ao\AppData\
Roaming\npm\gulp ->
C:\Users\ao\AppData\Roaming\npm\
node_modules
\gulp-cli\bin\gulp.js
+ gulp-cli@2.2.0
updated 7 packages in 7.386s
Check Gulp version
To check Gulp version execute
gulp -v
CLI version: 2.2.0
Local version: Unknown
About installing not the latest, but some specific version of Gulp read here
Now you need to go to the directory in which you plan to work. I will make the site www.HeiHei.ru so I go to the directory
$ cd /c/Users/ao/Desktop/
Sites/heihei
Then go directly to installing gulp in the current project
$ npm install gulp --save-dev
By adding the --save-dev switch, we indicated that we now save to the dev branch, since Gulp
this is a package that we will use in development, but put it on hosting
we won’t, as he will not do anything on the site. All gulp work will be on
developer side.
Read more
docs.npmjs.com
Let's see how our pacakge.json file has changed
vi package.json
{
"name": "heihei",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"jquery": "^3.4.1",
"normalize.css": "^8.0.1"
},
"devDependencies": {
"gulp": "^4.0.2"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ao/heiheiru.git"
},
"bugs": {
"url": "https://github.com/ao/heiheiru/issues"
},
"homepage": "https://github.com/ao/heiheiru#readme"
}
The devDependencies section has appeared, in which in the future I will add quite a lot of packages.
If you now see the contents of the node_modules folder
you can see that the Gulp installation has added more than one folder, such as
I would make
jquery
and a few dozen.
Old versions
npm
always created one folder and placed all the dependencies there.
Newer versions of npm save dependencies in the parent folder node_modules.
Install an older version
Sometimes it is necessary to install not the current, but an earlier version of Gulp.
This is especially true for version 3.9.1, which is very different from 4 and above.
You can do this by adding the correct version after @
npm install gulp@3.9.1 --save-dev
npm install gulp-cli@1.2.1 --save-dev
The Gulp version list is here , Gulp-cli - here . You need to open the Versions tab
If you want to first uninstall your version of Gulp and only then install another one - do this can be done with the uninstall command
npm uninstall gulp
Gulpfile.js
After installing Gulp, you need to in the root directory of the project
(in my case - heiheiru)
create file gulpfile.js
in which we will write down instructions for Gulp.
The first thing we write down there
const gulp = require('gulp');
Starting with version 4.0, you can use the new JavaScript syntax (ES2015+)
import gulp from 'gulp'
But for this you need to install babel and make sure that there are no errors. I saw complaints on the forums myself have not tried it yet.
Details
www.npmjs.com
After the gulpfile.js file has been created can run gulp
gulp
The result will be a similar message
[11:22:35] Using gulpfile ~\Desktop\Sites\
heihei\gulpfile.js
[11:22:35] Task never defined: default
[11:22:35] To list available tasks, try running: gulp --tasks
Gulp complains that the default task is not defined - default task
Need to define it
vi gulpfile.js
const gulp = require('gulp');
gulp.task('default', function() {
console.log("Gulp is running!");
});
gulp
default will start but now Gulp will complain about an incomprehensible closure.
[11:31:44] Using gulpfile ~\Desktop\Sites\heihei\gulpfile.js [11:31:44] Starting 'default'... Gulp is running! [11:31:44] The following tasks did not complete: default [11:31:44] Did you forget to signal async completion?
This error can be fixed in several ways. ways . I use the following:
const gulp = require('gulp');
gulp.task('default', function(cb) {
console.log("Gulp is running!");
cb()
});
gulp
File organization
In order not to create mess from files and directories, we need to organize everything right from the very beginning.
Root directroy should have easy to understand name. Typically it is the name of your project. In this example it can be heihei or heiheiru
In this folder we need to initialize GIT and npm.
npm
will create a directory called node_modules
It will also create the following files:
package.json
and
package-lock.json
.
It is also a good moment to create a
.gitignore
file.
We are using Gulp which means that there will be a
gulpfile.js
With the growing number of tasks that Gulp will perform, it will become inconvenient for us to store them all in one
file.
In
gulpfile.js
we will only import other .js files according to the principle - for each job one file.
To store these files we will need a folder, let's call it gulp and create it in the root. Inside it, create
Tasks subfolder
All that relates directly to the site put in a folder heiheiru/app
index.html
will put to the root app and
.css files, pictures and scripts we put into following directories
heiheiru/app/assets/styles
heiheiru/app/assets/images
heiheiru/app/assets/scripts
This will look like a folder tree in the editor Sublime
Gulp Usecases
A simple example is a task that recursively copies a folder and writing logs.
This case is explained in the
«How to copy a folder using Gulp»
article.
More complex example -
«How to send files via ftp using Gulp»
Processing Style Files
Metalanguages like SASS can save a lot of time by reducing manual work.
Install it using npm
npm install gulp-sass --save-dev
Now you can declare a sass variable and use this preprocessor
const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require( 'browser-sync' ).create();
gulp.task('default', function(done) {
console.log("Gulp is running!");
done();
});
// compile scss into css
function style() {
// 1. show the location .scss файлов
return gulp.src('./scss/**/*.scss')
// 2. passing them through sass compiller
.pipe(sass())
// 3. specify the CSS file into which the result is written
.pipe(gulp.dest( './css/style.css' ) )
}
exports.style = style;
const and let - have been introduced in JavaScript since ES6 and for modern JavaScript are a better option than var
gulp-watch
gulp-watch is the name of a Gulp plugin that tracks file changes. Starting from the fourth
Gulp version gulp-watch is included in the main package and does not require separate installation.
Let's start with a simple one - we make a function that each time the
index.html
file is changed to
The app folder will display a warning.
What it looks like in Gulp 4
// include gulp
// no need to include gulp-watch separately
// it is included to Gulp starting from version 4
const gulp = require('gulp');
// function that will log all changes
function html() {
console.log("index.html was edited!");
}
// function that monitors index.html
// you can name it watch, but for this time
// I prefer watchFiles
// you will see the reason later when we do exports
function watchFiles() {
gulp.watch( "./app/assets/index.html", html);
}
// To call our functions from the outside,
// e.g. from GitBash we write exports
// To the left we write name that we want to use outside,
// To the right there are our functions local names
exports.html = html;
exports.watch = watchFiles;
To start monitoring write
gulp watch
[20:12:19] Using gulpfile ~\Desktop\Sites\heihei\gulpfile.js
[20:12:19] Starting 'watch'...
Change something in index.html and save
[20:14:28] Starting 'html'...
Someone edited index.html!
In Gulp 3 it used to look like this:
// Importing gulp и gulp-watch
const gulp = require('gulp')
watch = require('gulp-watch');
gulp.task('html', function() {
console.log( "Someone edited index.html!");
}
gulp.task('watch', function() {
watch( './app/assets/index.html', function() {
gulp.start('html');
});
});
Create a directory
/app/assets/styles/
To keep all .css filsed for development
We will write a function that will collect all the .css files from this folder, process them using sass,
and merge them into a single file. Someone has edited. Someone has edited.
/app/temp/styles/style.css
We already wrote such a function above, just change it a little.
Add .css file monitoring
gulp.watch("./app/assets/styles/**/*.css", style);
function style() {
console.log("style is running!");
// 1.
return gulp.src("./app/assets/styles/*.css" )
// 2. pass that file through sass compiller
.pipe(sass())
// 3. where do I save the compiled CSS?
.pipe( gulp.dest( './app/temp/styles/style.css' ) )
}
function watchFiles() {
gulp.watch("./app/assets/index.html", html);
gulp.watch("./app/assets/styles/**/*.css", style);
}
Now, as soon as we edit one of the styles files, watch will notice this change, pass it through sass, and collect all the files into one.
Why do we need SASS:
to use css variables. Create a variable, which then
embed in .css pass through sass compiler and when suddenly you need to be everywhere
change the value of this variable, for example, the main color will change on the site, everything
what we will need to do is change one variable in one file.
to do style attachments (nested css)
to use mixins
PostCSS
Previously, you already read about the SASS preprocessor, which along with LESS and Stylus is the standard
for many projects.
I do not use them, but prefer the more modern PostCSS, which has a more modular
structure, and accordingly
more flexible and quick
Whatever pre or post processor you choose, you need to master working with it, learn
perform simple tasks and move on to more complex tasks such as
gulp.watch().on('change')
More details about PostCSS I put to
PostCSS
article.
You can read about PostCSS and return to this article or to one of the following, more
advanced chapters.
I did not post a description of working with PostCSS here, because it can be run
not just using gulp
Gulp Video Tutorials
Videos weigh a lot, so I dedicated a separate page for them - Gulp Video Tutorials
Errors
1
Error installing gulp. You perform
$ npm install gulp --save-dev
And in return you have
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\ao\Desktop\Sites\
heihei\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\ao\Desktop\Sites\
heihei\package.json'
npm WARN heihei No description
npm WARN heihei No repository field.
npm WARN heihei No README data
npm WARN heihei No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ gulp@4.0.2
added 314 packages from 217 contributors and audited 6490 packages in 30.037s
found 0 vulnerabilities
Most likely you did not initialize npm. Need to execute
npm init
Enter the required data (or just press Enter), after which the package.json file will be created and you can return to the gulp installation
2
events.js:174
throw er; // Unhandled 'error' event
^
CssSyntaxError: postcss-simple-vars: C:\Users\ao\Desktop\Sites\travel-site\app\assets\styles\modules\_large-hero.css:5:2: Undefined variable $aMadeUpVariable2
May be called, for example, by a nonexistent variable. Let's say you added a color as a variable, but nowhere has it been set.
3
If you start Gulp
gulp
And get something like:
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/
cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/
cjs/loader.js:789:10)
at Module.load (internal/modules/
cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/
cjs/loader.js:593:12)
at Function.Module._load (internal/modules/
cjs/loader.js:585:3)
at Module.require (internal/modules
/cjs/loader.js:692:17)
at require (internal/modules/
cjs/helpers.js:25:18)
at execute (C:\Users\ao\AppData\Roaming\npm\
node_modules\gulp-cli\lib\versioned\
^4.0.0\index.js:36:18)
at Liftoff.handleArguments (C:\Users\ao\AppData\Roaming\npm\
node_modules\gulp-cli\index.js:201:24)
at Liftoff.execute (C:\Users\ao\AppData\Roaming\npm\
node_modules\gulp-cli\
node_modules\liftoff\
index.js:201:12)
Most likely you are trying to use syntax ES2015+ and did not install babel or it works but incorrectly.
There are two ways out - to figure it out and configure, or switch to the old syntax with require.
Did you forget to signal async completion?
There are several ways to fix this error. I use the following:
const gulp = require('gulp');
gulp.task('default', function(cb) {
console.log("Gulp is running!");
cb();
});
5
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
This is a package incompatibility warning fsevents с Windows, as you can see здесь fsevents нужен для работы с iOS поэтому can just be ignored.
Error - Task function must be specified
I make out this error in the Gulp series article
No PostCSS Config found in
The solution is posted in the «Postcss: No PostCSS Config found in» article
Gulp | |
Concat multiple css to one | |
Send files via ftp with Gulp | |
Gulp series | |
Process only changed files with gulp.watch().on('change') | |
Copy Directory Gulp | |
Video Tutorials | |
JavaScript | |
NodeJS | |
NPM | |
Web |