Gulp static site build
last modified November 15, 2026
In this article we build a complete static site with Gulp 5. One gulpfile compiles Sass, adds vendor prefixes and minifies
CSS with PostCSS, bundles JavaScript with esbuild, optimises images, minifies HTML, cleans the output and serves the site with Browsersync,
in a fast development mode and in a production mode.
The plan
This is the project the other tutorials of the series lead to: each of the tasks was described on its own, and now we put them together.
The sources are in src and the result goes to dist. The tasks are:
cleanremovesdist, see Gulp clean;stylescompiles Sass, see Gulp Sass, and runs PostCSS with Autoprefixer and cssnano, see Gulp PostCSS;scriptsbundles the modules with esbuild, see Gulp esbuild;imagesoptimises PNG and JPEG files with a small plugin of our own, see Gulp writing a plugin;htmlminifies the pages, see Gulp HTML minify;devbuilds the site, serves it and rebuilds on change, see Gulp Browsersync and Gulp watch.
The independent tasks run in parallel after the cleaning, see Gulp series and parallel.
In the development mode the output is readable and has source maps; in the production mode it is minified and has no source maps.
The mode is selected by the environment variable NODE_ENV, as in Gulp conditional pipelines.
Installing the project
We create an ES module project and install the tools. Besides Gulp, there is Sass and its Gulp plugin, PostCSS with Autoprefixer
and cssnano, esbuild, the HTML minifier, Browsersync, del and sharp, a fast image library. We use sharp directly instead of
gulp-imagemin, whose dependency tree reports vulnerabilities in npm audit.
$ mkdir gulp-site $ cd gulp-site $ npm init -y $ npm pkg set type=module $ npm i -D gulp sass gulp-sass postcss gulp-postcss autoprefixer cssnano esbuild gulp-html-minifier-terser browser-sync del sharp $ mkdir -p src/scss src/js src/img tools
The pages
The site has two pages with the same header; each loads the stylesheet and the script, and contains a comment and some whitespace, so that the minifier has something to remove. The images are a logo, an icon and a photograph.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="css/main.css">
<script src="js/main.js" defer></script>
</head>
<body>
<!-- site header -->
<header class="site-header">
<img src="img/logo.png" alt="Logo" width="64">
<nav>
<a href="index.html">Home</a>
<a href="about.html">About</a>
</nav>
</header>
<main>
<h1 id="title">Static site</h1>
<p>A small site built with Gulp 5.</p>
<img src="img/photo.jpg" alt="Photo" width="400">
</main>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>About</title>
<link rel="stylesheet" href="css/main.css">
<script src="js/main.js" defer></script>
</head>
<body>
<header class="site-header">
<img src="img/logo.png" alt="Logo" width="64">
<nav>
<a href="index.html">Home</a>
<a href="about.html">About</a>
</nav>
</header>
<main>
<h1 id="title">About</h1>
<p>This page is built from the same sources.</p>
</main>
</body>
</html>
The styles
The stylesheet is split into partials. The file _variables.scss defines the colours and the spacing, _layout.scss the header and the main area, and
main.scss is the entry point that loads them with @use. The declaration user-select is there for Autoprefixer.
$primary: #2a6f97; $text: #222; $gap: 1rem;
@use 'variables' as v;
.site-header {
display: flex;
align-items: center;
gap: v.$gap;
padding: v.$gap;
border-bottom: 2px solid v.$primary;
nav a {
margin-right: v.$gap;
color: v.$primary;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
}
main {
max-width: 40rem;
margin: 0 auto;
padding: v.$gap;
user-select: none;
}
@use 'variables' as v;
@use 'layout';
body {
margin: 0;
font-family: sans-serif;
color: v.$text;
}
The scripts
The script is an ES module that imports a function from another module. The module has a second function that nobody uses; esbuild removes it from the bundle by tree shaking.
export function greet(name) {
return `Hello, ${name}!`;
}
export function unused() {
return 'not used';
}
import { greet } from './greet.js';
const title = document.querySelector('#title');
if (title) {
title.textContent = greet(title.textContent);
}
console.log('site ready');
The image plugin
The plugin tools/images.js is a Transform stream like the one in Gulp writing a plugin.
It recompresses a PNG file with the highest compression level and a palette, and a JPEG file with the quality of 80 and the mozjpeg encoder; other files, such as SVG,
are passed on unchanged. Because sharp is asynchronous, the transform method is async, and a failure is passed to the callback.
import { Transform } from 'node:stream';
import sharp from 'sharp';
export default function optimizeImages() {
return new Transform({
objectMode: true,
async transform(file, encoding, callback) {
if (!file.isBuffer()) {
return callback(null, file);
}
try {
const ext = file.extname.toLowerCase();
if (ext === '.png') {
file.contents = await sharp(file.contents).png({ compressionLevel: 9, palette: true }).toBuffer();
} else if (ext === '.jpg' || ext === '.jpeg') {
file.contents = await sharp(file.contents).jpeg({ quality: 80, mozjpeg: true }).toBuffer();
}
callback(null, file);
} catch (err) {
callback(err);
}
}
});
}
The gulpfile
The gulpfile has one function for each task, the helper tasks for the server and the composed tasks at the end. Its parts are explained in the following sections.
import { src, dest, series, parallel, watch } from 'gulp';
import * as dartSass from 'sass';
import gulpSass from 'gulp-sass';
import postcss from 'gulp-postcss';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import { build as esbuild } from 'esbuild';
import htmlmin from 'gulp-html-minifier-terser';
import browserSync from 'browser-sync';
import { deleteAsync } from 'del';
import optimizeImages from './tools/images.js';
const sass = gulpSass(dartSass);
const server = browserSync.create();
const isProd = process.env.NODE_ENV === 'production';
export function clean() {
return deleteAsync('dist');
}
export function styles() {
const plugins = [autoprefixer()];
if (isProd) {
plugins.push(cssnano());
}
return src('src/scss/main.scss', { sourcemaps: !isProd })
.pipe(sass().on('error', sass.logError))
.pipe(postcss(plugins))
.pipe(dest('dist/css', { sourcemaps: !isProd && '.' }))
.pipe(server.stream());
}
export function scripts() {
return esbuild({
entryPoints: ['src/js/main.js'],
outfile: 'dist/js/main.js',
bundle: true,
minify: isProd,
sourcemap: !isProd,
target: 'es2020',
logLevel: 'info'
});
}
export function images() {
let stream = src('src/img/**/*', { encoding: false });
if (isProd) {
stream = stream.pipe(optimizeImages());
}
return stream.pipe(dest('dist/img'));
}
export function html() {
let stream = src('src/*.html');
if (isProd) {
stream = stream.pipe(htmlmin({ collapseWhitespace: true, removeComments: true }));
}
return stream.pipe(dest('dist'));
}
function reload(done) {
server.reload();
done();
}
function serve(done) {
server.init({ server: 'dist', open: false, notify: false, ui: false, logLevel: 'silent' });
watch('src/scss/**/*.scss', styles);
watch('src/js/**/*.js', series(scripts, reload));
watch('src/img/**/*', series(images, reload));
watch('src/*.html', series(html, reload));
done();
}
export const assets = parallel(styles, scripts, images, html);
export const build = series(clean, assets);
export const dev = series(clean, assets, serve);
export default build;
The assets task runs the four build tasks in parallel, build adds the cleaning before it, and dev adds the server after it.
The default task is build.
Styles and scripts in the gulpfile
The styles task reads only the entry point, because the partials are loaded by Sass. In the production mode cssnano is added to the PostCSS
plugins. The sourcemaps options of src and dest are on in the development mode only; the value of the option of
dest is '.' (external files) or false. The sass.logError handler prints the errors, so that the watcher keeps running. At the end server.stream() injects
the changed CSS into the open browser without a reload.
export function styles() {
const plugins = [autoprefixer()];
if (isProd) {
plugins.push(cssnano());
}
return src('src/scss/main.scss', { sourcemaps: !isProd })
.pipe(sass().on('error', sass.logError))
.pipe(postcss(plugins))
.pipe(dest('dist/css', { sourcemaps: !isProd && '.' }))
.pipe(server.stream());
}
The scripts task calls esbuild directly, which is better than the plugin because the errors are reported, and the promise it
returns tells Gulp when the task is finished. The modules are bundled to one file, minified in the production mode and with a source map in the development mode.
export function scripts() {
return esbuild({
entryPoints: ['src/js/main.js'],
outfile: 'dist/js/main.js',
bundle: true,
minify: isProd,
sourcemap: !isProd,
target: 'es2020',
logLevel: 'info'
});
}
The images and html tasks add their transformation to the stream only in the production mode; in the development mode the files are just copied, which is faster. The images are
read with encoding: false, so that the binary files are not damaged, see Gulp 5.
Building in the development mode
The default mode is the development one. We run the build task and list the files. The CSS and JavaScript have source maps, and the image files are copies.
$ npx gulp build
[14:02:23] Using gulpfile ~/Documents/prog/js/gulp-site/gulpfile.mjs
[14:02:23] Starting 'build'...
[14:02:23] Starting 'clean'...
[14:02:23] Finished 'clean' after 6.05 ms
[14:02:23] Starting 'styles'...
[14:02:23] Starting 'scripts'...
[14:02:23] Starting 'images'...
[14:02:23] Starting 'html'...
[14:02:23] Finished 'scripts' after 18 ms
[14:02:23] Finished 'html' after 98 ms
[14:02:23] Finished 'styles' after 100 ms
[14:02:23] Finished 'images' after 100 ms
[14:02:23] Finished 'build' after 108 ms
dist/js/main.js 295b
dist/js/main.js.map 623b
⚡ Done in 3ms
$ find dist -type f -printf "%7s %p\n" | sort -k2
499 dist/about.html
523 dist/css/main.css
1476 dist/css/main.css.map
151 dist/img/icon.svg
8172 dist/img/logo.png
96702 dist/img/photo.jpg
571 dist/index.html
295 dist/js/main.js
623 dist/js/main.js.map
Building in the production mode
We set NODE_ENV to production for the same task. The source maps are gone, the CSS and JavaScript are minified,
the images are smaller, and the pages are collapsed to one line. The comment with the text site header was removed from the page.
$ NODE_ENV=production npx gulp build
[14:02:24] Using gulpfile ~/Documents/prog/js/gulp-site/gulpfile.mjs
[14:02:24] Starting 'build'...
[14:02:24] Starting 'clean'...
[14:02:24] Finished 'clean' after 9.17 ms
[14:02:24] Starting 'styles'...
[14:02:24] Starting 'scripts'...
[14:02:24] Starting 'images'...
[14:02:24] Starting 'html'...
[14:02:24] Finished 'scripts' after 21 ms
[14:02:25] Finished 'styles' after 132 ms
[14:02:25] Finished 'html' after 137 ms
[14:02:25] Finished 'images' after 172 ms
[14:02:25] Finished 'build' after 185 ms
dist/js/main.js 148b
⚡ Done in 2ms
$ find dist -type f -printf "%7s %p\n" | sort -k2
437 dist/about.html
382 dist/css/main.css
151 dist/img/icon.svg
1683 dist/img/logo.png
23852 dist/img/photo.jpg
481 dist/index.html
148 dist/js/main.js
The result
The minified files show what the plugins did. The CSS is one line, the declaration user-select got the -webkit- and -moz-
variants from Autoprefixer, and the values of the Sass variables are inlined. The script is a bundle that contains the used function only: the function unused was
removed by tree shaking.
$ cat dist/css/main.css
.site-header{display:flex;align-items:center;gap:1rem;padding:1rem;border-bottom:2px solid #2a6f97}.site-header nav a{margin-right:1rem;color:#2a6f97;text-decoration:none}.site-header nav a:hover{text-decoration:underline}main{max-width:40rem;margin:0 auto;padding:1rem;-webkit-user-select:none;-moz-user-select:none;user-select:none}body{margin:0;font-family:sans-serif;color:#222}
$ cat dist/js/main.js
(()=>{function e(o){return`Hello, ${o}!`}var t=document.querySelector("#title");t&&(t.textContent=e(t.textContent));console.log("site ready");})();
The npm scripts
Typing the environment variable is inconvenient, so we add two scripts to package.json: npm run dev for the development and npm run build for
the production. The NODE_ENV=production syntax works in Unix shells; on Windows a package such as cross-env is needed.
$ npm pkg set scripts.dev="gulp dev" scripts.build="NODE_ENV=production gulp build"
Then npm run build does the production build.
$ npm run build > gulp-site@1.0.0 build > NODE_ENV=production gulp build [14:02:25] Using gulpfile ~/Documents/prog/js/gulp-site/gulpfile.mjs [14:02:25] Starting 'build'... [14:02:25] Starting 'clean'... [14:02:25] Finished 'clean' after 8.85 ms [14:02:25] Starting 'styles'... [14:02:25] Starting 'scripts'... [14:02:25] Starting 'images'... [14:02:25] Starting 'html'... [14:02:25] Finished 'scripts' after 20 ms [14:02:26] Finished 'styles' after 132 ms [14:02:26] Finished 'html' after 138 ms [14:02:26] Finished 'images' after 169 ms [14:02:26] Finished 'build' after 180 ms dist/js/main.js 148b ⚡ Done in 2ms
The development server
The dev task builds the site, starts the Browsersync server on the port 3000 and sets watchers on the sources. The serve task finishes immediately, but the watchers and the server
keep the process alive, until we stop it with Ctrl+C. Each watcher runs the task of its files; the tasks for scripts, images and pages are followed by the
reload task, which reloads the browser, and the styles are injected. The ui: false option turns off the control panel of Browsersync, and logLevel: 'silent'
its messages.
function serve(done) {
server.init({ server: 'dist', open: false, notify: false, ui: false, logLevel: 'silent' });
watch('src/scss/**/*.scss', styles);
watch('src/js/**/*.js', series(scripts, reload));
watch('src/img/**/*', series(images, reload));
watch('src/*.html', series(html, reload));
done();
}
We start the task in one terminal and from another terminal change a colour in _variables.scss and restore it. The next two sections show the commands of the second terminal and the log of the first one.
Commands in the second terminal
The first command requests the page; Browsersync adds its client script to the HTML when the browser accepts it, so the count of lines with
browser-sync is 1. After the edit of the Sass file the served stylesheet contains the new colour.
$ curl -s -H 'Accept: text/html' localhost:3000/ | grep -c 'browser-sync' 1 $ sed -i 's/#2a6f97/#c0392b/' src/scss/_variables.scss $ sleep 2 $ curl -s localhost:3000/css/main.css | grep -o '#c0392b' | sort -u #c0392b $ sed -i 's/#c0392b/#2a6f97/' src/scss/_variables.scss $ sleep 1
The log of the development server
This is what npx gulp dev printed in the first terminal while the commands above ran. After the first build it started the server and then
ran only the styles task for each of the two changes of the Sass file; the other tasks did not run.
$ npx gulp dev [14:02:27] Using gulpfile ~/Documents/prog/js/gulp-site/gulpfile.mjs [14:02:27] Starting 'dev'... [14:02:27] Starting 'clean'... [14:02:27] Finished 'clean' after 15 ms [14:02:27] Starting 'styles'... [14:02:27] Starting 'scripts'... [14:02:27] Starting 'images'... [14:02:27] Starting 'html'... dist/js/main.js 295b dist/js/main.js.map 623b ⚡ Done in 2ms [14:02:27] Finished 'scripts' after 18 ms [14:02:27] Finished 'html' after 110 ms [14:02:27] Finished 'styles' after 111 ms [14:02:27] Finished 'images' after 112 ms [14:02:27] Starting 'serve'... [14:02:27] Finished 'serve' after 11 ms [14:02:27] Finished 'dev' after 141 ms [14:02:30] Starting 'styles'... [14:02:30] Finished 'styles' after 30 ms [14:02:32] Starting 'styles'... [14:02:32] Finished 'styles' after 25 ms
Errors in the development mode
A syntax error should not stop the server. In the next session we append a broken line to the script, then to the stylesheet, and restore both files. The esbuild error and the Sass error are printed, the corresponding task fails, but the watchers survive: after the repair the tasks run again, and the server still answers with the status 200. See also Gulp error handling.
$ echo 'const = ;' >> src/js/main.js
$ sleep 2
$ echo 'body {' >> src/scss/main.scss
$ sleep 2
$ cp /tmp/main.js.bak src/js/main.js
$ cp /tmp/main.scss.bak src/scss/main.scss
$ sleep 2
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:3000/
200
The log of the failed tasks
The log of the server in this session shows the two errors, each in its place, and the successful runs after the files were restored. The stack trace of esbuild and the details of the Sass error were shortened.
$ npx gulp dev
[14:02:35] Using gulpfile ~/Documents/prog/js/gulp-site/gulpfile.mjs
[14:02:35] Starting 'dev'...
[14:02:35] Starting 'clean'...
[14:02:35] Finished 'clean' after 8.95 ms
[14:02:35] Starting 'styles'...
[14:02:35] Starting 'scripts'...
[14:02:35] Starting 'images'...
[14:02:35] Starting 'html'...
dist/js/main.js 295b
dist/js/main.js.map 623b
⚡ Done in 3ms
[14:02:35] Finished 'scripts' after 17 ms
[14:02:35] Finished 'html' after 111 ms
[14:02:35] Finished 'styles' after 115 ms
[14:02:35] Finished 'images' after 117 ms
[14:02:35] Starting 'serve'...
[14:02:35] Finished 'serve' after 14 ms
[14:02:35] Finished 'dev' after 143 ms
[14:02:38] Starting 'scripts'...
✘ [ERROR] Expected identifier but found "="
src/js/main.js:10:6:
10 │ const = ;
╵ ^
1 error
[14:02:38] 'scripts' errored after 7.33 ms
[14:02:38] Error: Build failed with 1 error:
src/js/main.js:10:6: ERROR: Expected identifier but found "="
[14:02:40] Starting 'styles'...
Error in plugin "sass"
Message:
src/scss/main.scss
expected end of rule.
╷
9 │ body {
│ ^
╵
- 9:7 root stylesheet
Details:
...
[14:02:40] Finished 'styles' after 30 ms
[14:02:42] Starting 'scripts'...
dist/js/main.js 295b
dist/js/main.js.map 623b
⚡ Done in 3ms
[14:02:42] Starting 'styles'...
[14:02:42] Finished 'scripts' after 8.54 ms
[14:02:42] Starting 'reload'...
[14:02:42] Finished 'reload' after 1.17 ms
[14:02:42] Finished 'styles' after 25 ms
Source
Gulp quick start, sharp documentation, esbuild API, Browsersync with Gulp
In this article we have built a complete static site with Gulp 5: Sass, PostCSS, esbuild, images, HTML, cleaning and a Browsersync server, in a development
mode and a production mode selected with NODE_ENV. See also the Getting started with Gulp and Gulp vs. npm scripts and Vite tutorials.
Author
List all Gulp tutorials.