Gulp: Basics
In this article we are going to cover the following topics:
- First Default Task
- JS uglify and minify
- Coping files
- Sass compilation
- Watchers
- Live Reload+Server
What is gulp?
- Automation — gulp is a toolkit that helps you automate painful or time-consuming tasks in your development workflow.
- Platform-agnostic — Integrations are built into all major IDEs and people are using gulp with PHP, .NET, Node.js, Java, and other platforms.
- Strong Ecosystem — Use npm modules to do anything you want + over 2000 curated plugins for streaming file transformations
- Simple — By providing only a minimal API surface, gulp is easy to learn and simple to use
Official Site: https://gulpjs.com/
Before we will start learn Gulp my suggestion will be to install Gulp as global module, you can do it simply running in your command line the following command:
npm install -g gulp
Project Structure:
Content:
index.html
<html>
<head>
<title>Greatest App</title>
<link rel="stylesheet" href="./src/css/main.css">
<script src="./src/js/main.js"></script>
</head>
<body>
<h1 class="main-header">Gulp.js</h1>
<p class="wiki-desc">
gulp.js is an open-source JavaScript toolkit by Fractal Innovations and the open
source community at GitHub, used as a streaming build system in front-end web development.
</p>
<p>
It is a task runner built on Node.js and npm, used for automation of time-consuming
and repetitive tasks involved in web development like minification, concatenation,
cache busting, unit testing, linting, optimization, etc.
</p>
<p>
gulp uses a code-over-configuration approach to define its tasks and relies on its small,
single-purposed plugins to carry them out. gulp ecosystem has 300+ such plugins
made available to choose from.
</p>
<div class="question-container">
<div class="question">
Do you like Gulp.js?
</div>
<button onclick="doYouLikeGulp('yes')">Yes, I like it</button>
<button onclick="doYouLikeGulp('no')">No</button>
</div>
</body>
</html>
main.css
body {
background: brown;
color: beige;
text-align: center;
margin-top: 200px;
}
.main-header {
padding: 20px 20px 0 20px;
font-family: cursive;
}
p {
padding: 0 20px 0 20px;
font-family: sans-serif;
}
.wiki-desc {
font-style: italic;
text-decoration: underline;
}
.question {
margin: 30px 30px;
}
button {
padding: 15px;
background: brown;
color: beige;
border: 2px solid;
cursor: pointer;
font-size: 1em;
margin-left: 15px;
outline: 0;
}
main.js
function doYouLikeGulp(bool) {
if (bool === 'yes') {
alert('Good choice!')
} else {
alert('Are you kidding, right?');
}
}
.gitignore
node_modules/
dist/
package.json
{
"name": "greatest-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Demo:
Great, now we have our basic project.
Ok, so now we should install Gulp to our dev dependencies and create gulpfile.js. In root directory using command line run the following commands:
npm install gulp --save-dev
touch gulpfile.js
Now we ready to go :)
We will start from gulp default task. In gulp file add following lines of code:
var gulp = require('gulp');gulp.task('default', function() {
console.log('Hello Gulp!');
});
In order to run it just run gulp in you command line and you will see ‘Hello Gulp!’ in your command line.
Now it’s time to build our application.
First we will uglify and minify our javascript files (currently we have only one). In order to do that we need to install gulp-uglify plugin and create task for it. Also we need to install pump, it is a small node module that pipes streams together and destroys all of them if one of them closes.
npm install --save-dev gulp-uglify
npm install pump --save-dev
Modify gulpfile.js:
let gulp = require('gulp'),
uglify = require('gulp-uglify'),
pump = require('pump');gulp.task('default', function() {
console.log('Hello Gulp!');
});gulp.task('build:js', function(callback) {
pump([
gulp.src('src/**/*.js'),
uglify(),
gulp.dest('dist')
], callback);
});
Run in command line:
gulp build:js
Here we are copy, modify and minify all javascript files from ./src directory to ./dist. Let’s take a look on result:
Now let’s create task for copying html and remap our app.
Provide new task in gulpfile.js:
gulp.task('copy:html', function () {
return gulp.src(__dirname+'/index.html').pipe(gulp.dest('dist'));
});
We are going to join both tasks together, since we do not want to run each task separately:
gulp.task('build', ['build:js', 'copy:html']);
Update script src attribute path to our main javascript file:
<script src="./js/main.js"></script>
Now our page should work from ./dist folder. All seems to be working except styles. But don’t worry at all, we are going to be ok with it and even make some great improvements.
We can for sure say that Sass is a fairly modern technology and deserves for our attention, many companies in the whole world currently are using it.
Sass is the most mature, stable, and powerful professional grade CSS extension language in the world. (you can find more details here).
Required steps for using Sass:
- Create folder sass in ./src directory:
cd src
mkdir sass
cd sass
2. Add main sass file:
touch main.scss
paste content of main.scss file in sass style:
body {
background: brown;
color: beige;
text-align: center;
margin-top: 200px; .main-header {
padding: 20px 20px 0 20px;
font-family: cursive;
} p {
padding: 0 20px 0 20px;
font-family: sans-serif; &.wiki-desc {
font-style: italic;
text-decoration: underline;
}
} .question-container {
.question {
margin: 30px 30px;
} button {
padding: 15px;
background: brown;
color: beige;
border: 2px solid;
cursor: pointer;
font-size: 1em;
margin-left: 15px;
outline: 0;
}
}
}
3. Remove ./css folder because we do not need it anymore:
rm -rf css
4. Install gulp-sass plugin as dev dependency:
npm install gulp-sass --save-dev
5. Add gulp task for building sass files:
...
var sass = require('gulp-sass');...
gulp.task('build:sass', function() {
return gulp.src('./src/sass/**/*.scss')
.pipe(sass.sync().on('error', sass.logError))
.pipe(gulp.dest('./dist/css'));
});
// and it should be added to build task list
gulp.task('build', ['build:js', 'build:sass', 'copy:html']);
6. Update link tag in index.html:
<link rel="stylesheet" href="./css/main.css">
And BOOM….
Now all is working again but with sass and by running only one gulp task.
Now I want to fall in conversation about watchers, because they are really important feature in scope of using Gulp.
You may ask why we need those watchers? And the answer will be pretty simple:
- because we do not want with each sass or javascript change run build!
What we really want is to run it once and just refresh page with already existed new changes.
So let’s implement watcher in our gulpfile.js.
gulp.task('watch', function(){
gulp.watch('./src/**/*', ['build']);
});
Yup, that’s all! Just run:
gulp watch
First of all you will see that watcher is running all the time (in order to quit just click Ctrl+C).
And if you modifying for example main.js file you will see that watch task is rebuilding your sources:
So after refresh you will see your application up to date.
Last thing that I want to discuss in current article is a live reload feature.
For this moment all was just great and we didn’t thought that browser can reload all changes by himself. So currently I do not have the words how gulp is useful for me.
But before we start to implement Live Reload feature let’s improve our watch task:
gulp.task('watch', function(){
gulp.watch('./src/js/*.js', ['build:js']);
gulp.watch('./src/scss/*.scss', ['build:sass']);
gulp.watch('./*.html', ['copy:html']);
});
What is going on here and why it’s improvement:
- On each change we are not building whole application but only part where was change
- We also added watcher for our index.html page
No we are ready to go with live reload!
- Install st node module (A module for serving static files. Does etags, caching, etc.):
npm install st --save-dev
2. Install gulp-livereload plugin:
npm install gulp-livereload --save-dev
3. Add Live Reload Support and add gulp task for running server:
let gulp = require('gulp')
, uglify = require('gulp-uglify')
, pump = require('pump')
, sass = require('gulp-sass')
, livereload = require('gulp-livereload')
, st = require('st')
, http = require('http');gulp.task('default', function () {
console.log('Hello Gulp!');
});gulp.task('build:js', function (callback) {
pump([
gulp.src('src/**/*.js'),
uglify(),
gulp.dest('dist'),
livereload()
], callback);
});gulp.task('copy:html', function () {
return gulp.src(__dirname+'/index.html')
.pipe(gulp.dest('dist'))
.pipe(livereload());
});gulp.task('build:sass', function () {
return gulp.src('./src/sass/**/*.scss')
.pipe(sass.sync().on('error', sass.logError))
.pipe(gulp.dest('./dist/css'))
.pipe(livereload());
});gulp.task('watch', function(){
livereload.listen();
gulp.watch('./src/js/*.js', ['build:js']);
gulp.watch('./src/scss/*.scss', ['build:sass']);
gulp.watch('./*.html', ['copy:html']);
});gulp.task('server', function(done) {
http.createServer(
st({ path: __dirname+'/dist', index: 'index.html', cache: false })
).listen(8081, done);
});gulp.task('build', ['build:js', 'build:sass', 'copy:html']);
4. Add chrome LiveReload extension (you can find it here).
5. Start server:
gulp server
6. Open second command line window and start watcher:
gulp watch
7. Open chrome browser with url http://localhost:8081/index.html
8. In chrome connect to live reload by clicking on live reload extension icon in right corner of browser
After those eight steps you are ready to go! All changes will be handled by Gulp and Live Reload feature will help you to see all changes without extra needed moves.
Conclusion
Thank you guys for reading. I hope you enjoyed it and learned some new stuff related to JavaScript. Please subscribe and press ‘Clap’ button if you like this article.