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

Publication

Category

Recent Post

2013. 1. 24. 21:57 NodeJS

Node.js 기반하에 Front-end 개발을 할 경우 텍스트 기반의 툴들을 알아보자.

  - Node.js로 개발할 때 commmand-line 유틸리티가 상당히 많고 이는 front-end 개발자에게 도움을 준다 

  - 다섯가지의 Node CLI 유틸리티를 알아보자 

  - Node와 npm이 설치되어 있음을 전제로 한다 



1) UglifyJS

  - JavaScript를 압축하고 사이즈를 최소화해준다 (네트워크 전송량을 작게해서 성능향상을 기대할 수 있다) 

  - UglifyJS의 기능을 바로 웹상에서 사용하기   

- 설치하기 

D:\Development>npm install -g uglify-js

npm http GET https://registry.npmjs.org/uglify-js


- 명령어

uglifyjs -b -o <output file> <input file>


-b 옵션 : beautifies

D:\Development>uglifyjs -b -o d:\development\if_uglify.js d:\development\if.js

D:\Development>uglifyjs -o d:\development\if_uglify.js d:\development\if.js

// coffee에서 컴파일된 javascript 소스 
// Generated by CoffeeScript 1.4.0
(function() {
  var x;

  x = 4;

  if ((0 <= x && x <= 10)) {
    console.log("true");
  }

}).call(this);

// -b 옵션을 주었을 경우 
(function() {
    var x;
    x = 4;
    if (0 <= x && x <= 10) {
        console.log("true");
    }
}).call(this);

// -b 옵션을 주지 않았을 경우 
(function(){var x;x=4;if(0<=x&&x<=10){console.log("true")}}).call(this);



2) Grunt

  - JavaScript 프로젝트를 위한 task-based command line 빌드 툴

  - 미리 정의된 템플릿을 만들어 준다 : 테스트(QUnit & PhantomJS), Lint파일(JSHint), 최소화파일(UglifyJS), Static WebServer

  - 템플릿들은 Node Server에서 구동할 수 있다. (jQuery 템플릿도 가능)

  - 시작하기 가이드

  - Grunt 간단 소개

  - 좀 더 자세한 튜토리얼

- 설치하기 : 상당히 많은 모듈을 함께 설치한다

D:\Development>npm install -g grunt

... 중략 ...

grunt

├── dateformat@1.0.2-1.2.3

├── colors@0.6.0-1

├── semver@1.0.14

├── async@0.1.22

├── hooker@0.2.3

├── underscore@1.2.4

├── underscore.string@2.1.1

├── uglify-js@1.3.4

├── nopt@1.0.10 (abbrev@1.0.4)

├── gzip-js@0.3.1 (crc32@0.2.2, deflate-js@0.2.2)

├── temporary@0.0.5 (package@1.0.1)

├── glob-whatev@0.1.8 (minimatch@0.2.9)

├── connect@2.4.6 (fresh@0.1.0, cookie@0.0.4, pause@0.0.1, bytes@0.1.0, crc@0.2.0, debug@0.7.0, formidable@1.0.11, qs@0.5.1, send@0.0.4)

├── prompt@0.1.12 (pkginfo@0.3.0, winston@0.5.11)

├── jshint@0.9.1 (minimatch@0.0.5, cli@0.4.3)

└── nodeunit@0.7.4 (tap@0.4.0)


- jquery 템플릿 만들어보기

// 신규 디렉토리를 만듦

D:\Development\grunt>mkdir jquery

// 디렉토리 이동

D:\Development\grunt>cd jquery

// 명령 수행 

D:\Development\grunt\jquery>grunt init:jquery

Running "init:jquery" (init) task

This task will create one or more files in the current directory, based on the environment and the answers to a few questions. Note that answering "?" to any question will show question-specific help and answering "none" to most question


will leave its value blank.


"jquery" template notes:

Project name should not contain "jquery" or "js" and should be a unique ID not already in use at plugins.jquery.com. Project title should be a human-readable title, and doesn't need to contain the word "jQuery", although it may. For

example, a plugin titled "Awesome jQuery Plugin" might have the name "awesome-plugin". For more information please see the documentation at https://github.com/jquery/plugins.jquery.com/blob/master/docs/manifest.md


// 질문에 값을 입력한다 

Please answer the following:

[?] Project name jQueryTest

[?] Project title (jQuerytest) DoWonQuery

[?] Description (The best jQuery plugin ever.)

[?] Version (0.1.0)

[?] Project git repository (git://github.com/UserXP/jQueryTest.git)

[?] Project homepage (https://github.com/UserXP/jQueryTest)

[?] Project issues tracker (https://github.com/UserXP/jQueryTest/issues)

[?] Licenses (MIT)

[?] Author name (none)

[?] Author email (none)

[?] Author url (none)

[?] Required jQuery version (*)

[?] Do you need to make any changes to the above before continuing? (y/N)


Writing CONTRIBUTING.md...OK

Writing grunt.js...OK

Writing libs/jquery/jquery.js...OK

Writing libs/jquery-loader.js...OK

Writing libs/qunit/qunit.css...OK

Writing libs/qunit/qunit.js...OK

Writing README.md...OK

Writing src/jQueryTest.js...OK

Writing test/jQueryTest.html...OK

Writing test/jQueryTest_test.js...OK

Writing LICENSE-MIT...OK


Initialized from template "jquery".

Done, without errors.

// 필요한 라이브러리와 grunt.js 환경파일이 자동 생성된다 

D:\Development\grunt\jquery>dir

2013-01-25  오후 05:32    <DIR>          .

2013-01-25  오후 05:32    <DIR>          ..

2013-01-25  오후 05:32             2,091 CONTRIBUTING.md

2013-01-25  오후 05:32             1,547 grunt.js

2013-01-25  오후 05:32               551 jQueryTest.jquery.json

2013-01-25  오후 05:32    <DIR>          libs

2013-01-25  오후 05:32             1,066 LICENSE-MIT

2013-01-25  오후 05:32               199 package.json

2013-01-25  오후 05:32               604 README.md

2013-01-25  오후 05:32    <DIR>          src

2013-01-25  오후 05:32    <DIR>          test

               6개 파일               6,058 바이트

               5개 디렉터리  37,356,339,200 바이트 남음



3) GruntIcon

  - css icon 만들기

  - PhantomJS가 필요하다 (phantomjs.exe 파일을 프로젝트 폴더에 놓는다)

  - grunt.js 파일에 GruntIcon 로드 설정을 한다

- 설치

D:\Development\grunt\jquery>npm install grunt-grunticon

npm http GET https://registry.npmjs.org/grunt-grunticon

... 중략 ...

grunt-grunticon@0.1.4 node_modules\grunt-grunticon

└── grunt@0.3.17 (dateformat@1.0.2-1.2.3, colors@0.6.0-1, semver@1.0.14, asyn

c@0.1.22, hooker@0.2.3, underscore@1.2.4, underscore.string@2.1.1, uglify-js@1.3

.4, nopt@1.0.10, gzip-js@0.3.1, temporary@0.0.5, glob-whatev@0.1.8, connect@2.4.

6, jshint@0.9.1, prompt@0.1.12, nodeunit@0.7.4)


- grunt.js 파일 설정 넣기 

/*global module:false*/

module.exports = function(grunt) {


  // Project configuration.

  grunt.initConfig({

    pkg: '<json:jQueryTest.jquery.json>',

    meta: {

      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +

        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +

        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +

        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +

        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'

    },

    concat: {

      dist: {

        src: ['<banner:meta.banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'],

        dest: 'dist/<%= pkg.name %>.js'

      }

    },

    min: {

      dist: {

        src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],

        dest: 'dist/<%= pkg.name %>.min.js'

      }

    },

    qunit: {

      files: ['test/**/*.html']

    },

    lint: {

      files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']

    },

    watch: {

      files: '<config:lint.files>',

      tasks: 'lint qunit'

    },

    jshint: {

      options: {

        curly: true,

        eqeqeq: true,

        immed: true,

        latedef: true,

        newcap: true,

        noarg: true,

        sub: true,

        undef: true,

        boss: true,

        eqnull: true,

        browser: true

      },

      globals: {

        jQuery: true

      }

    },

    uglify: {},

    grunticon: {

      src: "src/icons-source/",

      dest: "src/icons-output/"

    }

  });


  // Default task.

  grunt.registerTask('default', 'lint qunit concat min');

  grunt.loadNpmTasks('grunt-grunticon');

};


- grunticon 생성 (윈도우: grunt.cmd, 리눅스 : grunt )
D:\Development\grunt\jquery>grunt.cmd grunticon
Running "grunticon" task
Look, it's a grunticon!

grunticon now minifying the stylesheet loader source.
grunticon loader file created.
grunticon now spawning phantomjs...
Done, without errors.

// grunt.js에 환경설정한 icon-output이 생성된다 



4) JSHint

  - JavaScript의 코드 품질 측정 툴 

  - 잠재적인 위험 요소를 찾아준다 : 웹기반 측정도 가능

- 설치

D:\Development\grunt\jquery>npm install -g jshint

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

npm http 304 https://registry.npmjs.org/jshint

npm http GET https://registry.npmjs.org/cli/0.4.3

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

npm http 304 https://registry.npmjs.org/cli/0.4.3

npm http 304 https://registry.npmjs.org/minimatch

npm http GET https://registry.npmjs.org/lru-cache

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

npm http 304 https://registry.npmjs.org/lru-cache

npm http 304 https://registry.npmjs.org/glob

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

npm http GET https://registry.npmjs.org/graceful-fs

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

npm http 304 https://registry.npmjs.org/graceful-fs

npm http 304 https://registry.npmjs.org/inherits

npm http 304 https://registry.npmjs.org/minimatch

npm http GET https://registry.npmjs.org/lru-cache

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

npm http 304 https://registry.npmjs.org/sigmund

npm http 304 https://registry.npmjs.org/lru-cache

C:\Documents and Settings\UserXP\Application Data\npm\jshint -> C:\Documents and

 Settings\UserXP\Application Data\npm\node_modules\jshint\bin\hint

jshint@0.9.1 C:\Documents and Settings\UserXP\Application Data\npm\node_modules\

jshint

├── minimatch@0.0.5 (lru-cache@1.0.6)

└── cli@0.4.3 (glob@3.1.17)

 

- 수행 : jshint <file to check>

D:\Development>jshint loop.js

loop.js: line 15, col 2, Mixed spaces and tabs.


1 error



5) Node-static

  - 로컬 테스트시에 캐쉬/헤더 별도 셋팅가능

  - 로컬 웹서버로서 아무 디렉토리에서나 시작하면 ROOT 디렉토리가 된다

- 설치

D:\Development>npm install -g node-static

npm http GET https://registry.npmjs.org/node-static

npm http 200 https://registry.npmjs.org/node-static

npm http GET https://registry.npmjs.org/node-static/-/node-static-0.6.7.tgz

npm http 200 https://registry.npmjs.org/node-static/-/node-static-0.6.7.tgz

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

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

npm http 304 https://registry.npmjs.org/colors

npm http 304 https://registry.npmjs.org/optimist

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

npm http 304 https://registry.npmjs.org/wordwrap

C:\Documents and Settings\UserXP\Application Data\npm\static -> C:\Documents and

 Settings\UserXP\Application Data\npm\node_modules\node-static\bin\cli.js

node-static@0.6.7 C:\Documents and Settings\UserXP\Application Data\npm\node_mod

ules\node-static

├── colors@0.6.0-1

└── optimist@0.3.5 (wordwrap@0.0.2)


- 수행 : 아무 디렉토리나 가서 수행 -> 브라우져에서 호출한다 

D:\Development>static

serving "." at http://127.0.0.1:8080


- 또는 8080이 사용중이라면 옵션을 준다 

static -p <port>  <directory> 


* CLI를 이용하여 브라우져안에서 클라이언트단 유닛 테스트 도구 : bunyip


<참조> 

'NodeJS' 카테고리의 다른 글

[Node.js] 라이언 일병 이야기 이해하기  (0) 2012.12.08
[Node.js] 역사와 기초  (0) 2012.12.08
[Node.js] 시작하기  (1) 2012.10.30
posted by 윤영식