-b, --bare compile without a top-level function wrapper
-m, --minify minify output files
-o, --output <path> output path
-s, --silent suppress console output
-w, --watch watch files for changes
- 컴파일 하기
$ coffeebar test.coffee
- 소스 디렉토리(src)를 지정하여 컴파일 디렉토리(lib) 지정하기
$ coffeebar src -o lib
- 소스 디렉토리(src)를 지정하여 하나의 파일로 합치기
$ coffeebar src -o joined.js
- 소스 디렉토리(src)를 지정하여 컴파일 디렉토리(lib) 지정하고 .coffee 소스 파일 변경되면 자동 컴파일하기
$ coffeebar src -o lib -w
3) API 사용법
- coffeebar(inputPaths, [options]) : inputPaths에 소스 디렉토리 지정하면 options에 따라 수행을 결정한다
- 옵션들
bare - (boolean) CoffeeScript compiler option which omits the top-level function wrapper if set to true.
minify - (boolean) Minify output files. Defaults to false.
output - (string) The path to the output file. If the path has a file extension, all files will be joined at that location. Otherwise, the path is assumed to be a directory.
silent - (boolean) Suppress all console output. Defaults to true.
watch - (boolean) Watch all files and directories for changes and recompile automatically. Defaults to false.
Node.js 에서 Express를 사용하면서 일관된 축약 언어 컴파일러로 JavaScript 코딩은 CoffeeScript를 사용하고, HTML은 Jade를 사용하고 CSS는 Stylus를 사용할 때 가장 기본적인 뼈대가 되는 코드를 만들어 주는 프레임워크 Cham을 알아보자.
//////////////////////////////////////////
// vowtest.js
var vows = require('vows'),
assert = require('assert');
// Create a Test Suite
vows.describe('Division by Zero').addBatch({
'when dividing a number by zero': {
topic: function () { return 42 / 0 },
'we get Infinity': function (topic) {
assert.equal (topic, Infinity);
}
},
'but when dividing zero by zero': {
topic: function () { return 0 / 0 },
'we get a value which': {
'is not a number': function (topic) {
assert.isNaN (topic);
},
'is not equal to itself': function (topic) {
assert.notEqual (topic, topic);
}
}
}
}).run(); // Run it
Java 처럼 Class를 쉽게 만들어 보자. 클래스끼리 상속하여 재정의(overriding)하는 부분도 알아보자
1) Class 만들기
- class 로 표현한다
- 컴파일 내역에 IIFE(즉시실행함수)안에 다시 Dog을 생성하여 호출함
// clazz.coffee
class Dog
// 컴파일 내역 : clazz.js
// Generated by CoffeeScript 1.4.0
(function() {
var Dog;
Dog = (function() {
function Dog() {}
return Dog;
})();
}).call(this);
- constructor 로 생성자를 정의한다
- constructor를 사용하면 Dog 생성자가 생성되고 다른 프로퍼티는 prototype에 정의된다
// clazz2.coffee
class Dog
constructor: (@name) ->
growl: -> console.log '*growl*'
dog = new Dog 'Dowon'
console.log dog.name
dog.growl()
// 결과
D:\Development\coffeescript\4>coffee clazz2
Dowon
*growl*
// 컴파일 내역 : clazz2.js
// Generated by CoffeeScript 1.4.0
var Dog, dog;
Dog = (function() {
function Dog(name) {
this.name = name;
}
Dog.prototype.growl = function() {
return console.log('*growl*');
};
return Dog;
})();
dog = new Dog('Dowon');
console.log(dog.name);
dog.growl();
2) 상속 관계 만들기
- extends 사용하여 상속관계 정의 한다
- super() 사용하여 동일 메소드에 대한 재정의(Overriding)을 한다
// clazz3.coffee
class Dog
constructor: (@name) ->
growl: -> console.log '*growl*'
class BorderCollie extends Dog
constructor: (name, @tricks = []) ->
super name
perform: (trick) -> console.log if trick in @tricks then "#{@name} is #{trick}" else '*whine*'
growl: (person) ->
if person is @master
console.log '*bark*'
else
super() # Dog.growl()
dog = new Dog 'Dowon'
console.log dog.name
dog.growl()
dog2 = new BorderCollie 'YoungSik', ['playing', 'catching', 'rolling']
dog2.master = "Dowon"
console.log dog2.name
dog2.perform 'rolling'
dog2.growl("Dowon")
dog2.growl("Yun")
// 결과
D:\Development\coffeescript\4>coffee clazz3
Dowon
*growl*
YoungSik
YoungSik is rolling
*bark*
*growl*
- BorderCollie extends Dog 으로 상속 만들어 줌
- BorderCollie의 constructor안에 "super name" 을 호출하여 super(name)을 넣어 줌
- BorderCollie의 grow안에서 super() 를 호출하여 super.growl()을 넣어 줌
// 컴파일 내역 : clazz3.js
// Generated by CoffeeScript 1.4.0
(function() {
var BorderCollie, Dog, dog, dog2,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Dog = (function() {
function Dog(name) {
this.name = name;
}
Dog.prototype.growl = function() {
return console.log('*growl*');
};
return Dog;
})();
BorderCollie = (function(_super) {
__extends(BorderCollie, _super);
function BorderCollie(name, tricks) {
this.tricks = tricks != null ? tricks : [];
BorderCollie.__super__.constructor.call(this, name);
}
BorderCollie.prototype.perform = function(trick) {
return console.log(__indexOf.call(this.tricks, trick) >= 0 ? "" + this.name + " is " + trick : '*whine*');
};
BorderCollie.prototype.growl = function(person) {
if (person === this.master) {
return console.log('*bark*');
} else {
return BorderCollie.__super__.growl.call(this);
}
};
return BorderCollie;
})(Dog);
dog = new Dog('Dowon');
console.log(dog.name);
dog.growl();
dog2 = new BorderCollie('YoungSik', ['playing', 'catching', 'rolling']);
dog2.master = "Dowon";
console.log(dog2.name);
dog2.perform('rolling');
dog2.growl("Dowon");
dog2.growl("Yun");
}).call(this);
machine =
running: no
turnOn: -> this.running = yes
turnOff: -> this.running = no
###
if not === unless
###
if not machine.running
machine.turnOn()
machine.turnOne() if not machine.running
console.log machine.running
unless machine.running
machine.turnOn()
else
machine.turnOff()
// Generated by CoffeeScript 1.4.0
(function() {
var machine;
machine = {
running: false,
turnOn: function() {
return this.running = true;
},
turnOff: function() {
return this.running = false;
}
};
/*
if not === unless
*/
if (!machine.running) {
machine.turnOn();
}
if (!machine.running) {
machine.turnOne();
}
console.log(machine.running);
if (!machine.running) {
machine.turnOn();
} else {
machine.turnOff();
}
}).call(this);
// 결과 :9번째 줄과 12번째 줄은 같은 구문이다
D:\Development\coffeescript>coffee if2
true
- switch ~ then 구문 사용하기 : switch.coffee
person =
name: "dowon"
job: "programmer"
giveWork = (person) ->
switch person.job
when "programmer"
console.log "1> Here's your code work, #{person.name}"
when "designer"
console.log "1> Here's your design work, #{person.name}"
else
console.log "1> Um, do you work here?"
giveWork person
# or
person.job = "designer"
giveWork2 = (person) ->
switch person.job
when "programmer" then console.log "2> Here's your code work, #{person.name}"
when "designer" then console.log "2> Here's your design work, #{person.name}"
else console.log "2> Um, do you work here?"
giveWork2 person
// Generated by CoffeeScript 1.4.0
var giveWork, giveWork2, person;
person = {
name: "dowon",
job: "programmer"
};
giveWork = function(person) {
switch (person.job) {
case "programmer":
return console.log("1> Here's your code work, " + person.name);
case "designer":
return console.log("1> Here's your design work, " + person.name);
default:
return console.log("1> Um, do you work here?");
}
};
giveWork(person);
person.job = "designer";
giveWork2 = function(person) {
switch (person.job) {
case "programmer":
return console.log("2> Here's your code work, " + person.name);
case "designer":
return console.log("2> Here's your design work, " + person.name);
default:
return console.log("2> Um, do you work here?");
}
};
giveWork2(person);
###
Math.random()
###
rand = (max = 10, min = 0) -> Math.floor(Math.random() * (max - min + 1)) + min
console.log rand()
console.log rand 100
console.log rand 60, 50
// 결과 : 수행때 마다 틀린 random값이 지정 범위내에서 출력됨
D:\Development\coffeescript>coffee random
5
100
53
D:\Development\coffeescript>coffee random
1
32
53
3) 비교연산
- ===, !== 사용하기
- if 문 사용하기
- ===, !== 를 사용하는 대신 is, isnt 문장으로 사용하기 : operator.coffee
###
is ===
isnt !==
###
name = "dowon"
if name is "dowon"
console.log "great"
if name isnt "Dowon"
console.log "poor"
### if( !false ) ###
if not false
console.log "cool"
###
var name = "dowon",
job = "programmer";
if(name === "dowon" || job === "programmer") {
console.log("right")
}
###
name = "dowon"
job = "programmer"
if name is "dowon" and job is "programmer"
console.log "right"
// 결과
D:\Development\coffeescript>coffee operator
great
poor
cool
right
- ? 연산자를 통하여 null 체크 하기 : operator2.coffee
name = "dowon"
if name?
console.log "hi"
person =
name: "dowon"
job: "programmer"
console.log person?.name
name = name || "youngsik"
name ||= "youngsik"
name ?= "youngsik"
console.log name
// Generated by CoffeeScript 1.4.0
(function() {
var name, person;
name = "dowon";
if (name != null) {
console.log("hi");
}
person = {
name: "dowon",
job: "programmer"
};
console.log(person != null ? person.name : void 0);
name = name || "youngsik";
name || (name = "youngsik");
if (name == null) {
name = "youngsik";
}
console.log(name);
}).call(this);
// 결과
D:\Development\coffeescript>coffee operator2
hi
dowon
dowon
- if 문을 재구성한다 : if.coffee
# x = 4
# if( x >= 0 && x <= 10) {}
x = 4
if 0 <= x <= 10
console.log "true"
// Generated by CoffeeScript 1.4.0
(function() {
var x;
x = 4;
if ((0 <= x && x <= 10)) {
console.log("true");
}
}).call(this);
C:\Documents and Settings\UserXP\Application Data\npm\cake-> C:\Documents and Settings\UserXP\Application Data\npm\node_modules\coffee-script\bin\cake
C:\Documents and Settings\UserXP\Application Data\npm\coffee -> C:\Documents and Settings\UserXP\Application Data\npm\node_modules\coffee-script\bin\coffee
coffee-script@1.4.0 C:\Documents and Settings\UserXP\Application Data\npm\node_m
odules\coffee-script
D:\Development\javascript>coffee -v
CoffeeScript version 1.4.0
2. Coffee 사용하기
- 확장자 .coffee 파일을 만든다
- coffee 명령으로 수행할 수도 있고, js 파일로 컴파일 할 수도 있다
- 일반적인 js 코딩 : arr.js
function makeArray(dimension) {
var arr = [], i = 0, j = 0;
for(; i < dimension; i++) {
arr[i] = [];
for( j=0; j < dimension; j++) {
arr[i][j] = '1111';
}
}
return arr;
}
var myArr = makeArray(4);
console.log(myArr);
// 결과
D:\coffeescript>node arr
[ [ '1111', '1111', '1111', '1111' ],
[ '1111', '1111', '1111', '1111' ],
[ '1111', '1111', '1111', '1111' ],
[ '1111', '1111', '1111', '1111' ] ]
- CoffeeScript 코딩 방식 : arr.coffee (coffee 확장자)
makeArray = (dimension) ->
arr = []
for i in [0...dimension]
arr[i] = []
arr[i][j] = '1111' for j in [0...dimension]
arr
myArr = makeArray 4
console.log myArr
console.log 'dowon hi'