Gulp 4 Crash Course - Installation, Setup and Launch
Add to your RSS feed26 October 202312 min readWhat 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:
-
- 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.
-
- 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.
-
- 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.
-
- 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.
-
- 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
- Install the gulp globaly
- Create a new project
- Install the gulp locally
- Create a file named gulpfile.js in the root of your project directory
This file will contain your Gulp tasks.
- Create folders src and dist
- 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
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>
- Create folder scss inside your src folder
-
Create file style.scss inside your scss folder
-
Create folder js inside src with file index.js
-
Create also folders fonts and images inside src folder
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-devAdd this code to you gulpfile.js file
1 const { src, dest } = require('gulp');2 const concat = require('gulp-concat');3 const scss = require('gulp-sass')(require('sass'));45 function createStyles() {6 return src('./src/scss/**/*.scss')7 .pipe(scss({ outputStyle: 'compressed' }).on('error', scss.logError))8 .pipe(dest('./src/css'));9 }1011 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
1 .some {2 padding: 0;3 .something {4 margin: 0;5 }6 }
Now run in your Terminal.
gulp createStylesGulp 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.
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-devAfter installing add this code before all pipes in your gulpfile.js
1 .pipe(concat('style.min.css'))
Now it's style.min.css :)
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-devImport gulp-uglify-es to your gulpfile
1 const uglify = require('gulp-uglify-es').default;
Declare a new function with name createScripts:
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:
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
1 const { src, dest, watch } = require('gulp');
Add function watching with code:
1 function watching() {2 watch(['./src/scss/**/*.scss'], createStyles);3 watch(['./src/js/**/*.js'], createScripts);4 }
Export watching function:
1 exports.watching = watching;
Use the following command:
gulp watchingNow, 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-devImport a browserSync, create a new function, and export:
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":
1 .pipe(browserSync.stream());
Add a new watch task in the watching function:
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:
1 const { src, dest, watch, parallel } = require('gulp');
Add default export with all functions inside:
1 exports.default = parallel(createStyles, createScripts, watching, sync);
Run a command:
gulp7. 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-devNow you can to import autoprefixer:
1 const autoprefixer = require('gulp-autoprefixer');
Add this code as a first pipe in a createStyles functions:
1 .pipe(autoprefixer())
Make a .browserslistrc file in your working root or workspace directory with those strings in it:
1 # Supported Browsers2 last 2 versions3 IE 104 Safari 8
8. Gulp Build
Create build function:
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:
1 exports.build = build;
Now run the build
gulp build9. 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-devImport clean:
1 const clean = require('gulp-clean');
Create function cleanProject and export it:
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
1 const { series } = require('gulp');
Change the build export to:
1 exports.build = series(cleanProject, build);
Run the new build:
gulp buildImplementing 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-devImport plugins
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:
1 function createImages() {2 return (3 src(['./src/images/src/**/*.*', '!./src/images/src/**/*.svg'])4 // run gulp-avif with 50% quality5 .pipe(avif({ quality: 50 }))6 // back to our source folder7 .pipe(src('./src/images/src/**/*.*'))8 // run webp9 .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-devgulp-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:
1 function images() {2 return (3 src(['./src/images/src/**/*.*', '!./src/images/src/**/*.svg'])4 // avoid loading processed images5 .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:
1 watch(['./src/images/src/**/*.*'], images);
Add images function to default export, inside a parallel function:
1 exports.default = parallel(createStyles, createScripts, images, watching, sync);
Add another path to building function:
1 './src/images/*.*';
4. Install plugin for svg optimization
npm install gulp-svg-sprite --save-devgulp-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:
1 const svgSprite = require('gulp-svg-sprite');
Add a new function for the SVG sprite:
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-devImport fonts plugins
1 const fonter = require('gulp-fonter');2 const ttf2woff2 = require('gulp-ttf2woff2');
Create src forder inside fonts.
Add a new createFonts function:
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:
1 './src/fonts/*.*',
Our build function method right now looks like this:
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-devCreate 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.
Import gulp-include:
1 const include = require('gulp-include');
Create includes function:
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:
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:
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
1 <footer>2 Footer3 <script src="js/index.min.js"></script>4 </footer>5 </body>6 </html>
Our index.html example (inside pages folder)
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.