Grunt でhtml, css, JavaScript のアレコレを便利にすると捗るので、Getting started を和訳した

Grunt とは

Grunt: The JavaScript Task Runner http://gruntjs.com/

Gruntはhtml, css, JavaScriptに関する一連の作業を自動化するビルドツールです。 例えば、複数のJavaScriptを1つにしたり、cssやjsを圧縮したり、などが出来ます。

Grunt の使い方

公式サイトの"Getting started"に書いてあります。エンジニアならまずGetting startedを読んだ方がいいよね。

という訳で以下、公式サイトからの引用と和訳です。

注意

  • 2014/02/14時点のGetting startedです。
  • 英語力の低い私の和訳なので、所々は間違っているかもしれません。
  • 間違いはコメントとかで指定頂けると嬉しいです。

Getting started (はじめに)

Grunt and Grunt plugins are installed and managed via npm, the Node.js package manager.

Grunt 0.4.x requires stable Node.js versions >= 0.8.0. Odd version numbers of Node.js are considered unstable development versions.

Grunt と Grunt plugins は Node.js のパッケージマネージャである npm を経由してインストールされます。

Grunt 0.4.x は安定したNode.jsのバージョン >= 0.8.0 が必要です。Node.jsの奇数バージョン番号は不安定な開発バージョンであると見なされます。

Installing the CLI (CLIのインストール)

If you're upgrading from Grunt 0.3, please see Grunt 0.3 Notes

もし Grunt 0.3 からアップグレードする場合、Grunt 0.3 Notes を読んでください。

In order to get started, you'll want to install Grunt's command line interface (CLI) globally. You may need to use sudo (for OSX, *nix, BSD etc) or run your command shell as Administrator (for Windows) to do this.

使い始めるためには、グローバル環境にGruntのコマンドラインインターフェース(CLI)をインストールする。これを行うには、(Windowsの場合)管理者としてコマンドを実行するか、(OSX, *nix, BSD etc の場合)sudoを使用する必要があります。

npm install -g grunt-cli

This will put the grunt command in your system path, allowing it to be run from any directory.

gruntコマンドをシステムパスに通し、どのディレクトリでも実行できるように設定します。

Note that installing grunt-cli does not install the Grunt task runner! The job of the Grunt CLI is simple: run the version of Grunt which has been installed next to a Gruntfile. This allows multiple versions of Grunt to be installed on the same machine simultaneously.

grunt-cliのインストールは Grunt タスクランナーをインストールしない事に注意してください! Grunt CLI の仕事はシンプルです: Gruntfileでインストールされた Grunt のバージョンを実行します。これにより同じマシンにGruntの複数のバージョンをインストールすることができます。

How the CLI works (CLIの動作)

Each time grunt is run, it looks for a locally installed Grunt using node's require() system. Because of this, you can run grunt from any subfolder in your project.

If a locally installed Grunt is found, the CLI loads the local installation of the Grunt library, applies the configuration from your Gruntfile, and executes any tasks you've requested for it to run.

To really understand what is happening, read the code. It's very short.

毎回gruntを実行すると、nodeのrequire()システムを使ってインストールされたGruntをローカルから探します。これにより、プロジェクト内の任意のディレクトリでgruntを実行できます。

もしインストールされたGruntを見つけた場合、CLIはGruntのライブラリをロードし、Gruntfileから設定を読み込み、指定されたタスクを実行します。

実際に何が行われているかを理解するために、コードを読んでください。これはとても短いです。

Working with an existing Grunt project (既存のGruntプロジェクトでの動作)

Assuming that the Grunt CLI has been installed and that the project has already been configured with a package.json and a Gruntfile, it's very easy to start working with Grunt:

Grunt CLIがインストールされ、既にプロジェクトがpackage.jsonGruntfileによって構成されていると仮定すれば、Gruntを使い始めるのはとても簡単です。

  1. Change to the project's root directory.
  2. Install project dependencies with npm install.
  3. Run Grunt with grunt.
  1. プロジェクトのルートディレクトリに移動する。
  2. npm installでプロジェクトの依存関係をインストールする。
  3. gruntでGruntを実行する。

That's really all there is to it. Installed Grunt tasks can be listed by running grunt --help but it's usually a good idea to start with the project's documentation.

本当にこれだけです。インストールされたGruntのタスクはgrunt --helpを実行すると一覧にできますが、通常はプロジェクトのドキュメントをまず読むことをお勧めします。

Preparing a new Grunt project (新しいGruntプロジェクトの準備)

A typical setup will involve adding two files to your project: package.json and the Gruntfile.

package.json: This file is used by npm to store metadata for projects published as npm modules. You will list grunt and the Grunt plugins your project needs as devDependencies in this file.

Gruntfile: This file is named Gruntfile.js or Gruntfile.coffee and is used to configure or define tasks and load Grunt plugins.

典型的なセットアップ方法はプロジェクトに2つのファイル(package.jsonGruntfile)を追加することです。

package.json: このファイルはnpmモジュールとして作成されたプロジェクトのメタデータを保存するためにnpmによって使用されます。このファイルのdevDependenciesにプロジェクトに必要なgruntとGruntプラグインを追加する必要があります。

Gruntfile: このファイルはGruntfile.jsGruntfile.coffeeという名前し、設定やタスクの定義、Gruntプラグインの読み込みに使用されます。

package.json

The package.json file belongs in the root directory of your project, next to the Gruntfile, and should be committed with your project source. Running npm install in the same folder as a package.json file will install the correct version of each dependency listed therein.

package.jsonはプロジェクトのルートディレクトリに置き、Gruntfileと、ソースコードと一緒にコミットすべきです。package.jsonと同じディレクトリでnpm installを実行すると、記載されている各依存関係の正しいバージョンがインストールされます。

There are a few ways to create a package.json file for your project:

プロジェクトのpackage.jsonを作る方法はいくつかあります。

  • Most grunt-init templates will automatically create a project-specific package.json file.
  • The npm init command will create a basic package.json file.
  • Start with the example below, and expand as needed, following this specification.
  • grunt-initはプロジェクト固有のpackage.json自動的に作成します。
  • npm initコマンドは一般的なpackage.jsonを作成します。
  • 例を参考に、仕様に従いながら必要に応じて追記していきます。
{
  "name": "my-project-name",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.2",
    "grunt-contrib-jshint": "~0.6.3",
    "grunt-contrib-nodeunit": "~0.2.0",
    "grunt-contrib-uglify": "~0.2.2"
  }
}

Installing Grunt and gruntplugins (Gruntのインストールとgruntプラグイン)

The easiest way to add Grunt and gruntplugins to an existing package.json is with the command npm install <module> --save-dev. Not only will this install <module> locally, but it will automatically be added to the devDependencies section, using a tilde version range.

For example, this will install the latest version of Grunt in your project folder, adding it to your devDependencies:

既存のpackage.jsonにGruntやgruntプラグインを追加する最も簡単な方法はnpm install <module> --save-devコマンドを使うことです。これはローカルに<module>をインストールするだけでなく、チルダを使うバージョン範囲devDependencies自動的に追加します。

たとえば、下記コマンドはプロジェクトのフォルダ内にGruntの最新バージョンをインストールし、devDependenciesに追加します。

npm install grunt --save-dev

The same can be done for gruntplugins and other node modules. Be sure to commit the updated package.json file with your project when you're done!

同じことがgruntプラグインや他のnodeモジュールで実行できます。実行したら、更新したpackage.jsonを必ずコミットしてください。

The Gruntfile

The Gruntfile.js or Gruntfile.coffee file is a valid JavaScript or CoffeeScript file that belongs in the root directory of your project, next to the package.json file, and should be committed with your project source.

Gruntfile.jsまたはGruntfile.coffeeファイルは正しいJavaScriptCoffeeScriptファイルであり、プロジェクトのルートディレクトリに置き、ソースコードと一緒にコミットしなければなりません。

A Gruntfile is comprised of the following parts:

Gruntfileは下記のパーツで構成されています。

  • The "wrapper" function
  • Project and task configuration
  • Loading Grunt plugins and tasks
  • Custom tasks
  • ラッパー関数
  • プロジェクトとタスクの設定
  • Gruntプラグインとタスクの読み込み
  • カスタムタスク

An example Gruntfile (Gruntfileのサンプル)

In the following Gruntfile, project metadata is imported into the Grunt config from the project's package.json file and the grunt-contrib-uglify plugin's uglify task is configured to minify a source file and generate a banner comment dynamically using that metadata. When grunt is run on the command line, the uglify task will be run by default.

下記のGruntfileでは、プロジェクトのメタデータpackage.jsonからインポートし、grunt-contrib-uglifyプラグインuglifyタスクはソースファイルを圧縮し、メタデータで動的にバナーコメントを生成するように設定されています。

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/<%= pkg.name %>.js',
        dest: 'build/<%= pkg.name %>.min.js'
      }
    }
  });

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Default task(s).
  grunt.registerTask('default', ['uglify']);

};

Now that you've seen the whole Gruntfile, let's look at its component parts.

Gruntfileの全体をみてきたところで、その構成パーツをみていきましょう。

The "wrapper" function (ラッパー関数)

Every Gruntfile (and gruntplugin) uses this basic format, and all of your Grunt code must be specified inside this function:

すべてのGruntfile(とgruntプラグイン)はこの基本的なフォーマットを使い、Gruntのコードの全てはこの関数の中に書く必要があります。

module.exports = function(grunt) {
  // Do grunt-related things in here
};

Project and task configuration (プロジェクトとタスクの設定)

Most Grunt tasks rely on configuration data defined in an object passed to the grunt.initConfig method.

たいていのGruntタスクはgrunt.initConfigメソッドに渡されたオブジェクトで定義された設定に依存します。

In this example, grunt.file.readJSON('package.json') imports the JSON metadata stored in package.json into the grunt config. Because <% %> template strings may reference any config properties, configuration data like filepaths and file lists may be specified this way to reduce repetition.

この例では、gruntの設定の中でgrunt.file.readJSON('package.json')を使いpackage.jsonに保存されているJSONメタデータをインポートしています。<% %>テンプレート文字列は任意の設定や、ファイルパスやファイルリストのようなデータ設定を、繰り返しを減らすために指定することができます。

You may store any arbitrary data inside of the configuration object, and as long as it doesn't conflict with properties your tasks require, it will be otherwise ignored. Also, because this is JavaScript, you're not limited to JSON; you may use any valid JS here. You can even programmatically generate the configuration if necessary.

タスクが必要とするプロパティに競合しない限り、オブジェクトの中に任意の属性でデータを保存してもよく、それ以外は無視されます。Javascriptであれば、JSONに限定しなくても良い(ここに任意の正しいJSを使えます)。もし必要であればプログラムで設定を生成できます。

Like most tasks, the grunt-contrib-uglify plugin's uglify task expects its configuration to be specified in a property of the same name. Here, the banner option is specified, along with a single uglify target named build that minifies a single source file to a single destination file.

たいていのタスクのように、grunt-contrib-uglifyプラグインuglifyタスクは同じ名前のプロパティで指定された設定を想定しています。ここでは、bannerオプションは、1つのソースファイルを圧縮された1つのファイルにするbuildというターゲットと一緒に指定されています。

// Project configuration.
grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  uglify: {
    options: {
      banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
    },
    build: {
      src: 'src/<%= pkg.name %>.js',
      dest: 'build/<%= pkg.name %>.min.js'
    }
  }
});

Loading Grunt plugins and tasks (Gruntプラグインとタスクの読み込み)

Many commonly used tasks like concatenation, minification and linting are available as grunt plugins. As long as a plugin is specified in package.json as a dependency, and has been installed via npm install, it may be enabled inside your Gruntfile with a simple command:

結合、圧縮、構文チェックなど多くの一般的なタスクがgrunt pluginsとして提供されています。プラグインpackage.jsonの依存に指定して、npm installでインストールし、Gruntfileの中で下記のように書くと有効になります。

// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');

Note: the grunt --help command will list all available tasks.

ノート: grunt --helpコマンドは全ての有効なタスクを一覧表示します。

Custom tasks (カスタムタスク)

You can configure Grunt to run one or more tasks by default by defining a default task. In the following example, running grunt at the command line without specifying a task will run the uglify task. This is functionally the same as explicitly running grunt uglify or even grunt default. Any number of tasks (with or without arguments) may be specified in the array.

defaultタスクを定義することで、デフォルトで1つ以上のタスクを実行するようGruntを設定できます。次の例では、タスクを指定せずにコマンドラインgruntを実行するとuglifyタスクが実行します。これは機能的にはgrunt uglifygrunt defaultを明示的に実行するのと同じです。タスクは配列で任意の数を指定できます。

// Default task(s).
grunt.registerTask('default', ['uglify']);

If your project requires tasks not provided by a Grunt plugin, you may define custom tasks right inside the Gruntfile. For example, this Gruntfile defines a completely custom default task that doesn't even utilize task configuration:

もしプロジェクトがGruntプラグインで提供されていないタスクを必要とする場合、Gruntfileの中にカスタムタスクを定義することもできます。たとえば、このGruntfileはタスク設定を利用しない独自のdefaultタスクを定義しています。

module.exports = function(grunt) {

  // A very basic default task.
  grunt.registerTask('default', 'Log some stuff.', function() {
    grunt.log.write('Logging some stuff...').ok();
  });

};

Custom project-specific tasks don't need to be defined in the Gruntfile; they may be defined in external .js files and loaded via the grunt.loadTasks method.

カスタムタスクはGruntfileの中に定義する必要はありません。これらは外部の.jsファイルに定義し、grunt.loadTasksで読み込みことが出来ます。

Further Reading (参考文献)

  • The Installing grunt guide has detailed information about installing specific, production or in-development, versions of Grunt and grunt-cli.
  • The Configuring Tasks guide has an in-depth explanation on how to configure tasks, targets, options and files inside the Gruntfile, along with an explanation of templates, globbing patterns and importing external data.
  • The Creating Tasks guide lists the differences between the types of Grunt tasks and shows a number of sample tasks and configurations.
  • For more information about writing custom tasks or Grunt plugins, check out the developer documentation.
  • gruntのインストール方法はGruntとgrunt-cliの開発版、リリース版を指定してのインストールについて詳細情報が記載されています。
  • タスクの設定では外部データのインポート、globパターン、テンプレートの説明、Gruntfile内部のオプションやファイル、ターゲット、タスクの設定などの詳細な説明が記載されています。
  • タスクの作り方はGruntタスクの種類の違いと、サンプルタスクの数や設定を記載しています。
  • カスタムタスクの書き方やGruntプラグインについての情報は開発者ドキュメントをチェックしてください。

Found an error in the documentation? File an issue.

このドキュメントに間違いを見つけた? issueを送ってください