LoginSignup
15

More than 5 years have passed since last update.

Grunt で Hello World

Posted at

概要

タスク自動化ツール Grunt (v0.4.5) の使い方メモとして、Hello World と表示するタスクの書き方を説明します。

※ 自作タスクをつくるサンプルです。プラグインは出てきません。
※ Grunt(grunt-cli)のインストール方法については他の記事を参照してください。

ファイルの準備

~/grunt-project という名前のディレクトリを今回の作業ディレクトリとします。

  1. cd ~/grunt-project
  2. npm init
    • 出てきた質問に答えます。Enterでスキップできます
    • package.json というファイルが作られます
  3. npm install grunt --save-dev
    • package.json の devDependencies に grunt が追加されます
    • node_modules に grunt ディレクトリが追加されます
  4. touch Gruntfile.js
    • Windows では右クリックメニューなどからGruntfile.jsを新規作成

本編

いろいろな方法で、コンソールにHello Worldと表示させるタスクを定義します。
それぞれの書き方で同じ動作をしますが、下に行くほど保守性が高まります。

最小限

最小限の記述で動かしてみます。

Gruntfile.js
module.exports = function(grunt) {

  grunt.registerTask('default', function() {
    console.log('Hello World');
  });

};

grunt default または grunt を実行してください。
下記が表示されれば成功です。

Running "default" task
Hello World

Done, without errors.

タスクに名前を付ける

Hello World を表示するというタスクに hello という名前を付けます。

Gruntfile.js
module.exports = function(grunt) {

  grunt.registerTask('hello', function() {
    console.log('Hello World');
  });

};

これで grunt hello と入力すると、先ほどと同じ結果が得られます。
ただし、grunt 単体だとdefaultのタスクがないよという旨の警告(Warning: Task "default" not found. Use --force to continue.)とともに失敗します。
grunt 単体で動作させたい場合は、下記のようにdefaultタスクに登録します。

Gruntfile.js
module.exports = function(grunt) {

  grunt.registerTask('hello', function() {
    console.log('Hello World');
  });

  //grunt.registerTask('default', 'hello');
  grunt.registerTask('default', ['hello']);

};

コメントアウトした書き方でも動きますが、今後複数のタスクを登録することを考えて配列にしています。

モジュール化する

今後のことを考えて、タスクの定義を他のファイルで行います。タスク定義ファイル用のディレクトリがあると便利なので、同時に作ります。

  1. mkdir tasks
  2. touch tasks/hello.js
tasks/hello.js
module.exports = function(grunt) {

  grunt.registerTask('hello', function() {
    console.log('Hello World');
  });

};

Gruntfile.js
module.exports = function(grunt) {

  // tasksディレクトリ以下のタスクをすべて読み込む
  grunt.loadTasks('./tasks');

  grunt.registerTask('default', ['hello']);

};

参考

  • ドットインストール Grunt入門 [Link]
  • Getting Started with Grunt: The JavaScript Task Runner / Jaime Pillora [Link]

ひとこと

Grunt は最初コンパイルのためのツールかと思っていたのですが、node.jsでできることはなんでもタスク化できるのですね。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15