Gruntを試してみる

CentOSにNode.jsをインストールしてみる
の続き

Gruntを試してみる。

インストール

gruntのコマンドラインインターフェースをグローバルにインストールする。

$ sudo npm install -g grunt-cli

サンプルの準備

適当なディレクトリを作って、そこで試す。

$ mkdir sample
$ cd sample

まず、gruntをインストールする。

$ npm install grunt

「-g」を付けずにinstallすると、カレントディレクトリに
下記のような感じでgruntがインストールされる。

$ tree
.
└── node_modules
    └── grunt
        ├── CONTRIBUTING.md
        ├── LICENSE-MIT
        ├── README.md
        ・・・

Hello, world!

Hello, world!を出力してみる。

$ vi Gruntfile.js
module.exports = function(grunt) {
  // task
  grunt.registerTask('hello', function() {
    console.log('Hello World');
  });
};

gruntでhelloタスクを実行すると、Hello, world!が出力される。

$ grunt hello
Running "hello" task
Hello World

デフォルトのタスクの指定

デフォルトに指定すると、

$ vi Gruntfile.js
module.exports = function(grunt) {
  // task
  grunt.registerTask('hello', function() {
    console.log('Hello World');
  });
  grunt.registerTask('default', 'hello');	←追加
};

タスクを指定しない場合、デフォルトのタスクが実行される。

$ grunt
Running "hello" task
Hello World

CSS圧縮

試しにCSSを圧縮してみる。

下記のプラグインが必要になるのでインストールする。

$ npm install grunt-contrib-cssmin

CSSを圧縮するGruntfileを作成する。

$ vi Gruntfile.js
module.exports = function(grunt) {
  // config
  grunt.initConfig({
    cssmin: {
      'sample.min.css': 'sample.css',
    }
  });

  // plugin
  grunt.loadNpmTasks('grunt-contrib-cssmin');

  // task
  grunt.registerTask('default', 'cssmin');
};

下記のCSSを圧縮してみる。

$ vi sample.css
body {
  margin:0px;
}

実行すると、

$ grunt
Running "cssmin:sample.min.css" (cssmin) task
File sample.min.css created: 21 B → 14 B

下記のようにCSSが圧縮される。

$ cat sample.min.css
body{margin:0}