Gulp で SCSS のコンパイルから bourbon の導入までを試す - Gulp で作る Web フロントエンド開発環境 #1

wakamsha
68

そろそろ Gulp 始めたいと思います

gulp-jumbotron

これまでは Ruby on Rails によるフロントエンド開発がメインだったのですが、最近アサインされた新規開発案件が Scala & Play によるものであるのと、API 中心でサーバーサイドとフロントエンドがハッキリ分離するという構成のため、それならばということで一からフロントエンド開発環境を構築することにしました。もともと Grunt は多少嗜んでいたので今回もそれを使い続けても良かったのですが、何かと新しい情報は Gulp 関連が多いことから、僕もこの機会に Gulp 入門してみたいと思います。

前提条件

  • Mac OS X Yosemite
  • nodebrew インストール済み
  • node.js インストール済み ( v5.4 ~ )
  • npm インストール済み ( 3.3.12 ~ )

僕は Nodebrew を使っていますが、Node.js がインストールされていれば Homebrew でも公式サイトが配布しているインストーラからでも構いません。

サンプルコードはこちらからどうぞ。

Getting Started

黒い画面 (コマンドライン) 中心で進めていきます。

プロジェクト作成

はじめにプロジェクトディレクトリを適当な場所に作成します。

$ mkdir -p path/your/directory
$ cd path/your/directory

package.json を作成

プロジェクト内で使用するパッケージ / モジュールを管理するための package.jsonを作成します。

$ npm init

name: (getting_started)
version: (1.0.0)
description: Getting started Gulp.
entry point: (index.js) gruntfile.js
test command:
git repository:
keywords:
author:YOUR NAME
license: (ISC)
About to write to /Users/yamadanaoki/Documents/project/getting_started/package.json:

{
  "name": "getting-started",
  "version": "1.0.0",
  "description": "Getting started Gulp.",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "wakasmha",
  "license": "ISC"
}

後述する gulpfile は記述量の少ない CoffeeScript で書けるようにします。

Node.js v4.0 以降であれば ECMAScript2015 ( ES6 ) の記法で書くことが出来ます。

gulp インストール

$ npm install -g gulp

$ npm install gulp --save-dev

gulp -v # インストールしたバージョンの確認
[13:14:34] CLI version 3.8.11
[13:14:34] Local version 3.8.11
  1. -gを付けてグローバルインストールする
  2. 作成したディレクトリ内にも gulp をインストールする

インストールコマンドに --save-devというオプションを付けると、インストールされたパッケージ情報が package.jsonに追記されます。ちなみに install--save-devというコマンドは、それぞれ i-Dと省略することが出来ます。

$ npm i -D PACKAGE_NAME

この先何度も入力するコマンドなので、少しでも短いほうがいいですね。

coffee-script インストール

gulpfile を CoffeeScript で書けるように coffee-script をインストールします。

$ npm i -D coffee-script

簡単なタスクで動作確認

fromディレクトリ内の全てのファイルをtoディレクトリへ移動するというサンプルを試してみます。

gulp-gettingstarted/
  ├── from/
  │   ├── foo.txt
  │   └── bar.txt
  └── to/
gulp = require 'gulp'

gulp.task 'default', ->       # 1
  gulp.src './from/*'        # 2
    .pipe gulp.dest './to/'  # 3

Grunt と違って gulp はpipe()という関数をチェーンメソッドとして連結させていくことで、処理の流れを視覚的にわかりやすくしています。

  1. gulp に実行させたいタスクを定義。タスク名は defaultとする
  2. src() で入力対象を指定
  3. pipe()で次の処理を定義。gulp.dest()でファイルの移動先を指定

実行してみます。

$ gulp

[13:42:07] Requiring external module coffee-script/register
[13:42:07] Using gulpfile ~/Documents/project/getting_started/gulpfile.coffee
[13:42:07] Starting 'default'...
[13:42:07] Finished 'default' after 13 ms

正常に動作しました。

SCSS (Sass) をコンパイル

sass-logo

Node パッケージをインストールします。

$ npm i -D gulp-sass

scss 用ディレクトリを作成します。

mkdir -p src/scss

適当にSCSSファイルを作成します。

$theme-priary:       #f00;
$box-shadow-default: 0 1px 2px rgba(0,0,0,.1);
body {
  background: #fafafa;
}
.text-primary {
  color: $theme-priary;
  font-weight: bold;
}
$card-bg-default: #fff;
.card {
  background-color: $card-bg-default;
  display: block;
  margin-bottom: 10px;
  position: relative;
  box-shadow: $box-shadow-default;
  padding: 15px;
}
@import "variables";
@import "scaffolding";
@import "modules/card";

タスクを定義します。

gulp = require 'gulp'
sass = require 'gulp-sass'

gulp.task 'scss', ->
  gulp.src './src/scss/**/*.scss'
    .pipe sass()
    .pipe gulp.dest('./dest/assets/css')

実行してみます。

$ gulp scss

[14:22:00] Requiring external module coffee-script/register
[14:22:00] Using gulpfile ~/Documents/project/getting_started/gulpfile.coffee
[14:22:00] Starting 'scss'...
[14:22:00] Finished 'scss' after 20 ms

生成されたCSSファイルがこちら。

body {
  background: #fafafa; }

.text-primary {
  color: #f00;
  font-weight: bold; }

.card {
  background-color: #fff;
  display: block;
  margin-bottom: 10px;
  position: relative;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  padding: 15px; }

うまくいきましたね。

SourceMap を導入してみる

Web ブラウザにはコンパイルされた CSS が読み込まれるわけですが、複数の SCSS ファイルが結合されたり mixin 等が展開された状態なので、そのままではデバッグが非常に困難です。SourceMap を導入すれば、Chrome の dev ツールなどで CSS を見た時に、そのクラスがコンパイル前の SCSS のどの部分にあたるのかという情報が分かるようになります。

scss_sourcemap

パッケージをインストールします。

$ npm i -D gulp-sourcemaps

タスクを定義します。

gulp = require 'gulp'
sass = require 'gulp-sass'
sourcemaps = require 'gulp-sourcemaps'

gulp.task 'scss', ->
  gulp.src './src/scss/**/*.scss'
    .pipe sourcemaps.init()
    .pipe sass()
    .pipe sourcemaps.write()
    .pipe gulp.dest('./dest/assets/css')

実行してみます。

$ gulp scss

ブラウザで確認してみて、先ほどの画像の様になっていれば成功です。

bourbon を導入してみる

bourbon-logo

SCSS フレームワークである bourbon を導入します。少し前までは Compass を使っていましたが、やや動作が重いのとベンダープレフィクスも以前ほど意識しなくてよくなってきたことから、より軽量な Bourbon を使うことにします。

パッケージをインストールします。

$ npm i -D node-bourbon

適当に SCSS を追記します。

a {
  color: blue;
  background: transparent;
  @include transition(.1s);
  &:hover,
  &:focus {
    color: white;
    background: blue;
  }
}

タスクを定義します。

gulp = require 'gulp'
sass = require 'gulp-sass'
sourcemaps = require 'gulp-sourcemaps'
bourbon = require 'node-bourbon'

bourbon.with './src/scss/application'

gulp.task 'scss', ->
  gulp.src './src/scss/**/*.scss'
    .pipe sourcemaps.init()
    .pipe sass
      includePaths: bourbon.includePaths
    .pipe sourcemaps.write()
    .pipe gulp.dest('./dest/assets/css')

bourbon.with()には bourbon のmixin を呼び出している scss ファイルを指定します。配列形式で複数指定できますが、今回指定した application.scss は全てのパーシャルをインポートしているので、これ一つだけ指定しておけば十分です。これをsass()関数の includePathsというオプションに指定します。

実行してみます。

$ gulp scss

[19:57:22] Requiring external module coffee-script/register
[19:57:22] Using gulpfile ~/Documents/project/getting_started/gulpfile.coffee
[19:57:22] Starting 'scss'...
[19:57:22] Finished 'scss' after 59 ms

生成された CSS ファイルがこちら。

body {
  background: #fafafa; }

.text-primary {
  color: #f00;
  font-weight: bold; }

a {
  color: blue;
  background: transparent;
  -webkit-transition: .1s;
  -moz-transition: .1s;
  transition: .1s; }
  a:hover, a:focus {
    color: white;
    background: blue; }

.card {
  background-color: #fff;
  display: block;
  margin-bottom: 10px;
  position: relative;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  padding: 15px; }

これで Bourbon が使えるようになりました。

締め

とりあえず Gulp の基本的なお作法を体験してみました。あまりに基本的過ぎてこれだけでは Grunt からわざわざ乗り換える程の動機にはなりませんが、それはもう少し使い続けていくことで判断すれば良いと思います。

今回触れた gulp-sass はかなり機能が削られているようで、コンパイル時にミニファイ化することも出来ませんが、それは他の Node パッケージに任せれば良いことなので、今回はこれで良しとします。