TECH

Vol.78

author

Y.M

Streamlining file management with Gulp

#WEB#HTML#CSS#マクロ開発#programming#Node.js
Last update : 2026.3.31
Posted : 2017.9.15
When building a website using HTML, it’s not uncommon to find yourself in a situation where you need to update all related HTML files to synchronize common components. While implementing a CMS or framework might be overkill in some cases, there are times when you want to achieve more flexible source control and eliminate repetitive manual tasks. In such situations, Gulp offers a practical and efficient solution.
stuffstuff

What is Gulp?

Gulp is a build tool based on Node.js.
It helps eliminate various manual tasks by automating processes such as compiling Sass and CoffeeScript.
Because its build configurations can be easily customized, it can flexibly adapt to a wide range of project requirements.
There is also a wealth of reference material available—including the official npm website and articles published by third-party developers—making it relatively easy to find the information needed for setup.
While writing configurations in JavaScript may initially seem complex, as long as your objectives are clearly defined, suitable examples can be found, allowing for quick implementation.
In this article, we will gather insights from various web resources and tailor them to fit BOEL’s development workflow, introducing some customizations along the way.

Installing Gulp

This guide will be based on a macOS environment.
macOS Sierra 10.12.6

Installing Node.js

To use Gulp, you first need to install Node.js.
You can download the installer from the following website.

Node.js

The installation process is similar to installing a standard application. Open the .dmg file and follow the on-screen instructions.
After installing Node.js, make sure that the npm command is available.

npm -v
5.3.0

If the version number is displayed, the installation has been completed successfully.

For more information about Node.js, please also refer to the following article:

“TIPS vol.63: Publishing a Node.js Application on a Linux Server”
We encourage you to take a look.

Global Installation

Gulp requires both global and local installation. First, perform the global installation.

sudo npm install gulp -g

After installation, confirm that a package.json file has been generated within your project folder.
Next, proceed with the local installation of Gulp within the project directory.

npm install --save-dev gulp

Once the installation is complete, verify that Gulp can be executed properly.

A Quick Introduction to Gulp.js (for Mac)
About Gulp and npm

Running Gulp

Next, we will proceed with the configuration.
The setup below is primarily based on the following reference, with adjustments made to suit the specific requirements of the project.

Project Setup with Gulp

Next, we will proceed with the configuration.
The setup below is primarily based on the following reference, with adjustments made to suit the specific requirements of the project.

EJS Basics – Improving Site Production Efficiency with EJS

  • Use gulp-ejs to modularize common HTML components
  • Compile SCSS using gulp-sass
  • Prevent task interruption on errors and enable real-time notifications with gulp-plumber and gulp-notify
  • Automatically add vendor prefixes with gulp-autoprefixer
  • Launch a local development server using gulp-webserver

 

※gulp-webserver
Launching a Development Web Server with gulp-webserver

※gulp-plumber, gulp-notify
Getting Started with Gulp (6): Desktop Notifications with gulp-plumber and gulp-notify

In addition, we will also support the following:
・Image compression using imagemin-pngquant and gulp-imagemin
・HTML validation using gulp-html-validator

Combining the reference sample with these additions, the configuration will look as follows.

//package.json
{
  "name": "ejs-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^3.1.1",
    "gulp-ejs": "^2.2.1",
    "gulp-html-validator": "^0.0.5",
    "gulp-imagemin": "^3.3.0",
    "gulp-notify": "^2.2.0",
    "gulp-plumber": "^1.1.0",
    "gulp-sass": "^3.0.0",
    "gulp-webserver": "^0.9.1",
    "imagemin-pngquant": "^5.0.1"
  }
}
//gulpfile.js
const gulp = require('gulp');
const ejs = require('gulp-ejs');
const sass = require('gulp-sass');
const plumber = require('gulp-plumber');
const notify = require('gulp-notify');
const autoprefixer = require('gulp-autoprefixer');
const webserver = require('gulp-webserver');
const imagemin = require('gulp-imagemin');
const pngquant = require('imagemin-pngquant');
const htmlValidation = require('gulp-html-validator');


gulp.task('ejs',()=>{
  return gulp.src("./src/ejs/*.ejs")
    .pipe(plumber({errorHandler: notify.onError("Error: <%= error.message %>")}))
    .pipe(ejs('', {"ext": ".html"}))
    .pipe(gulp.dest("./dist"));
});

// sass 
gulp.task('sass',()=>{
  return gulp.src("./src/scss/*.scss")
    .pipe(plumber({errorHandler: notify.onError("Error: <%= error.message %>")}))
    .pipe(sass())
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gulp.dest("./dist/css"));
});

// localhost
gulp.task('webserver', ()=>{
    gulp.src("./dist")
      .pipe(webserver({
        host: 'localhost',
        port: 8000,
        livereload: true
      }));
});

const imagePath = {
    src: './src/images/',
    dist: './dist/images/'
  };

  gulp.task('optimizeImage', ()=> {
    return gulp.src(imagePath.src + '**/*').pipe(imagemin({
      use: [
        pngquant({
          quality: 60 - 80,
          speed: 1
        })
      ]
    })).pipe(gulp.dest(imagePath.dist));
  });

gulp.task('valid', () =>{
return gulp.src("./dist/*.html")
  .pipe(plumber({errorHandler: notify.onError("Error: <%= error.message %>")}))
    .pipe(htmlValidation())
    .pipe(gulp.dest('./validout'));
});

gulp.task('watch', ()=>{
  gulp.watch('./src/scss/**/*.scss', ['sass']);
  gulp.watch('./src/ejs/**/*.ejs', ['ejs']);
});

gulp.task('default',['watch','webserver','optimizeImage','valid']);

Install the required packages. After editing package.json, run the following command.

npm install

Once the necessary packages have been added, the tasks defined in gulpfile.js will be ready to run.
Let us now take a look at what can be achieved in practice.

Templating HTML with EJS as the Core

With EJS, you can template and modularize your HTML.
Create a src folder and begin building reusable components.

Create an EJS Folder

Create index.ejs as the core file.

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Build Test</title>
</head>
<body>
<% include _partial/header %>
<main>
  <p>Text Area</p>
</main>
<% include _partial/footer %>
</body>
</html>

Externalizing the Header and Footer

<% include _partial/header %>
<% include _partial/footer %>
These are not standard HTML syntax. They are EJS directives used to include header and footer templates.
Create a _partial folder, and within it, create header.ejs and footer.ejs.

<!- header.ejs ->
<header>
    Externalized header component
</header>
<!- footer.ejs ->
<footer>
    Externalized footer component
</footer>

With this, the HTML structure is ready.

Compiling SCSS

You can compile SCSS into CSS files.
Prepare an scss folder within the src directory and create your SCSS files.
For example, you can write SCSS as shown below.

/*common.scss*/
body{margin: 0;
p{margin: 0;}
}

Image Compression

The gulpfile.js includes settings for image compression.
Create an images folder within src and place your image files there.

HTML Validation

The configuration also outputs the results of HTML validation for the generated files.
A validout folder will be automatically created, where the validation results will be displayed.

Running Gulp

Once the above preparations are complete, let’s run Gulp.

gulp

A dist folder will be automatically generated, and the output files will be built.

<!- index.html ->
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Build Test</title>
</head>
<body>
<header>
  Externalized header component
</header>

<main>
  <p>Text Area</p>
</main>
<footer>
  Externalized footer component
</footer>

</body>
</html>
/*common.css*/
body {margin: 0; }
body p {margin: 0; }

Also confirm that the images have been generated.
Try comparing the file sizes with the original images.

You can preview the HTML from the following URL (provided via the local server).

While Gulp is running, accessing the above URL allows you to preview changes in real time—when HTML or CSS is updated, the browser will automatically refresh.

Conclusion

In this article, we have outlined the basic usage of Gulp from a practical perspective.
While features such as modularizing HTML, automatically compiling SCSS, compressing images, and enabling real-time previews may seem like small improvements individually, they are processes that are repeated many times during production.

Even small efficiencies, when accumulated, can lead to significant savings in both time and effort.
Additionally, the configurations introduced here represent only a portion of what Gulp can achieve, and there are many more ways to customize it.

Going forward, we aim to further enhance usability by incorporating JavaScript files into the workflow and continuing to refine the setup according to project needs.

Source: HTML Validation

Source: Image Compression

PREV
Vol.77Design tips that evoke autumn
NEXT
Vol.7910 microinteractions that enhanc…

MORE FOR YOU