JavaScript Development Space

Gulp 4 Crash Course - Installation, Setup and Launch

Add to your RSS feedOctober, 26th 202312 min read
Gulp 4 Crash Course - Installation, Setup and Launch

What is GulpJS?

GulpJS is an open-source JavaScript-based toolkit that runs on Node.js. It simplifies and automates a wide range of development tasks, including file concatenation, minification, transpilation, testing, and more. GulpJS utilizes a streaming approach to efficiently process files, making it an efficient and powerful tool for managing project assets.

Key Features and Benefits:

    1. Task Automation: GulpJS provides a straightforward and intuitive way to automate tasks in the front-end development workflow. By defining tasks using simple JavaScript functions, developers can automate repetitive processes, such as compiling Sass to CSS, bundling JavaScript modules, or optimizing images. GulpJS excels at reducing manual intervention, saving developers valuable time and effort.
    1. Streaming Build System: GulpJS leverages the concept of streams, which allows developers to process files as streams of data. This approach offers numerous advantages, such as improved performance, reduced memory consumption, and faster build times. GulpJS plugins, designed to work with streams, can be easily combined and customized to create complex workflows tailored to project requirements.
    1. Extensive Plugin Ecosystem: GulpJS boasts a vast ecosystem of plugins that extend its capabilities. These plugins cover a wide range of tasks, such as CSS preprocessing, JavaScript transpilation, image optimization, code linting, and more.
    1. Customizable Configuration: GulpJS offers a flexible configuration system, allowing developers to tailor their workflows according to project requirements. The configuration is typically done through a simple JavaScript file, making it easy to understand and modify.
    1. Improved Performance and Optimization: One of the primary goals of GulpJS is to enhance the performance of web applications. By leveraging GulpJS tasks such as minification, concatenation, and optimization of assets, developers can significantly reduce file sizes, improve loading times, and boost overall performance. GulpJS also enables efficient caching and ensures that only necessary changes are propagated, resulting in faster development iterations and enhanced user experiences.

Installation

1. Install the gulp globaly

npm install --global gulp-cli

2. Create a new project

mkdir newproj && cd newproj

3. Install the gulp locally

npm install --save-dev gulp

4. Create a file named gulpfile.js in the root of your project directory

This file will contain your Gulp tasks.

5. Create folders src and dist

mkdir src && mkdir dist

6. Create an index.html file inside the src folder

Put a blank HTML code. Just type ! and hit Tab.

Add stylesheet link to css/style.min.css

Add script link to js/index.min.js

html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Document</title>
7 <link rel="stylesheet" href="css/style.min.css" />
8 </head>
9 <body>
10 <script src="js/index.min.js"></script>
11 </body>
12 </html>

7. Create folder scss inside your src folder

cd src && mkdir scss

8. Create file style.scss inside your scss folder

9. Create folder js inside src with file index.js

10. Create also folders fonts and images inside src folder

Current folders structure Current folders structure

Defining Gulp Tasks and Install Plugins:

1. Gulp Sass

It enables to automate the compilation of Sass (Syntactically Awesome Style Sheets) files into CSS. Sass is a powerful preprocessor for CSS that introduces features like variables, nesting, mixins, and more, making CSS code more modular, maintainable, and efficient.

Install plugins gulp-sass and sass

npm install sass gulp-sass --save-dev

Add this code to you gulpfile.js file

js
1 const { src, dest } = require('gulp');
2 const concat = require('gulp-concat');
3 const scss = require('gulp-sass')(require('sass'));
4
5 function createStyles() {
6 return src('./src/scss/**/*.scss')
7 .pipe(scss({ outputStyle: 'compressed' }).on('error', scss.logError))
8 .pipe(dest('./src/css'));
9 }
10
11 exports.createStyles = createStyles;

In this example, it takes SCSS files from the src/scss directory, minifies them using the gulp-sass plugin, and outputs the minified files to the src/css directory.

Let's test a plugin.

Add some scss code to style.scss file

css
1 .some {
2 padding: 0;
3 .something {
4 margin: 0;
5 }
6 }

Now run in your Terminal.

gulp createStyles

Gulp will generate css folder with file style.css in the css directory. Inside the style.css file we will find minified css(not scss) styles.

Gulp4 current structure Gulp generated folder

To rename it to "style.min.css" we need another plugin - Gulp Concat.

2. Gulp Concat

Gulp Concat simplifies the process of concatenating JavaScript files, making your front-end development workflow more efficient. By combining multiple files into a single bundle, you can enhance the performance of your web applications and improve code organization and maintainability.

npm install gulp-concat --save-dev

After installing add this code before all pipes in your gulpfile.js

js
1 .pipe(concat('style.min.css'))

Now it's style.min.css :)

GulpfileJs gulpfile.js

3. gulp-uglify-es

Gulp Uglify-ES is a popular plugin that enables to automate the process of minifying and compressing JavaScript code. Minification involves removing unnecessary characters like whitespace, comments, and renaming variables to shorter names, without affecting the functionality of the code. This process significantly reduces the size of JavaScript files, resulting in faster downloads and improved performance.

npm install gulp-uglify-es --save-dev

Import gulp-uglify-es to your gulpfile

js
1 const uglify = require('gulp-uglify-es').default;

Declare a new function with name createScripts:

js
1 function createScripts() {
2 return src('./src/js/**/*.js').pipe(concat('index.min.js')).pipe(uglify()).pipe(dest('./src/js'));
3 }

Don't forget to export the new function:

js
1 exports.createScripts = createScripts;

Create some JavaScript file or files to test it.

4. Watching Files for Changes:

Gulp 4 provides a convenient way to watch files for changes and automatically trigger tasks. Here's an example of a watch task that triggers the 'createStyles', and 'createScripts' functions whenever a SCSS, or JS file is modified:

Import watch from gulp

js
1 const { src, dest, watch } = require('gulp');

Add function watching with code:

js
1 function watching() {
2 watch(['./src/scss/**/*.scss'], createStyles);
3 watch(['./src/js/**/*.js'], createScripts);
4 }

Export watching function:

js
1 exports.watching = watching;

Use the following command:

gulp watching

Now, whenever you save changes to a SCSS file in the src/scss directory, or JS files in the src/js directory, Gulp will automatically execute the right function.

5. Browsersync

Browsersync is a lightweight development server and synchronization tool that enables simultaneous testing and live reloading of web pages across multiple devices and browsers. It eliminates the need for manual refreshing or switching between devices during development. Browsersync injects updated CSS and reloads the page automatically whenever changes are made, allowing developers to see the results instantly across all connected devices.

npm i browser-sync --save-dev

Import a browserSync, create a new function, and export:

js
1 const browserSync = require('browser-sync').create();
2 function sync() {
3 browserSync.init({
4 server: {
5 baseDir: './src',
6 },
7 });
8 }
9 exports.sync = sync;

Add a new pipe at the end of the existing functions "createScripts" and "createStyles":

js
1 .pipe(browserSync.stream());

Add a new watch task in the watching function:

js
1 watch(['./src/**/*.html']).on('change', browserSync.reload);

6. Parallel Task Execution

Parallel task execution in Gulp 4 allows multiple tasks to run concurrently instead of sequentially. By executing tasks concurrently, time-consuming operations can be completed in parallel, resulting in faster overall build times. This enhancement is particularly beneficial for larger projects with complex build pipelines, as it maximizes system resources and reduces the time required to compile, transpile, minify, or process files.

Import parallel from gulp:

js
1 const { src, dest, watch, parallel } = require('gulp');

Add default export with all functions inside:

js
1 exports.default = parallel(createStyles, createScripts, watching, sync);

Run a command:

gulp

7. Gulp Autoprefixer

Gulp Autoprefixer simplifies the process of adding vendor prefixes to CSS properties, ensuring cross-browser compatibility and saving development time.

npm install gulp-autoprefixer --save-dev

Now you can to import autoprefixer:

js
1 const autoprefixer = require('gulp-autoprefixer');

Add this code as a first pipe in a createStyles functions:

js
1 .pipe(autoprefixer())

Make a .browserslistrc file in your working root or workspace directory with those strings in it:

js
1 # Supported Browsers
2 last 2 versions
3 IE 10
4 Safari 8

8. Gulp Build

Create build function:

js
1 function build() {
2 return src(['./src/css/**/*.min.css', './src/js/**/*.min.js', './src/**/*.html'], {
3 base: 'src',
4 }).pipe(dest('dist'));
5 }

It will take your minified files and copy them into the dist folder.

Export build function:

js
1 exports.build = build;

Now run the build

gulp build

9. Gulp Clean

gulp-clean is a plugin that provides a simple and efficient way to delete files and directories within your project. Clean automates the process of removing unnecessary files or directories from your project. In our case, we will remove dist folder every time before running the build.

npm install gulp-clean --save-dev

Import clean:

js
1 const clean = require('gulp-clean');

Create function cleanProject and export it:

js
1 function cleanProject() {
2 return src('dist/**').pipe(clean());
3 }
4 exports.cleanProject = cleanProject;

10. Series

Series is a function provided by Gulp that allows your to define a sequence of tasks to be executed in a specific order. It ensures that each task is completed before moving on to the next one.

Import series from gulp

js
1 const { series } = require('gulp');

Change the build export to:

js
1 exports.build = series(cleanProject, build);

Run the new build:

gulp build

Implementing Image Minification in Gulp:

Optimizing images is a crucial step in improving website performance and user experience. This optimization technique eliminates unnecessary data from image files, such as metadata, comments, and color profiles. By minimizing the file size, websites can load faster, reducing bandwidth consumption and enhancing user experience across various devices and network conditions.

1. Install plugins:

gulp-avif - for convertation PNG and JPG images to AVIF.

gulp-webp - for convertation PNG, JPEG, TIFF to WebP.

gulp-imagemin - for compression GIF, JPEG, PNG, and SVG. Version 7.1.0 for using in CommonJS modules.

npm install gulp-avif gulp-webp gulp-imagemin@7.1.0 --save-dev

Import plugins

js
1 const avif = require('gulp-avif');
2 const webp = require('gulp-webp');
3 const imagemin = require('gulp-imagemin');

Create folder src inside images folder (/src/images/src).

2. Create images function:

js
1 function createImages() {
2 return (
3 src(['./src/images/src/**/*.*', '!./src/images/src/**/*.svg'])
4 // run gulp-avif with 50% quality
5 .pipe(avif({ quality: 50 }))
6 // back to our source folder
7 .pipe(src('./src/images/src/**/*.*'))
8 // run webp
9 .pipe(webp())
10 .pipe(src('./src/images/src/**/*.*'))
11 .pipe(imagemin())
12 .pipe(dest('./src/images'))
13 );
14 }

Gulp will process the images from the specified source directory (src/images/src/*), optimize them using gulp-imagemin, and save the optimized versions in the destination directory (src/images/dist/).

Put some images inside images/src folder and run images function (of course you need to export it before). As a result, you can see that every image has been also converted into AVIF and WEBP formats. Thanks to gulp-webp, and gulp-avif plugins.

3. Time-saving:

npm install gulp-newer --save-dev

gulp-newer is a Gulp plugin that helps minimize task execution time by processing only those files that have been modified or added since the last execution.

Run the gulp-newer before every plugin in images function:

js
1 function images() {
2 return (
3 src(['./src/images/src/**/*.*', '!./src/images/src/**/*.svg'])
4 // avoid loading processed images
5 .pipe(newer('./src/images'))
6 .pipe(avif({ quality: 50 }))
7 .pipe(src('./src/images/src/**/*.*'))
8 // ...
9 .pipe(newer('./src/images'))
10 .pipe(webp())
11 .pipe(src('./src/images/src/**/*.*'))
12 // ...
13 .pipe(newer('./src/images'))
14 .pipe(imagemin())
15 .pipe(dest('./src/images'))
16 );
17 }

Add images to watching function:

js
1 watch(['./src/images/src/**/*.*'], images);

Add images function to default export, inside a parallel function:

js
1 exports.default = parallel(createStyles, createScripts, images, watching, sync);

Add another path to building function:

js
1 './src/images/*.*';

4. Install plugin for svg optimization

npm install gulp-svg-sprite --save-dev

gulp-svg-sprite is a plugin that automates the creation of SVG spritesheets. It takes a collection of SVG files and generates a single sprite file that contains all the individual SVG icons.

Import plugin:

js
1 const svgSprite = require('gulp-svg-sprite');

Add a new function for the SVG sprite:

js
1 function createSvg() {
2 return src('./src/images/src/*.svg')
3 .pipe(
4 svgSprite({
5 mode: {
6 stack: {
7 sprite: '../sprite.svg',
8 example: true,
9 },
10 },
11 }),
12 )
13 .pipe(dest('./src/images'));
14 }

Fonts

Fonts play a crucial role in web design, contributing to the overall aesthetics and user experience of a website. However, using multiple font files can impact page load times and performance.

Font optimization involves reducing the file size of fonts without sacrificing quality. Optimized fonts contribute to faster page load times, improved website performance, and enhanced user experience, especially on devices with slower network connections. By minimizing font file sizes, developers can effectively mitigate the performance impact caused by multiple font files.

Install plugins

gulp-fonter is a plugin that enables developers to convert font files from one format to another seamlessly. It automates the process of generating web-compatible font files, including formats such as TrueType (TTF), Web Open Font Format (WOFF), and WOFF2.

gulp-ttf2woff2 is a Gulp plugin that automates the conversion of TrueType fonts (TTF) to the WOFF2 format. WOFF2 provides better compression and faster load times compared to other font formats, making it ideal for web usage.

npm install gulp-fonter gulp-ttf2woff2 --save-dev

Import fonts plugins

js
1 const fonter = require('gulp-fonter');
2 const ttf2woff2 = require('gulp-ttf2woff2');

Create src forder inside fonts.

Add a new createFonts function:

js
1 function createFonts() {
2 return src('./src/fonts/src/*.*')
3 .pipe(fonter({ formats: ['woff', 'ttf'] }))
4 .pipe(src('./src/fonts/*.ttf'))
5 .pipe(ttf2woff2())
6 .pipe(dest('./src/fonts'));
7 }

Add exports and modify the build function:

js
1 './src/fonts/*.*',

Our build function method right now looks like this:

js
1 function build() {
2 return src(
3 [
4 './src/css/**/*.min.css',
5 './src/images/**/*.*',
6 '!./src/images/**/*.svg',
7 './src/images/sprite.svg',
8 './src/js/**/*.min.js',
9 './src/fonts/*.*',
10 './src/**/*.html',
11 ],
12 { base: 'src' },
13 ).pipe(dest('dist'));
14 }

Now you can download some fonts from Google fonts and test your fonts function.

Pages and Components: install gulp-include

gulp-include is a Gulp plugin that simplifies the process of including partial files in your project. It provides a straightforward mechanism for splitting code into smaller, manageable pieces and reusing them across multiple files. The plugin leverages a special syntax to define placeholders that can be easily replaced with the content of the corresponding partial files during the build process.

npm install gulp-file-include --save-dev

Create folders pages and components inside src, and move index.html file to pages.

Move index.html to pages folder, and create header.html and footer.html inside the components directory.

GulpfileJs Current Gulp structure

Import gulp-include:

js
1 const include = require('gulp-include');

Create includes function:

js
1 function includes() {
2 return src('./src/pages/**/*.html')
3 .pipe(
4 include({
5 includePath: './src/components/',
6 }),
7 )
8 .pipe(dest('./src'))
9 .pipe(browserSync.stream());
10 }

Add new directories to your watching method:

js
1 watch(['./src/components/**/*.html', './src/pages/**/*.html'], includes);

Let's test it:

Run gulp clean, and decompose the index.html by header and footer inside the components folder.

Our header.html example:

html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Document</title>
7 <link rel="stylesheet" href="css/style.min.css" />
8 </head>
9 <body>
10 <header>Header</header>
11 </body>
12 </html>

Our footer.html example

html
1 <footer>
2 Footer
3 <script src="js/index.min.js"></script>
4 </footer>
5 </body>
6 </html>

Our index.html example (inside pages folder)

html
1 <!--=include header.html -->
2 <main>main</main>
3 <!--=include footer.html -->

Run gulp...if everything goes well, Gulp will automatically combine the files into index.html.

Check this github repository for full code from the tutorial.

Related Posts:

Create Your Own HTML5 Tag With ChatGPT Autocomplete, Text Replacement, or Translation

Learn how to create custom elements in HTML5 using the Web Components API. This guide covers defining, registering, and using custom elements with encapsulated styles and behaviors for reusable, modular web development.

The Best Way to Create Singleton Design Pattern in JavaScript and TypeScript

Discover the best practices for implementing the Singleton Design Pattern in JavaScript and TypeScript. This guide covers step-by-step instructions to ensure efficient and scalable code.

JavaScript Development Space

Follow JavaScript Development Space

Stay updated with the latest trends, tutorials, and best practices in JavaScript development. Follow our JavaScript Development blog for expert insights, coding tips, and resources to enhance your web development skills.

© 2024 JavaScript Development Blog. All rights reserved.