Gruntfile.js を書くために必要な JavaScript 文法のおさらい
は、以下のように表記する
文字列'hello'
または "hello"
数値1
とか 2
とか
論理値true
または false
配列の表し方
[値1, 値2, ...]
定義
var array = ['hello', 'bye'];
アクセス
console.log(array[0]);
console.log(array[1]);
オブジェクトの表し方
{名前1 : 値1, 名前2 : 値2, ...}
定義
var obj = {
name1: 'value1', // 文字列
name2: 2, // 数値
name3: false, // bool
name4: ['e1', 'e2'], // 配列
name5: { // オブジェクト
name6: 'aaa',
name7: 123
},
name7: function () { // ファンクション
console.log('hello');
}
};
アクセス
console.log(obj.name1);
書けそうな所にはどこでも書けてしまうのが JavaScript の関数の特徴
定義
function hello(name) {
console.log('Hello, ' + name);
}
実行
hello('world');
関数も変数に代入できる
var f1 = hello;
代入した変数名で実行
f1('world');
名前のない関数を変数に代入
var bye = function(name) {
console.log('Bye, ' + name);
};
実行
bye('world');
定義
function greet(name, g1, g2) {
g1(name);
g2(name);
}
実行
greet('world', hello, bye);
greet('world', bye, bye);
定義
var greetings = {
hello: function(name) {
console.log('Hello, ' + name);
},
bye: function(name) {
console.log('Bye, ' + name);
}
};
実行
greetings.hello('world');
greetings.bye('world');
module.exports
に代入したオブジェクトや関数は、外部のスクリプトから require()
経由で利用できるGruntfile.js の定義
module.exports = function(grunt) {
grunt.registerTask('hello', function(){
console.log('Hello, world!');
});
};
node で以下を実行してみる
// Gruntfile.js に定義した関数を gruntfile 変数に代入
var gruntfile = require('./Gruntfile.js');
// grunt も module.exports で公開されているため取得できる
var grunt = require('grunt');
// Gruntfile.js に定義した関数を実行
gruntfile(grunt);
// 以下を実行すると hello タスクが実行される
grunt.task.run('hello');
grunt.task.start();