改めて、Grunt.jsをインストール

Web制作で面倒な作業を自動化するビルドツール、Grunt v0.4 入門|Web Design KOJIKA17

を参考に、Grunt.jsをインストールしてみたいと思います。

 

今の私の状況は、Node.jsとgrunt-cliのインストールは出来ていますので、下準備が整った状態となるようです。

 

「Grunt.jsを使ってみる」の項からスタートです。

Grunt.js v0.4にはまず基本となるファイル、package.json と Gruntfile.js(Gruntfile.coffee)が必要になります。

 で、それは各プロジェクトごとに必要なのかな?

 

とりあえず、「testProject」という作業フォルダを作って、ターミナルで作業フォルダまで移動します。$ npm init とコマンドします。

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

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


Is this ok? (yes)  yes

こんな感じです。

 対話形式で質問されるのですが、「entry point: (index.js) 」から何を答えればいいのか分からなくなって、とりあえずenterキーを押していきました。

最後は「yes」で。

すると、作業フォルダに「package.json」が出来ていました!

 

次に、

$ npm install grunt --save-dev

 で、gruntをインストールします。

・・・・なんか、npmでいっぱいインストールされたっぽいです。

作業フォルダを覗いてみると

testProject
├node_modules
│└grunt(この中に数えきれないくらいたくさんのファイルとフォルダが・・)
└package.json

こんなんでいいのか?不安に駆られながら、、とりあえず進もう!

 

以下の2つをインストールします。

ファイルが更新された自動感知して処理を実行する grunt-contrib-watch
cssファイルの改行やコメントを削除してファイルサイズを少なくする grunt-contrib-cssmin

$ npm install grunt-contrib-watch grunt-contrib-cssmin --save-dev

これまた、たくさんインストールされました。

 

で、作業フォルダを覗いてみると、、ほうほう

testProject
├node_modules
│├grunt(この中に数えきれないくらいたくさんのファイルとフォルダが・・)
│├grunt-contrib-cssmin(この中に数えきれないくらいたくさんのファイルとフォルダが・・)
│└grunt-contrib-watch(この中に数えきれないくらいたくさんのファイルとフォルダが・・)
└package.json

となっています。

なるほど!

で、この「node_modulesフォルダ」を削除しても、「package.json」があれば、$ npm installで同じ環境をインストールすることができる!というすぐれものらしい。

もちろん、新しいプロジェクトを作成する時は、この「package.json」を作業フォルダにコピーして、$ npm installで準備完了ってわけですね。すばらしい!

 

お次は「Gruntfile.js」。

作業フォルダに「Gruntfile.js」ファイルを作成して、

module.exports = function(grunt) {
  grunt.initConfig({
    cssmin: {
      compress: {
        files: {
          './min.css': ['css/base.css', 'css/style.css']
        }
      }
    },
    watch: {
      files: ['css/*.css'],
      tasks: ['cssmin']
    }
  });
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-watch');grunt.registerTask('default', ['cssmin', 'watch']);
};

と入力。

これでいいのかな??

 

作業フォルダで、$ gruntをコマンドしてみたら

$ grunt
Running "cssmin:compress" (cssmin) task
>> Destination not written because minified CSS was empty.

Running "watch" task
Waiting...

となってます!

Running "watch" task
Waiting...

ってことは成功ですよね?