Streamlining file management with Gulp


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
gulpを使うにはnode.jsのインストールが必要です。
下記サイトから実行ファイルがダウンロードできます。
アプリケーションをインストールする感覚で行えます。dmgを開き、手順に従ってインストールしてください。
node.jsをインストールした後、npmコマンドが実行できることを確認します。
npm -v
5.3.0
バージョンが出てくればインストールに問題ありません。
またnode.jsについては、
「TIPS vol.63 node.jsアプリをLinuxサーバーで公開してみよう」 でも紹介しています。
そちらもぜひご覧ください。
Global Installation
gulpはグローバルインストール、ローカルインストール二通りが必要です。まずグローバルインストールを実行します。
sudo npm install gulp -g
プロジェクトフォルダ内にpackage.jsonが生成されているのを確認してください。
プロジェクトフォルダ内でgulpのローカルインストールを行います。
npm install --save-dev gulp
インストールが完了したらgulpが実行できるか確認しましょう。
Running Gulp
gulpを実行するためにはgulpfile.jsというファイルが必要になります。
プロジェクトフォルダに作成しましょう。
Project Setup with Gulp
設定を進めていきます。
基本的には下記サイトを参考にさせていただいています。これを軸に、プロジェクトの特性に合わせ調整を加えていきます。
- gulp-ejsでHTMLの共通部分を分割化
- gulp-sassでscssをコンパイル
- gulp-plumber、gulp-notifyでエラー強制停止の防止を行う。リアルタイム通知
- gulp-autoprefixerでベンダープレフィックスを自動で付与
- gulp-webserverでローカルサーバーを立ち上げ
※gulp-webserver
gulp-webserverで開発用Webサーバーを立ち上げる
※gulp-plumber、gulp-notify
これからはじめるGulp(6):gulp-plumberとgulp-notifyを使ったデスクトップ通知
追加で下記にも対応します。
・imagemin-pngquantとgulp-imageminで画像圧縮
・gulp-html-validatorでHTMLバリデーションする
参考サイトのサンプルとあわせて下記のようなコードになります。
//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']);
パッケージをインストールします。package.jsonを編集したら下記コマンドを実行します。
npm install
必要なパッケージが追加され、gulpfile.jsに書いた内容が実行できるようになります。
実際にどんなことができるか見ていきましょう。
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
index.ejs(コアファイル)を作成します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>構築のテスト</title>
</head>
<body>
<% include _partial/header %>
<main>
<p>テキストエリア</p>
</main>
<% include _partial/footer %>
</body>
</html>
Externalizing the Header and Footer
<% include _partial/header %>
<% include _partial/footer %>
これらはHTMLでは見覚えのない書き方です。これはヘッダーとフッターのテンプレートを読み込む記述になります。
実際に_partialフォルダを作成し、header.ejsとfooter.ejsを作成します。
<!- header.ejs ->
<header>
外部化したヘッダーパーツ
</header>
<!- footer.ejs ->
<footer>
外部化したフッターパーツ
</footer>
これでHTMLとなるファイルの準備はOKです。
Compiling SCSS
scssをコンパイルし、cssファイルにすることができます。
srcににscssのフォルダを用意し、scssのファイルを作成します。
下記のようにscssの形式で書いてみます。
/*common.scss*/
body{margin: 0;
p{margin: 0;}
}
Image Compression
gulpfile.jsには画像を圧縮する設定を行っています。
srcにimagesフォルダを作成し、画像を用意しておきます。
HTML Validation
生成されたHTMLのバリデーションを行った結果をファイルに書き出す設定をしています。
結果はvalidoutフォルダが自動生成され、その中に結果が表示されます。
Running Gulp
上記の準備ができた段階でgulpを実行してみましょう。
gulp
distフォルダが自動生成され、成果物ファイルが構築されます。
<!- index.html ->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>構築のテスト</title>
</head>
<body>
<header>
外部化したヘッダーパーツ
</header>
<main>
<p>テキストエリア</p>
</main>
<footer>
外部化したフッターパーツ
</footer>
</body>
</html>
/*common.css*/
body {margin: 0; }
body p {margin: 0; }
画像も生成されていることを確認します。
元の画像とファイルサイズを比較してみてください。
HTMLのプレビューを下記URLから確認することができます。NPM公式サイト
gulp実行中は上記URLからプレビュー閲覧すると、HTML、CSSを変更したときにブラウザがリフレッシュされ、リアルタイムで更新確認できます。
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
RECENT POSTS
Vol.198
From parent–child bonds to community: The future of education that nurtures diversity and designs relationships
Vol.197
Exploring the future of environmental design integrating vision, diversity, and a future-oriented perspective
Vol.196
Vision-making for diverse and future-oriented education: Interpreting the future of learning through environmental design
Vol.195
“One Health” and Japan — Toward an Era of Integrating Humans, Animals, and the Environment
Vol.194
The benefits and challenges of digital education in the AI era, and the future of learning

Vol.193
Vision-Making in the age of AI — How artificial intelligence is transforming the meaning of work and the nature of organizations









