Gulpに挑戦
ずっとフロントエンドのタスクランナーにはGruntを使っていましたが、Gulpがどんなものか触ってみたくなったので、勉強のために導入してみました。
なお、私の環境は
- Windows 7 Ultimate 64bit
です。プロジェクトディレクトリはgit初期化済みで、リモートリポジトリもadd済みです。
インストール
まずNode.jsを最新版にします。Windows版はインストーラで一発です。
> node -v v0.12.2 > npm -v 2.7.4
gulpをグローバルインストールします。
> npm install gulp -g > gulp -v > [11:10:14] CLI version 3.8.11
初期化など
プロジェクトディレクトリに移動してpackage.jsonファイルを作ります。
> npm init
gulpをローカルインストール。
> npm i -D gulp
gulpfileをCoffeeScriptで書きたいので、coffee-scriptをローカルインストールします。
> npm i -D coffee-script
.gitignore
ファイルにnode_modules/を書いておきます。
node_modules/
ここまでをgit pushしておきます。
> git status > git add . > git commit -m "install gulp" > git push origin master
各種モジュールのインストール
おそらく次のモジュールを使うことになるのであらかじめインストールしておきます:
- gulp-sass
- gulp-imagemin
- gulp-coffee
- gulp-concat
- gulp-uglify
- gulp-plumber
- gulp-webserver
> npm i -D gulp-sass gulp-imagemin gulp-coffee gulp-concat gulp-uglify gulp-plumber gulp-webserver
gulpfile.coffeeのテスト
プラグインをいろいろ入れておきながらなんですが、gulpfileを書くのは初めてなので、テスト的なものを書いておきます。
gulp = require 'gulp' gulp.task 'hello', -> console.log 'hello world!' gulp.task 'default', ['hello']
結果
> gulp [11:48:47] Requiring external module coffee-script/register [11:48:47] Using gulpfile ~\dev\mysite\gulpfile.coffee [11:48:47] Starting 'hello'... hello world! [11:48:47] Finished 'hello' after 177 μs [11:48:47] Starting 'default'... [11:48:47] Finished 'default' after 14 μs
うまくいきました。
タスクを書いていく
やることは、
- ./src/imageにある画像を軽量化して./dist/imageに配置
- ./src/coffeeにあるcoffeeファイルをコンパイル、結合、圧縮して./dist/jsに配置
- ./src/scssにあるscssファイルをコンパイルして./dist/cssに配置
- scss, coffee, htmlに変更があったらリロード
- scssとcoffeeのコンパイルにエラーがあっても止めない
gulp-imagemin
imagemin = require 'gulp-imagemin' gulp.task 'img', -> gulp.src ['./src/image/*.jpg', './src/image/*.png'] .pipe imagemin() .pipe gulp.dest './dist/image' gulp.task 'default', ['img']
gulp-plumber, gulp-coffee, gulp-concat, gulp-uglify
plumber = require 'gulp-plumber' coffee = require 'gulp-coffee' concat = require 'gulp-concat' uglify = require 'gulp-uglify' gulp.task 'js', -> gulp.src './src/coffee/*.coffee' .pipe plumber() .pipe coffee() .pipe concat 'all.min.js' .pipe uglify() .pipe gulp.dest './dist/js' gulp.task 'default', ['img', 'js']
gulp-sass
sass = require 'gulp-sass' gulp.task 'css', -> gulp.src './src/scss/*.scss' .pipe plumber() .pipe sass() .pipe gulp.dest './dist/css' gulp.task 'default', ['img', 'js', 'css']
watchの記述
gulp.task 'watch', -> gulp.watch './src/coffee/*.coffee', ['js'] gulp.watch './src/scss/*.scss', ['css'] gulp.watch './dist/*.html', ['watch'] gulp.task 'default', ['img', 'js', 'css', 'watch']
webserverの記述
webserver = require 'gulp-webserver' gulp.task 'webserver', -> gulp.src './dist' .pipe webserver{ host: 'localhost' livereload: true } gulp.task 'default', ['img', 'js', 'css', 'watch', 'webserver']
http://localhost:8000にアクセスできるようになりました。