블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2013. 2. 2. 17:22 Dev Environment/Sublime Text

Syntax에 대한 highlight 기능을 위하여 Jade와 Stylus 플로그인을 설치한다 


1) Sublime Text의 Package 디렉토리로 이동

  - 위치 : Sublime Text의 메뉴에서 Preferences > Browse Packages... 선택하면 이동한다 

  - 해당 위치에서 플러그인을 설치한다 



2) Jade 플로그인 설치 

$ git clone https://github.com/miksago/jade-tmbundle.git Jade

Cloning into 'Jade'...

remote: Counting objects: 139, done.

remote: Compressing objects: 100% (71/71), done.

remote: Total 139 (delta 59), reused 120 (delta 44)

Receiving objects: 100% (139/139), 18.63 KiB, done.

Resolving deltas: 100% (59/59), done.


  - Jade 확장자 파일을 연다 

  - ctr+shift+p 에서 jade라고 타입핑하고 'Set Syntax: Jade' 선택하면 highlighting 된다 

  



3) Stylus 플러그인 설치 

$ git clone https://github.com/LearnBoost/stylus.git Stylus

Cloning into 'Stylus'...

remote: Counting objects: 15849, done.

remote: Compressing objects: 100% (5401/5401), done.

remote: Total 15849 (delta 10322), reused 15R609 (delta 10117)eceiving objects

Receiving objects: 100% (15849/15849), 2.36 MiB | 121 KiB/s, done.

Resolving deltas: 100% (10322/10322), done.

Checking out files: 100% (658/658), done.


  - styl 확장자 파일을 연다 

  - ctr+shift+p 에서 stylus라고 타입핑하고 'Set Syntax: Stylus' 선택하면 highlighting 된다 

  


<참조>

  - 원문 : http://stackoverflow.com/questions/7666977/syntax-highlighting-for-jade-in-sublime-text-2

posted by 윤영식
2013. 1. 31. 16:34 NodeJS/Concept

Node.js 에서 Express를 사용하면서 일관된 축약 언어 컴파일러로 JavaScript 코딩은 CoffeeScript를 사용하고, HTML은 Jade를 사용하고 CSS는 Stylus를 사용할 때 가장 기본적인 뼈대가 되는 코드를 만들어 주는 프레임워크 Cham을 알아보자. 


1) Cham 설치하기 

  - Node.js 와 NPM, CoffeeScript는 기본 설치되어 있어야 한다 

  - git clone 으로 설치하기 

$ git clone https://github.com/conancat/cham.git

Cloning into 'cham'...

remote: Counting objects: 155, done.

remote: Compressing objects: 100% (103/103), done.

remote: Total 155 (delta 48), reused 142 (delta 35)

Receiving objects: 100% (155/155), 136.89 KiB | 59 KiB/s, done.

Resolving deltas: 100% (48/48), done.


  - Express, jade, stylus 설치하기 

  - 설치후 브라우져 호출 : http://localhost:3000/ 

//////////////////////////////////////

// 설치 

$ cd cham

$ npm install express

npm http GET https://registry.npmjs.org/express/2.4.3

npm http 200 https://registry.npmjs.org/express/2.4.3

... 중략 ...

npm http 200 https://registry.npmjs.org/formidable

express@2.4.3 node_modules\express

├── mime@1.2.9

├── qs@0.5.3

└── connect@1.9.2 (formidable@1.0.11)


$ npm install jade

npm http GET https://registry.npmjs.org/jade

... 중략 ...

npm http 200 https://registry.npmjs.org/commander/-/commander-0.6.1.tgz

jade@0.28.1 node_modules\jade

├── commander@0.6.1

├── mkdirp@0.3.4

└── coffee-script@1.4.0


$ npm install stylus -g

npm http GET https://registry.npmjs.org/stylus

... 중략 ...

C:\Users\yuwonsystem01\AppData\Roaming\npm\stylus -> C:\Users\yuwonsystem01\AppD

ata\Roaming\npm\node_modules\stylus\bin\stylus

stylus@0.32.0 C:\Users\yuwonsystem01\AppData\Roaming\npm\node_modules\stylus

├── debug@0.7.0

├── mkdirp@0.3.4

└── cssom@0.2.5


$ npm install vows

npm http GET https://registry.npmjs.org/vows

npm http 200 https://registry.npmjs.org/vows

npm http GET https://registry.npmjs.org/vows/-/vows-0.7.0.tgz

... 중략 ...

npm http 200 https://registry.npmjs.org/diff/-/diff-1.0.4.tgz

vows@0.7.0 node_modules\vows

├── eyes@0.1.8

└── diff@1.0.4


///////////////////////////////////

// 실행하기 

$ node app

Express server listening on port 3000 in development mode



2) 구조파악하기 

  - root 폴더에 CakeFile이 존재하여 cake를 수행할 수 있다. (CoffeeScript 형태로 작성)

/////////////////////////////////////

// cake를 실행하면 사용법이 출력됨 

D:\git-nulpulum\cham>cake

Cakefile defines the following tasks:


cake watch             # Watches all Coffeescript(JS) and Stylus(CSS) files

cake watchJS         # Watches all coffeescript files for changes

cake watchCSS      # Watches all CSS files for changes

cake compileJS       # Compiles all Coffeescript files into JS

cake test                # Runs all tests

cake docs              # Create documentation using Docco


//////////////////////////////////////////////

// watch 하고 있는 원본 소스들을 볼 수 있다

// 원본 소스는 전부 src에 위치함

D:\git-nulpulum\cham>cake watch

15:10:11 - compiled src\lib\helpers.coffee

15:10:11 - compiled src\lib\module.coffee

15:10:11 - compiled src\lib\conf.coffee

15:10:11 - compiled src\test\testHelpers.coffee

15:10:11 - compiled src\public\js\plugins.coffee

15:10:11 - compiled src\app.coffee

15:10:11 - compiled src\test\example.test.coffee

15:10:11 - compiled src\lib\routes.coffee

15:10:11 - compiled src\public\js\script.coffee

  watching C:\Users\yuwonsystem01\AppData\Roaming\npm\node_modules\stylus\lib\functions\index.styl

  watching src\public\css\conf\base.styl

  watching src\public\css\conf\helpers.styl

  watching src\public\css\conf\colors.styl

  watching src\public\css\elems\reset.styl

  watching src\public\css\elems\helpers.styl

  watching src\public\css\elems\typography.styl

  watching src\public\css\elems\common.styl

  watching src\public\css\pages\layout.styl

  watching src\public\css\pages\index.styl

  watching src\public\css\media\media.styl

  compiled public\css\style.css

  watching src\public\css\style.styl

15:15:16 - compiled src\app.coffee       <== app.coffee 를 열어서 살짝 수정하였더니 자동으로 재컴파일 됨 


  - 의존관계 파악을 위해 package.json 파일을 열어보자 

{

  "name": "cham",

  "version": "0.0.1",

  "private": true,

  "dependencies": {

    "express": "2.4.3",

    "jade": ">= 0.0.1"

  },

  "devDependencies": {

    "vows": ">= 0.5.9",     // BDD 테스트

    "stylus": ">= 0.13.9",  // CSS

    "coffee-script": ">= 1.1.2" // Javascript 

  },

  "engines": {

    "node": "*"

  },

  "author": "Grey Ang <conancat@gmail.com> (http://grey-ang.com)",

  "description": "Boilerplate for quick Coffeescript driven app, backed by Jade and Stylus",

  "repository": {

    "type": "git",

    "url": "git://github.com/conancat/cham.git"

  },

  "scripts": {

    "test": "cake test"

  }

}


  - CoffeeScript 문법의 CakeFile : "task <명칭>, <설명>, -> 펑션"  task 다음에 3개의 아규먼트로 cake task 만듦

    + watchJS 명령 : coffee -cw -o ./ src/

    + watchCSS 명령 : stylus --watch --include ./public --out ./public/css ./src/public/css

    + compileJS 명령 : coffee -c -o ./ src/

    + test 명령 : vows test/*.test.js

    + docs 명령

       docco src/*.coffee

       docco src/lib/*.coffee

       docco src/test/*.coffee 

//////////////////////////////////////////
// CakeFile 내역 
# Module requires
{spawn, exec} = require 'child_process'
sys = require 'sys'

# ## Helpers

# Helper function for showing error messages if anyting happens
printOutput = (process) ->
  process.stdout.on 'data', (data) -> sys.print data
  process.stderr.on 'data', (data) -> sys.print data
  
# Watch Javascript for changes
watchJS = ->
  coffee = exec 'coffee -cw -o ./ src/'
  printOutput(coffee)

# Watch CSS for changes
watchCSS = ->
  
  # Without Nib
  stylus = exec 'stylus --watch --include ./public --out ./public/css ./src/public/css'
  
  # Use this line instead if you're using Nib
  # stylus = exec 'stylus --watch --include ./public --use ./node_modules/nib/lib/nib.js --out ./public/css ./src/public/css'
  
  printOutput(stylus)
  
# ## Tasks
# I guess pretty self explainory? lol
task 'watch', 'Watches all Coffeescript(JS) and Stylus(CSS) files', ->
  watchJS()
  watchCSS()

task 'watchJS', 'Watches all coffeescript files for changes', ->
  watchJS()
  
task 'watchCSS', 'Watches all CSS files for changes', ->
  watchCSS()
  
task 'compileJS', 'Compiles all Coffeescript files into JS', ->
 coffee = exec "coffee -c -o ./ src/"
 printOutput(coffee)
  
task 'test', 'Runs all tests', ->
  vows = exec 'vows test/*.test.js'
  printOutput(vows)
  
task 'docs', 'Create documentation using Docco', ->
  docco = exec """
    docco src/*.coffee
    docco src/lib/*.coffee
    docco src/test/*.coffee
  """
  printOutput(docco)



3) 사용한 모듈들 알아보기

  - Stylus

    + CSS를 축약해서 표현, 사용이 간단하고, 코드가 간결해짐 

    + ; 과 { } 를 사용할 필요가 없고  DRY (Don't Repeat Yourself) 지원


  - Docco

    + 주석을 MarkDown 으로 줄 수 있다 (GitHub README.md 만들기와 일관성 있어 좋군)

    + 수행한 위치 바로 밑에 docs 폴더에 위치함 

    + 설치 : npm install -g docco

    + 수행 : docco src/*.coffee


  - Jade

    + HTML 템플릿 엔진 : 이것도 < > 사용이 필요없어 코드가 간결해짐

    + 사용 설명


  - Vows

    + 비동기 BDD for Node

//////////////////////////////////////////
// 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 

///////////////////////////////////////

// 결과 : 성공 

D:\git-nulpulum\cham>node vowtest.js

··· ✓ OK » 3 honored (0.036s)



  - Express

    + 설치 : npm install -g express

    + 수행 : $ express <projectName>

//////////////////////////////////////////
// Express로 Listen Server 구성
var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('Hello World');
});

app.listen(3000);


  - CoffeeScript

    + 설치 : npm install -g coffee-script

    + 실행 : coffee <파일명>.coffee    <== .coffee 확장자 생략가능   



<참조> 

  - https://github.com/conancat/cham

'NodeJS > Concept' 카테고리의 다른 글

[Node.js] Express의 Connect 살펴보기  (0) 2013.03.11
[Node.js] 기술 발전 방향 4단계  (0) 2013.02.16
[Node.js] 생태계에 대한 생각들  (0) 2012.12.23
[Jade] Jade 사용하기  (0) 2012.12.15
[EJS] 사용하기  (0) 2012.12.15
posted by 윤영식
2012. 12. 15. 15:31 NodeJS/Concept

Express 프레임워크에서 기본으로 사용하는 Jade에 대하여 알아보자. 



▶ app.js 연구 


1) 우선 require를 사용하여 모듈패턴에 의한 모듈을 얻는다. 모듈로 얻음으로 namespace가 분리되므로 서로간의 충돌을 방지 할 수 있다. 물론 접근은 module.<exports Name> 으로 접근한다 

var express = require('express')

  , routes = require('./routes')             // index.js 파일 

  , user = require('./routes/user')        // user.js 파일 

  , dowon = require('./routes/dowon') // dowon.js 파일 

  , http = require('http')

  , path = require('path');


2) ./routes/dowon 으로 require 했으므로 routes 디렉토리 밑에 dowon.js 파일을 생성한다. hi 라는 펑션을 exports 객체에 설정하여 모든 인스턴스가 공유할 수 있게 한다. 물론 모듈안에서 공유가 된다. 단, function(req, res) {...} 로 구현하자. 

exports.hi = function(req, res){  // dowon 모듈에서 hi 펑션 공유 

  res.render('dowon', { title: 'Hi DoWon', name: 'youngsik', age: '30' }); // dowon.jade 지정 

};


3) res.render('dowon', ...) 설정에서 dowon이라고 key를 넣었으므로 views 폴더 밑에 dowon.jade 파일을 생성한다. jade syntax에 맞추어 코딩을 하고 값은 #{key} 형식으로 코딩하면 json에서 값을 읽어 자동 셋팅하고, html 파일로 변환된다 

- var dododo = function() { return 'dododo young!'; };


p #{title}


p hi dowon yun


p

  | hi

  | dowon

  | yun


p.

  hi

  dowon

  yun


// error

p

  hi

  dowon

  yun  


 ul

   li one

   li two

   li #{name}

   li #{age}

   li= dododo()


// each loop

//-

- var users=[{ title: 'Hi DoWon1', name: 'youngsik1', age: '30' }, {title: 'Hi DoWon2', name: 'youngsik2', age: '40' }, { title: 'Hi DoWon3', name: 'youngsik3', age: '50' }];


 ul

     each user in users

        li= user.title

        li= user.name

        li= user.age



4) app.js 에서 get 요청에 대하여 서비스 되는 모듈의 exports 펑션을 지정한다. 즉, /dowon uri가 호출되면 hi 펑션이 수행함

app.get('/', routes.index);

app.get('/users', user.list);

app.get("/dowon", dowon.hi);


Node의 require(<js 파일>) 호출을 통하여 모듈을 로딩하고, 모듈로 로딩된 js 파일안에 모듈에서 공유할 펑션을 정의하였다. 해당 펑션에는 jade 파일명을 지정하여 서비스 한다. 결국, Node의 require, exports Global객체를 적절히 사용하여 구성하였다. 하기와 같은 과정을 거치는 것이다



Route → Route Handler → Template → HTML


  • Route : dowon.js
  • Route Handler : hi에 지정한 function
  • Template : dowon.jade
  • HTML : jade에 의하여 html로 변환 


<참조>

  - ninja-express

  - Jade syntax 배우기 (필독)

  - Jade code : 동영상 (필감)


posted by 윤영식
prev 1 next