ぺーぺーSEのブログ

備忘録・メモ用サイト。

Sass、Compass入門

SassとCSS界のjQueryことCompassを触ってみた。
下記を見たことを前提に書く。

blog.pepese.com
※npmとかGrunt使うよ!

また、CSSについては下記を参照。
blog.pepese.com

SassはCSSを簡単に書けるメタ言語。コンパイルしてCSSを出力する。
CompassはSassのフレームワーク。Sassで使える便利セットが詰まっている。
またここでは「.sass」ではなく、「.scss」を使う。
※「.scss」の方がメジャーっぽい。

インストール

RubyをインストールしておいてGemでSassとCompassをインストール。

> gem install sass
> gem install compass
> sass -v
Sass 3.4.14 (Selective Steve)
> compass -v
Compass 1.0.3 (Polaris)
Copyright (c) 2008-2015 Chris Eppstein
Released under the MIT License.
Compass is charityware.
Please make a tax deductable donation for a worthy cause: http://umdf.org/compass

GruntのプロジェクトでSass、Compass使うときはプラグインをインストール。

> npm install --save-dev grunt-contrib-sass grunt-contrib-compass


Sass文法

SCSS形式の文法ね。

■セレクタの入れ子

こんなふうに

要素1 要素2 {
  プロパティ : 値;
}
要素1 要素3 {
  プロパティ : 値;
}

書くのめんどいよね。
下記のように書ける。

要素1 {
  要素2 {
    プロパティ : 値;
  }
  要素3 {
    プロパティ : 値;
  }
}


もちろんコンパイルしたら上のcssが出る。

■プロパティの入れ子
p {
  background-color: blue;
  background-image: url("hoge.jpg");
  background-repeat: repeat-y;
}

書くのめんどいよね。
下記のように書ける。

p{
  background: {
    color: blue;
    image: url('hoge.jpg');
    repeat: repeat-y;
  }
}



■「&」

入れ子にしてコンパイルした後スペース空くのが嫌な時は「&」をつける。
こう書くと、

.row-offcanvas-right {
  right: 0;
  &.active {
    right: 50%;
  }
}


こうなる。

.row-offcanvas-right {
  right: 0;
}
.row-offcanvas-right.active {
  right: 50%;
}


■継承

@extend」でセレクタを指定して継承することができる。

.p1{
    background-color: gray;
    color: red;
}
.p2{
    @extend .p1; /* .p2に対して.p1のスタイルをそのまま適用 */
    border: 1px solid white; /* .p2にだけ適用したいスタイルも書ける */
}


↓↓↓

.p1, .p2 {
  background-color: gray;
  color: red;
}
.p2 {
  border: 1px solid white;
}


■変数

$変数名: 値;」の形式で定義・値代入し、「$変数名」で使用することができる。

$original-red:#a82f34;
$a-width:400px;
a{
  color: $original-red;
  width: $a-width + 300px; /* 四則演算も可能 */
}



■MixinとInclude

@mixin」でスタイルの塊を定義して「@include」で使用することができる。
Mixinは下記のように定義できる。

@mixin Mixin_Name {
  好きなスタイル
}
@mixin Mixin_Name(引数1, 引数2, …) {
  引数を使用した好きなスタイル
}
@mixin Mixin_Name(引数1:デフォルト値,引数2:デフォルト値…) {
  引数を使用した好きなスタイル
}


MixinはIncludeで下記のように使用できる。

@include Mixin_Name;
@include Mixin_Name(引数1, 引数2, …);
@include Mixin_Name(引数1: 値, 引数2: 値, …);



■Import

@import」を使用すると指定したcss/sassファイルの中身をそのまま適用できる。

@import "hoge.css";
@import "foge.scss";



■Partial

ImportしたSCSSファイルはコンパイルするけど、ImportされたSCSSファイルはコンパイルしたくない。(だっていらないもの)
このコンパイルしたくない、ImportだけしたいSCSSファイルのことをPartialファイルという。
ファイル名の先頭にアンスコ_」をつけるだけでPartialファイルになる。
「_hoge.scss」とか。

Compassの使い方

■設定

Compassの設定ファイルconfig.rbをプロジェクトルートに作成する。

css_dir = "dest/assets/css"
sass_dir = "src/scss"
images_dir = "src/img"
javascripts_dir = "dest/assets/js"
relative_assets = true

Compassの初期化。

> compass init
directory dest/assets/css/
   create src/scss/screen.scss
   create src/scss/print.scss
   create src/scss/ie.scss
    write dest/assets/css/ie.css
    write dest/assets/css/offcanvas.css
    write dest/assets/css/print.css
    write dest/assets/css/screen.css

*********************************************************************
Congratulations! Your compass project has been created.

You may now add and edit sass stylesheets in the src/scss subdirectory of your project.

Sass files beginning with an underscore are called partials and won't be
compiled to CSS, but they can be imported into other sass stylesheets.

You can configure your project by editing the config.rb configuration file.

You must compile your sass stylesheets into CSS when they change.
This can be done in one of the following ways:
  1. To compile on demand:
     compass compile [path/to/project]
  2. To monitor your project for changes and automatically recompile:
     compass watch [path/to/project]

More Resources:
  * Website: http://compass-style.org/
  * Sass: http://sass-lang.com
  * Community: http://groups.google.com/group/compass-users/


To import your new stylesheets add the following lines of HTML (or equivalent) to your webpage:
<head>
  <link href="/dest/assets/css/screen.css" media="screen, projection" rel="stylesheet" type="text/css" />
  <link href="/dest/assets/css/print.css" media="print" rel="stylesheet" type="text/css" />
  <!--[if IE]>
      <link href="/dest/assets/css/ie.css" media="screen, projection" rel="stylesheet" type="text/css" />
  <![endif]-->
</head>

Gruntを使用している場合はGruntfile.jsを修正。

'use strict';

module.exports = function(grunt) {

  // initConfigの中で各タスクを設定
  grunt.initConfig({
    // package.jsonに設定されている内容を取得
    // バージョンや名称などの情報を外部ファイルで共通化できる
    pkg: grunt.file.readJSON("package.json"),
    
    // compassタスク(grunt-contrib-compass)の設定
    compass: {
      compile: {
        options: {
          config: 'config.rb'
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-compass');
}:

grunt compass」すればコンパイルされる。

■使い方

Compassのモジュールを使うときはSCSSファイルの先頭等で

@import "compass/css3";


を記載する。
これでCompassで様々用意されているMixinを使用できる。
Mixinの詳細は下記を参照。
http://compass-style.org/reference/compass/css3/

■例

@import "compass/css3";
.row-offcanvas {
  position: relative;
  @include transition-property(all);
  @include transition-duration(.25s);
  @include transition-timing-function(ease-out);
}

↓↓↓

.row-offcanvas {
  position: relative;
  -moz-transition-property: all;
  -o-transition-property: all;
  -webkit-transition-property: all;
  transition-property: all;
  -moz-transition-duration: 0.25s;
  -o-transition-duration: 0.25s;
  -webkit-transition-duration: 0.25s;
  transition-duration: 0.25s;
  -moz-transition-timing-function: ease-out;
  -o-transition-timing-function: ease-out;
  -webkit-transition-timing-function: ease-out;
  transition-timing-function: ease-out;
}

ベンダプレフィックス全部ついてる。。。

Yeoman入門

Yeoman触ってみた。
下記の記事を読んでインストールやプロキシ設定とかしてる前提で書く。

blog.pepese.com

blog.pepese.com

Yeoman

クライアントサイドの技術(Haml、Slim、Jade、Sass、LESS、Stylus、Coffeescript、TypeScript等)は増加の一途をたどっていて多種多様となっている。
HTML/CSSプリプロセッサやAltJS等の拡張言語はコンパイルするし、css/jsファイルはインスペクションしたり圧縮したりする。
Yeomanはアプリの雛形生成、コンパイル、テスト、インスペクション圧縮等のワークフローを提供してくる。
YeomanはYoGrunt(タスクランナー)、Bower(パッケージマネージャ)で構成されている。
ここではYoyeoman-generatorともいう)について書く。

インストール
> npm install -g yo


使い方

Yoはジェネレータ(yeoman-generator)という仕組みを使用して、アプリの雛形を生成する。
雛形は以下のように検索する。

> npm search yeoman-generator
〜省略〜
generator-webapp                        Scaffold out a front-end web app                             =sindresorhus…       2014-10-07 0.5.1       yeoman-generator web app front-end h5bp modernizr jquery grunt    
〜省略〜

2000個強出てきた。どれ使っていいかわからん。
とりあえずオーソドックスそうな上記の「generator-webapp」を使用する。
雛形を作成するコマンドは以下。(プロジェクトディレクトリ作成コマンドも含む)

> mkdir yoSample
> cd yoSample
> yo webapp

     _-----_
    |       |
    |--(o)--|   .--------------------------.
   `---------´  |    Welcome to Yeoman,    |
    ( _´U`_ )   |   ladies and gentlemen!  |
    /___A___\   '__________________________'
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

Out of the box I include HTML5 Boilerplate, jQuery, and a Gruntfile.js to build your app.
? What more would you like? Bootstrap
   create Gruntfile.js
   create package.json
   create .gitignore
   create .gitattributes
   create bower.json
   create .jshintrc
   create .editorconfig
   create app\favicon.ico
   create app\404.html
   create app\robots.txt
   create app\.htaccess
   create app\styles\main.css
   create app\index.html
   create app\scripts\main.js


I'm all done. Running bower install & npm install for you to install the required dependencies. If this fails,
 try running the command yourself.


npm WARN package.json yosample@0.0.0 No description
npm WARN package.json yosample@0.0.0 No repository field.
npm WARN package.json yosample@0.0.0 No README data
bower cached        https://github.com/twbs/bootstrap.git#3.0.3
bower validate      3.0.3 against https://github.com/twbs/bootstrap.git#~3.0.3
bower cached        https://github.com/jquery/jquery.git#1.11.2
bower validate      1.11.2 against https://github.com/jquery/jquery.git#~1.11.0
bower install       jquery#1.11.2
bower install       bootstrap#3.0.3
\
jquery#1.11.2 bower_components\jquery

bootstrap#3.0.3 bower_components\bootstrap
└── jquery#1.11.2
\


> phantomjs@1.9.15 install h:\workspace\yoSample\node_modules\grunt-mocha\node_modules\grunt-lib-phantomjs\nod
e_modules\phantomjs
> node install.js

Downloading https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.8-windows.zip
Saving to [UserHome]\AppData\Local\Temp\phantomjs\phantomjs-1.9.8-windows.zip
Using proxy http://xxxx:******@proxy.example.com:8080/
Receiving...
  [=======================================-] 97% 0.0s
Received 7292K total.
Extracting zip contents
Removing h:\workspace\yoSample\node_modules\grunt-mocha\node_modules\grunt-lib-phantomjs\node_modules\phantomj
s\lib\phantom
Copying extracted folder [UserHome]\AppData\Local\Temp\phantomjs\phantomjs-1.9.8-windows.zip-extract-142
5017693714\phantomjs-1.9.8-windows -> h:\workspace\yoSample\node_modules\grunt-mocha\node_modules\grunt-lib-ph
antomjs\node_modules\phantomjs\lib\phantom
Writing location.js file
Done. Phantomjs binary available at h:\workspace\yoSample\node_modules\grunt-mocha\node_modules\grunt-lib-phan
tomjs\node_modules\phantomjs\lib\phantom\phantomjs.exe

> jpegtran-bin@0.2.8 postinstall h:\workspace\yoSample\node_modules\grunt-contrib-imagemin\node_modules\image-
min\node_modules\jpegtran-bin
> node index.js

<  pre-build test failed, compiling from source...
<  pre-build test failed, compiling from source...
× 401
√ jpegtran built successfully!
× 401
√ jpegtran built successfully!

> optipng-bin@0.3.11 postinstall h:\workspace\yoSample\node_modules\grunt-contrib-imagemin\node_modules\image-
min\node_modules\optipng-bin
> node index.js

<  pre-build test failed, compiling from source...
× 401
√ optipng built successfully!

> gifsicle@0.1.7 postinstall h:\workspace\yoSample\node_modules\grunt-contrib-imagemin\node_modules\image-min\
node_modules\gifsicle
> node index.js

<  pre-build test failed, compiling from source...
× 401
√ gifsicle built successfully!

> pngquant-bin@0.1.7 postinstall h:\workspace\yoSample\node_modules\grunt-contrib-imagemin\node_modules\image-
min\node_modules\pngquant-bin
> node index.js

' connect ETIMEDOUT
grunt-contrib-copy@0.5.0 node_modules\grunt-contrib-copy

grunt-rev@0.1.0 node_modules\grunt-rev

grunt-contrib-concat@0.3.0 node_modules\grunt-contrib-concat

grunt-contrib-htmlmin@0.2.0 node_modules\grunt-contrib-htmlmin
├── each-async@0.1.3
├── pretty-bytes@0.1.2
├── html-minifier@0.5.6
└── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)

jshint-stylish@0.1.5 node_modules\jshint-stylish
├── text-table@0.2.0
└── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)

grunt-concurrent@0.5.0 node_modules\grunt-concurrent
├── pad-stdio@0.1.1 (lpad@0.2.1)
└── async@0.2.10

time-grunt@0.3.2 node_modules\time-grunt
├── date-time@0.1.1
├── pretty-ms@0.1.0
├── text-table@0.2.0
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
└── hooker@0.2.3

grunt-contrib-clean@0.5.0 node_modules\grunt-contrib-clean
└── rimraf@2.2.8

grunt-newer@0.7.0 node_modules\grunt-newer
├── rimraf@2.2.6
└── async@0.2.10

grunt-contrib-cssmin@0.9.0 node_modules\grunt-contrib-cssmin
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
├── clean-css@2.1.8 (commander@2.1.0)
└── maxmin@0.1.0 (pretty-bytes@0.1.2, gzip-size@0.1.1)

grunt-usemin@2.1.1 node_modules\grunt-usemin
├── debug@0.7.4
└── lodash@1.0.1

grunt-contrib-uglify@0.4.1 node_modules\grunt-contrib-uglify
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
├── maxmin@0.1.0 (pretty-bytes@0.1.2, gzip-size@0.1.1)
└── uglify-js@2.4.16 (uglify-to-browserify@1.0.2, async@0.2.10, optimist@0.3.7, source-map@0.1.34)

grunt-contrib-watch@0.6.1 node_modules\grunt-contrib-watch
├── async@0.2.10
├── tiny-lr-fork@0.0.5 (debug@0.7.4, faye-websocket@0.4.4, noptify@0.0.3, qs@0.5.6)
├── gaze@0.5.1 (globule@0.1.0)
└── lodash@2.4.1

load-grunt-tasks@0.4.0 node_modules\load-grunt-tasks
├── multimatch@0.1.0 (minimatch@0.2.14, lodash@2.4.1)
└── findup-sync@0.1.3 (glob@3.2.11, lodash@2.4.1)

grunt@0.4.5 node_modules\grunt
├── dateformat@1.0.2-1.2.3
├── which@1.0.9
├── eventemitter2@0.4.14
├── getobject@0.1.0
├── colors@0.6.2
├── rimraf@2.2.8
├── async@0.1.22
├── grunt-legacy-util@0.2.0
├── hooker@0.2.3
├── nopt@1.0.10 (abbrev@1.0.5)
├── exit@0.1.2
├── minimatch@0.2.14 (sigmund@1.0.0, lru-cache@2.5.0)
├── glob@3.1.21 (inherits@1.0.0, graceful-fs@1.2.3)
├── lodash@0.9.2
├── coffee-script@1.3.3
├── underscore.string@2.2.1
├── iconv-lite@0.2.11
├── findup-sync@0.1.3 (glob@3.2.11, lodash@2.4.1)
├── grunt-legacy-log@0.1.1 (underscore.string@2.3.3, lodash@2.4.1)
└── js-yaml@2.0.5 (argparse@0.1.16, esprima@1.0.4)

grunt-contrib-jshint@0.9.2 node_modules\grunt-contrib-jshint
├── hooker@0.2.3
└── jshint@2.4.4 (console-browserify@0.1.6, exit@0.1.2, minimatch@0.4.0, underscore@1.4.4, shelljs@0.1.4, c
li@0.4.5, htmlparser2@3.3.0)

grunt-svgmin@0.4.0 node_modules\grunt-svgmin
├── each-async@0.1.3
├── pretty-bytes@0.1.2
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
└── svgo@0.4.5 (colors@0.6.2, whet.extend@0.9.9, coa@0.4.1, sax@0.6.1, js-yaml@2.1.3)

grunt-bower-install@1.4.1 node_modules\grunt-bower-install
├── wiredep@1.4.4 (chalk@0.1.1, through2@0.4.2, glob@3.2.11, lodash@1.3.1)
└── bower-config@0.5.2 (osenv@0.0.3, graceful-fs@2.0.3, optimist@0.6.1, mout@0.9.1)

grunt-contrib-connect@0.7.1 node_modules\grunt-contrib-connect
├── connect-livereload@0.3.2
├── open@0.0.4
├── async@0.2.10
├── portscanner@0.2.2 (async@0.1.15)
└── connect@2.13.1 (uid2@0.0.3, methods@0.1.0, pause@0.0.1, cookie-signature@1.0.1, debug@0.8.1, fresh@0.2.
0, qs@0.6.6, bytes@0.2.1, buffer-crc32@0.2.1, raw-body@1.1.3, batch@0.5.0, cookie@0.1.0, compressible@1.0.0, n
egotiator@0.3.0, send@0.1.4, multiparty@2.2.0)

grunt-autoprefixer@0.7.6 node_modules\grunt-autoprefixer
├── diff@1.0.8
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
└── autoprefixer@1.3.1 (fs-extra@0.9.1, postcss@0.3.5, caniuse-db@1.0.30000081)

grunt-mocha@0.4.11 node_modules\grunt-mocha
├── lodash@2.3.0
├── mocha@1.18.2 (diff@1.0.7, growl@1.7.0, commander@2.0.0, mkdirp@0.3.5, debug@2.1.1, glob@3.2.3, jade@0.2
6.3)
└── grunt-lib-phantomjs@0.4.0 (eventemitter2@0.4.14, semver@1.0.14, temporary@0.0.8, phantomjs@1.9.15)

grunt-contrib-imagemin@0.6.1 node_modules\grunt-contrib-imagemin
├── pretty-bytes@0.1.2
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
├── mkdirp@0.3.5
├── async@0.2.10
└── image-min@0.2.3 (filesize@2.0.4, win-spawn@2.0.0, stream-combiner@0.0.4, multipipe@0.0.2, through2@0.4.
2, concat-stream@1.4.7, map-key@0.1.5, mout@0.9.1, jpegtran-bin@0.2.8, optipng-bin@0.3.11, gifsicle@0.1.7, png
quant-bin@0.1.7)
   invoke   mocha:app
   create test\bower.json
   create test\.bowerrc
   create test\spec\test.js
   create test\index.html


I'm all done. Running bower install for you to install the required dependencies. If this fails, try running t
he command yourself.


bower not-cached    https://github.com/mochajs/mocha.git#~1.14.0
bower resolve       https://github.com/mochajs/mocha.git#~1.14.0
bower not-cached    https://github.com/chaijs/chai.git#~1.8.0
bower resolve       https://github.com/chaijs/chai.git#~1.8.0
bower download      https://github.com/chaijs/chai/archive/1.8.1.tar.gz
bower download      https://github.com/mochajs/mocha/archive/1.14.0.tar.gz
bower extract       chai#~1.8.0 archive.tar.gz
bower resolved      https://github.com/chaijs/chai.git#1.8.1
bower extract       mocha#~1.14.0 archive.tar.gz
bower mismatch      Version declared in the json (1.12.0) is different than the resolved one (1.14.0)
bower resolved      https://github.com/mochajs/mocha.git#1.14.0
bower install       chai#1.8.1
bower install       mocha#1.14.0

chai#1.8.1 bower_components\chai

mocha#1.14.0 bower_components\mocha

yo [generator名]」コマンドで雛形を作成する。
おっさんが出現して質問してきたから「Bootstrap」と答えた。

この状況で必要な「npm install --save-dev」および「bower install --save」が叩かれてnode_modulesおよびbower_componentsディレクトリが作成されて必要なモジュールが入ってる。
しかも、Gruntfile.jsやappディレクトリ配下にスキャフォールドっぽいhtml、css、jsがある。
やばす。

Grunt入門

JavaScriptスクランナーのGruntをさわってみる。

npmとNode.js

npmNode Packege Manager)は、Node.js用のパッケージ管理コマンド。
JavaScriptのエコシステム(CoffeeScriptやGrunt等)はインストールにnpmを使用することが多い。
npmはNode.jsと同時にインストールされるので、Node.jsを入れておけばいい。
また、Node.jsはJavaScriptの実行エンジンでnodeで実行できる。

https://www.mpmjs.org/
http://nodejs.org/

LinuxCentOS)へのインストール

リポジトリ追加(32bit)

> rpm -ivh http://ftp.riken.jp/Linux/fedora/epel/6/i386/epel-release-6-8.noarch.rpm

リポジトリ追加(64bit)

> rpm -ivh http://ftp.riken.jp/Linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm

インストール

> yum install nodejs npm --enablerepo=epel
> node -v
v0.12.0

> npm -v
2.5.1

プロキシ配下環境の人は以下の設定をする。

> npm config set proxy http://<username>:<password>@<proxy-host>:<proxy-port>
> npm config set https-proxy http://<username>:<password>@<proxy-host>:<proxy-port>

★「https-proxy」のスキームは「https」ではなく「http」。


Grunt

Gruntはタスクランナー。
JavaScriptコードの圧縮、インスペクション、CoffeeScriptコンパイルといったコマンドで実行する作業を自動化するツール
Gruntは、本体とコマンドラインインターフェースが別パッケージとなっていて、後者はgrunt-cliという。

■インストール

> npm install -g grunt-cli
[UserHome]\AppData\Roaming\npm\grunt -> [UserHome]\AppData\Roaming\npm\node_modules\grunt-cli\bin\
grunt
grunt-cli@0.1.13 [UserHome]\AppData\Roaming\npm\node_modules\grunt-cli
├── resolve@0.3.1
├── nopt@1.0.10 (abbrev@1.0.5)
└── findup-sync@0.1.3 (lodash@2.4.1, glob@3.2.11)

> grunt -v
grunt-cli: The grunt command line interface. (v0.1.13)

オプションの「-g」はグローバルインストールの意で、npmのインストール場所にパッケージをインストールする。
付けない場合は、カレントディレクトリ(プロジェクトディレクトリ)のnode_modules内にインストールされる。
インストールしているパッケージの一覧を表示したい場合は「npm list [-g]」。
アンインストールしたい場合は「npm uninstall [-g] パッケージ名」。

プロジェクトディレクトリの作成

プロジェクト用のディレクトリを作成して初期化を行う。

> mkdir project
> cd project
> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (project)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to h:\workspace\project\package.json:

{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes)

npm initは対話式(ここでは全部Enterおした)。
package.json(Node.jsのパッケージ管理用ファイル)が作成される。
次にGrunt本体を導入する。

> npm install --save-dev grunt
grunt@0.4.5 node_modules\grunt
├── which@1.0.9
├── dateformat@1.0.2-1.2.3
├── getobject@0.1.0
├── eventemitter2@0.4.14
├── colors@0.6.2
├── rimraf@2.2.8
├── grunt-legacy-util@0.2.0
├── async@0.1.22
├── hooker@0.2.3
├── exit@0.1.2
├── nopt@1.0.10 (abbrev@1.0.5)
├── minimatch@0.2.14 (sigmund@1.0.0, lru-cache@2.5.0)
├── glob@3.1.21 (inherits@1.0.0, graceful-fs@1.2.3)
├── lodash@0.9.2
├── coffee-script@1.3.3
├── underscore.string@2.2.1
├── iconv-lite@0.2.11
├── findup-sync@0.1.3 (glob@3.2.11, lodash@2.4.1)
├── grunt-legacy-log@0.1.1 (underscore.string@2.3.3, lodash@2.4.1)
└── js-yaml@2.0.5 (esprima@1.0.4, argparse@0.1.16)

--save-dev」をつけるとpackage.jsondevDependenciesが追加され、そこに記載されているモジュールがnode_modulesディレクトリに配備される。
devDependenciesというのは開発時のみ利用するモジュールのバージョンを管理する。
ライブラリとして公開するようなモジュールだと、「--save」になる。
使用するぶんには「--save-dev」でおk。

使い方

Gruntの設定はGruntfile.jsで行い、JavaScriptCoffeeScriptで記述でき、通常プロジェクトルートへ配置する。

> touch Gruntfile.js

記載方法は下記の関数を定義し、この中にタスクを記載していく。

module.exports = function(grunt) {
  // タスク
}

タスクのザックリとした書き方は以下。

module.exports = function(grunt) {

  // initConfigの中で各タスクを設定
  grunt.initConfig({ 
    // uglifyタスク
    uglify: {
      // uglifyタスクの設定を記述
    }
  });

  // プラグインをロード0
  // grunt.loadNpmTasks('プラグイン名');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // gruntコマンドのデフォルトタスクにuglifyを追加
  // grunt.registerTask(<タスク名>, [<タスクの説明>,] <タスク内容>);
  grunt.registerTask('default', ['uglify']);
}

grunt」でタスクを実行できる。
上記は例としてgrunt-contrib-uglifyというプラグインを使用しているが、実際には下記のコマンドでプラグインを事前に導入しておく必要がある。

> npm install --save-dev grunt-contrib-uglify
grunt-contrib-uglify@0.8.0 node_modules\grunt-contrib-uglify
├── uri-path@0.0.2
├── chalk@0.5.1 (ansi-styles@1.1.0, escape-string-regexp@1.0.3, supports-color@0.2.0, has-ansi@0.1.0, strip-ansi@0.3.0)
├── uglify-js@2.4.16 (uglify-to-browserify@1.0.2, async@0.2.10, optimist@0.3.7, source-map@0.1.34)
├── maxmin@1.0.1 (figures@1.3.5, pretty-bytes@1.0.3, chalk@1.0.0, gzip-size@1.0.0)
└── lodash@3.3.1

Grunt実行例

標準出力

■Gruntfile.js

module.exports = function(grunt) {
  grunt.registerTask('default', 'Hello World Task', function() {
    grunt.log.writeln("Hello World !");
  });
}

■実行

> grunt
Running "default" task
Hello World !

Done, without errors.


タスク名設定

grunt.registerTaskの第一引数にタスク名を付けることができる。
■Gruntfile.js

module.exports = function(grunt) {
  grunt.registerTask('hello', 'Hello World Task', function() {
    grunt.log.writeln("Hello World !");
  });
}

■タスク名を指定して実行

> grunt hello
Running "hello" task
Hello World !

Done, without errors.


引数

引数(arg1、arg2)をつけてみる。
■Gruntfile.js

module.exports = function(grunt) {
  grunt.registerTask('sayHello', 'Say Hello', function(arg1, arg2) {
    grunt.log.writeln("Hello " + arg1 + arg2 + " !");
  });
}

■実行(引数は「:」区切りで渡す)

>grunt sayHello:Mr.:Tanaka
Running "sayHello:Mr.:Tanaka" (sayHello) task
Hello Mr.Tanaka !

Done, without errors.

参考:
http://js.studio-kingdom.com/grunt