ぺーぺーSEのブログ

備忘録・メモ用サイト。

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