Program LOG

勉強した内容をまとめ中。。。間違ってたら教えて。。。

Grunt.js開発の実行手順まとめ

開発環境について色々記事にしてきましたが、
実際Gruntで開発をする想定で、環境を用意する場合の事を考えてみました。

Gruntのインストールに関しては、別の記事が何個かありますので、
以下を確認してください!
CygwinでGruntjsをインストール - Program LOG
CygwinでGruntjsを使ってみる - Program LOG
ChefでSass+Compass+Coffee+Gruntの実行環境を作る(1) - Program LOG
ChefでSass+Compass+Coffee+Gruntの実行環境を作る(2) - Program LOG

ちなみに今回は、ChefでGruntの実行環境がある前提での記事になりますので、ご注意を!

前提

まず、gruntの環境を用意する上で、package.jsonを生成しますが、
それをどこに作り、どこをルートに開発をしたいかって考えました。
仮想サーバー内部に環境を用意してしまうと、GitなどでGUIを使えないことになります。
GUI大好きな僕からすると、すごい微妙・・・w
やっぱり、Vagrantの共有フォルダをルートにして開発したいと思います。

共有フォルダで開発しよう!

共有フォルダにchefで「root」ってディレクトリを作成して、
その中に「docroot」ってディレクトリをさらに作成。
そして、「/var/www/html/」にシンボリックリンクで、
「/vagrant/root/docroot/」を見るよう設定しました。
レシピは以下の通りです。

#ディレクトリの作成
directory "/vagrant/root/docroot/" do
  owner "vagrant"
  group "vagrant"
  recursive true
  mode 0755
  action :create
  not_if { ::File.exists?("/vagrant/root/docroot/")}
end
#元のディレクトリを削除しておく。
directory "/var/www/html" do
  action :delete
  not_if { File.symlink?('/var/www/html') }
end
#シンボリックリンク
link "/var/www/html" do
  to "/vagrant/root/docroot"
end

実行結果は以下の通り

$ knife solo cook develop
・・・中略・・・
 * directory[/vagrant/root/docroot/] action create
    - create new directory /vagrant/root/docroot/
    - change mode from '' to '0755'
    - change owner from '' to 'vagrant'
    - change group from '' to 'vagrant'

  * directory[/var/www/html] action delete
    - delete existing directory /var/www/html

  * link[/var/www/html] action create
    - create symlink at /var/www/html to /vagrant/root/docroot

package.jsonを生成する。

これは、chefにやらせなくてもいいかと思いますね。
仮に、毎回使いたい物が一緒だったとしても、自動的に実行させなくてもいいかと。。。
手順さえしっかりしていればの話しですが・・・w
これは、以前も実践していますが、おさらいとして記載しておきたいと思います。

[vagrant@localhost root]$ 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: (root)
version: (0.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (BSD-2-Clause)
About to write to /vagrant/root/package.json:

{
  "name": "root",
  "version": "0.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "BSD-2-Clause"
}


Is this ok? (yes)
[vagrant@localhost root]$ ll
total 1
drwxrwxrwx 1 vagrant vagrant   0 Jul 13 07:04 docroot
-rwxrwxrwx 1 vagrant vagrant 209 Jul 13 07:08 package.json

前回Cygwinでは出来なかったので、ちょっと感動・・・w
対話しましたよー!w(まぁ、すべてエンターなんですが・・・w)
続いて、Grunt本体のモジュールをインストールしたいと思います。

[vagrant@localhost root]$ npm install grunt --save-dev
npm WARN package.json root@0.0.0 No description
npm WARN package.json root@0.0.0 No repository field.
npm WARN package.json root@0.0.0 No README data
・・・中略・・・
npm ERR! error rolling back Error: UNKNOWN, unlink '/vagrant/root/node_modules/grunt/node_modules/lodash/lodash.js'
npm ERR! error rolling back  grunt@0.4.5 { [Error: UNKNOWN, unlink '/vagrant/root/node_modules/grunt/node_modules/lodash/lodash.js']
npm ERR! error rolling back   errno: -1,
npm ERR! error rolling back   code: 'UNKNOWN',
npm ERR! error rolling back   path: '/vagrant/root/node_modules/grunt/node_modules/lodash/lodash.js' }
npm ERR! Error: UNKNOWN, symlink '../which/bin/which'
npm ERR! If you need help, you may report this log at:

ぬ?・・・・エラー?wなんで?w
エラーを調べてみたけど、よく分からんwけど、対処方法が見つかり「--no-bin-links」をつけて再度実行

[vagrant@localhost root]$ npm install grunt --save-dev --no-bin-links
npm WARN package.json root@0.0.0 No description
npm WARN package.json root@0.0.0 No repository field.
npm WARN package.json root@0.0.0 No README data
grunt@0.4.5 node_modules/grunt
├── which@1.0.5
├── dateformat@1.0.2-1.2.3
├── eventemitter2@0.4.14
├── getobject@0.1.0
├── rimraf@2.2.8
├── colors@0.6.2
├── hooker@0.2.3
├── async@0.1.22
├── grunt-legacy-util@0.2.0
├── 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)
├── lodash@0.9.2
├── coffee-script@1.3.3
├── glob@3.1.21 (inherits@1.0.0, graceful-fs@1.2.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.15)

いけました!多分大丈夫っぽいw
原因の特定はできないけど、vagrant環境だとあるみたいです。

プラグインを入れよう!

続いて、代表的なプラグインを入れていこうと思います。
今回入れるのは、compass+coffee+watchの3種です。
まずは、ディレクトリの作成しておきたいと思います。
以下のような構成です。

/vagrant/root/docroot/
├── css (sassのコンパイル先)
├── sass (Sassファイル入れる場所)
├── js (coffeeのコンパイル先)
└── coffee (coffeeの入れる場所)

[vagrant@localhost root]$ cd ./docroot/
[vagrant@localhost docroot]$ mkdir css
[vagrant@localhost docroot]$ mkdir sass
[vagrant@localhost docroot]$ mkdir js
[vagrant@localhost docroot]$ mkdir coffee

続いて、テスト用のcoffeeファイルとsassファイルを作成しておきます。

[vagrant@localhost docroot]$ vim ./sass/style.scss
#navbar {
  width: 80%;
  height: 23px;
  ul { list-style-type: none; }
  li {
    float: left;
    a { font-weight: bold; }
  }
}
[vagrant@localhost docroot]$ vim ./coffee/sample.coffee
(function() {
  alert("hello world!");

}).call(this);

ひとまず、この2つのファイルを自動的にコンパイルしてくれるように作成していきます。
それでは、各種プラグインのインストールから行います。

[vagrant@localhost root]$ npm install grunt-contrib-coffee --save-dev --no-bin-links
・・・中略・・・
grunt-contrib-coffee@0.10.1 node_modules/grunt-contrib-coffee
├── chalk@0.4.0 (has-color@0.1.7, ansi-styles@1.0.0, strip-ansi@0.1.1)
├── lodash@2.4.1
└── coffee-script@1.7.1 (mkdirp@0.3.5)

[vagrant@localhost root]$ npm install grunt-contrib-compass --save-dev --no-bin-links
・・・中略・・・
grunt-contrib-compass@0.9.0 node_modules/grunt-contrib-compass
├── dargs@0.1.0
├── async@0.8.0
├── tmp@0.0.23
└── bin-version-check@0.1.0 (minimist@0.1.0, semver@2.3.1, bin-version@0.1.0)

[vagrant@localhost root]$ npm install grunt-contrib-watch --save-dev --no-bin-links
・・・中略・・・
grunt-contrib-watch@0.6.1 node_modules/grunt-contrib-watch
├── async@0.2.10
├── lodash@2.4.1
├── tiny-lr-fork@0.0.5 (debug@0.7.4, faye-websocket@0.4.4, qs@0.5.6, noptify@0.0.3)
└── gaze@0.5.1 (globule@0.1.0)

3種類とも無事にインストールする事が出来ました!

あ!compassのプロジェクトを作るのを忘れていました・・・orz
compassのプロジェクトを作成します。

[vagrant@localhost root]$ compass create docroot
[vagrant@localhost root]$ mv docroot/config.rb ./
[vagrant@localhost root]$ vim confing.rb
http_path = "docroot/"
css_dir = "docroot/css"
sass_dir = "docroot/sass"
images_dir = "docroot/images"
javascripts_dir = "docroot/js"

こんな感じですかね?
一回テストで流しておきます。

[vagrant@localhost root]$ compass compile
   create docroot/css/ie.css
   create docroot/css/print.css
   create docroot/css/screen.css
   create docroot/css/style.css

正常にいったようです。

Gruntfile.js作成

sassとcoffeeをコンパイルし、ためのGruntfile.jsを記述しましょう。

module.exports = function(grunt) {
  grunt.initConfig({
    coffee: {
      compile: {
        files:[{ 
         expand: true,
         cwd: 'docroot/coffee',
         src: ['**/*.coffee'],
         dest: 'docroot/js/',
         ext: '.js',
       }]
      }
    },
    compass: {
        dist: {
            options: {
                config: 'config.rb'
            }
        }
    },
    watch: {
      coffee:{
        tasks: 'coffee',
        files:['docroot/**/*.coffee']
      },
      compass:{
        tasks: 'compass',
        files:['docroot/**/*.scss']
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-coffee');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.registerTask('default', ['coffee','compass','watch']);
};

$ gruntを実行してみよう!
それでは早速gruntを実行したいと思います。

[vagrant@localhost root]$ grunt
Running "coffee:compile" (coffee) task

Running "compass:dist" (compass) task
unchanged docroot/sass/ie.scss
unchanged docroot/sass/print.scss
unchanged docroot/sass/screen.scss
unchanged docroot/sass/style.scss
Compilation took 0.042s

Running "watch" task
Waiting...

正常に各コンパイルしてから、waitingし始めました!

Gruntをバックグランドで実行しておこう!

最後に、gruntコマンドをバックグラウンドで実行しておけば、
変更があったときだけ、実施内容が表示されます。
waitingするのであれば、オススメです!

[vagrant@localhost root]$ nohup grunt &
[1] 3830
[vagrant@localhost root]$ nohup: ignoring input and appending output to `nohup.out'
[vagrant@localhost root]$

nohup grunt &は、ログアウトしても、そのまま実行してくれますので、
オススメです!例えば、デバッグなんかをしたくて、終了させて、インラインで実行したい場合は
以下の手順となります。
ただ、実行した内容が、nohup.outというファイルに書き出されますので、そちらを確認するのもいいと思います。
(ファイルがかなり蓄積されるので、ファイルを作成しないというのもいいかもしれません。)

[vagrant@localhost ~]$ ps aux | grep 'grunt'
vagrant   3830  2.6  9.6 717572 45492 ?        Sl   03:27   0:12 grunt
vagrant   3933  0.0  0.1 103236   856 pts/0    S+   03:34   0:00 grep grunt
[vagrant@localhost ~]$ kill 3830
[vagrant@localhost ~]$ cd /vagrant/root/
[vagrant@localhost ~]$ grunt

という感じです。
nohup.outを作成しないで実行する場合は以下の通りです。

[vagrant@localhost root]$ nohup grunt > /dev/null 2>&1 &
[1] 3990


いかがでしたでしょうか?
ひとまず、gruntで簡単にコンパイル作業を自動化し、監視もバッグラウンドで行うといった
感じで、構成してみました!
今後は、Gruntで色んなタスクを自動化したいと思います。。。

手順コマンドまとめ

$ cd /vagrant/root/
$ npm init
> 対話は全てエンター
$ npm install grunt --save-dev --no-bin-links
$ compass create docroot
$ npm install grunt-contrib-coffee --save-dev --no-bin-links
$ npm install grunt-contrib-compass --save-dev --no-bin-links
$ npm install grunt-contrib-watch --save-dev --no-bin-links
$ grunt &
#もしくは
$ nohup grunt > /dev/null 2>&1 &

使用環境