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

Publication

Category

Recent Post

2013. 1. 31. 10:08 Dev Environment/Build System

Grunt의 API를 사용하여 Task를 만들어 보자. Grunt의 Task가 핵심으로 한개를 수행하거나 여러개를 동시에 수행할 수도  있다. 


1) Task 별칭 등록하기 

  - grunt.registerTask 로 Task의 별칭을 지정한다

    + api : grunt.registerTask(taskName, taskList)

    + 예 : task.registerTask('default', 'lint qunit concat min'); 

    + grunt 수행시 특정 task를 지정하지 않으면 자동으로 default 별칭의 task가 수행된다 


2) Function Task 만들기

  - grunt.regiterTask 로 Task를 신규로 만들 수 있다

    + api : grunt.registerTask(taskName, description, taskFunction)

    + description, taskFunction을 파라미터로 넘기면 새로운 task 등록됨 

    + fail이 나면 return false 를 해야 한다 

//////////////////////////////////////////////
// grunt.js 환경파일에 등록한다 
  grunt.registerTask('dowon', 'A sample task that logs stuff.', function(arg1, arg2) {
    if (arguments.length === 0) {
      grunt.log.writeln(this.name + ", no args");
    } else {
      grunt.log.writeln(this.name + ", " + arg1 + " " + arg2);
    }
  });

//////////////////////////////////////////////
// 결과
// 아규먼트 없을 때
D:\Development\testing_grunt>grunt.cmd dowon
Running "dowon" task
dowon, no args
Done, without errors.

// 아규먼트 전달 : 이용 
D:\Development\testing_grunt>grunt.cmd dowon:hello:youngsik
Running "dowon:hello:youngsik" (dowon) task
dowon, hello youngsik
Done, without errors.


3) Multi Task 만들기 

  - grunt.registerMultiTask 를 이용하여 만든다

    + api : grunt.registerMultiTask(taskName, description, taskFunction)

    + lint, concat, min task등이 multi task이다 

    + sub-properties (별칭 targets) 이 내부적으로 task가 된다

    + multi task에서는 function에서 특별히 this 키워드를 사용하여 접근한다 

  - grunt.initConfig 안에 target을 만든다 객체명칭 = multi task의 대표 명칭이다 

    + 하기 예제에서 logstuff 가 multi task의 대표명칭이다 

    + grunt.registerMultiTask의 첫번째 아규먼트인 multi task 명칭을 logstuff 로 일치시킨다 

    + 등록한 function에서 this 함에 주의*

//////////////////////////////////////////////
/*global config:true, task:true*/
grunt.initConfig({
  logstuff: {
    foo: [1, 2, 3],
    bar: 'hello world',
    baz: false
  }
});

grunt.registerMultiTask('logstuff', 'This task logs stuff.', function() {
  // this.target === the name of the target
  // this.data === the target's value in the config object
  // this.name === the task name
  // this.args === an array of args specified after the target on the command-line
  // this.flags === a map of flags specified after the target on the command-line
  // this.file === file-specific .src and .dest properties

  // Log some stuff.
  grunt.log.writeln(this.target + ': ' + this.data);

  // If data was falsy, abort!!
  if (!this.data) { return false; }
  grunt.log.writeln('Logging stuff succeeded.');
});

//////////////////////////////////////////////
// 결과
// target을 지정하지 않았을 때는 전체 target이 수행
D:\Development\testing_grunt>grunt.cmd logstuff
Running "logstuff:foo" (logstuff) task
foo: 1,2,3
Logging stuff succeeded.

Running "logstuff:bar" (logstuff) task
bar: hello world
Logging stuff succeeded.

Running "logstuff:baz" (logstuff) task
baz: false
 Task "logstuff:baz" failed. Use --force to continue. 

Aborted due to warnings.

// foo target을 지정
D:\Development\testing_grunt>grunt.cmd logstuff:foo
Running "logstuff:foo" (logstuff) task
foo: 1,2,3
Logging stuff succeeded.

Done, without errors.

// bar target을 지정 
D:\Development\testing_grunt>grunt.cmd logstuff:bar
Running "logstuff:bar" (logstuff) task
bar: hello world
Logging stuff succeeded.

Done, without errors.

// baz target에서 false return하면서 warning 발생함 
D:\Development\testing_grunt>grunt.cmd logstuff:baz
Running "logstuff:baz" (logstuff) task
baz: false
 Task "logstuff:baz" failed. Use --force to continue. 

Aborted due to warnings.


4) Init Task 만들기 

  - api : grunt.registerInitTask(taskName, description, taskFunction)

    +최초에 수행되는 init task를 수행하고 별도의 환경 설정 데이터도 필요없다 


5) Task명칭 바꾸기 

  - api : grunt.renameTask(oldname, newname)



6) Inside Tasks 알아보기 

  - grunt의 this 에는 여러 유용한 properties 와 method를 가지고 있다. grunt.task.current 로 expose 한다 

  - Task에서 구현하는 function에서 사용한다 

  - this.async / grunt.task.current.async

    + task를 비동직적으로 수행시켜 준다 

//////////////////////////////////////////////
// Tell grunt this task is asynchronous.
var done = this.async();
// Your async code.
setTimeout(function() {
  // Let's simulate an error, sometimes.
  var success = Math.random() > 0.5;
  // All done!
  done(success);
}, 1000);


  - this.requires / grunt.task.current.requires : 의존관계있는 task를 열거

  - this.requiresConfig / grunt.task.current.requiresConfig : config properties 열거 

  - this.name / grunt.task.current.name : 등록된 task 명칭 

  - this.nameArgs / grunt.task.current.nameArgs : grunt뒤의 아규먼트들 예) grunt.cmd task1:foo  -> task1:foo 

  - this.args / grunt.task.current.args : task명칭을 뺀 실제 아규먼트값을 배열로 리턴

  - this.flags / grunt.task.current.flags : 아규먼트를 만들어준다 

  - this.errorCount / grunt.task.current.errorCount : task에서 발생한 에러건수 


7) Indside Multi Tasks 알아보기 

  - this.target / grunt.task.current.target : multi task에서만 사용. config data로 등록된 key (name) 값 

  - this.data / grunt.task.current.data : multi task에서만 사용. config data로 등록된 value 값

  - this.file / grunt.task.current.file : compact format 사용시 this.file.src , this.file.dest 가 만들어진다 (template api 참조)



8) 외부에서 정의된 Task 로딩하기 

  - 큰 프로젝트에서 sub 프로젝트끼리 공유하기 위하여 task와 helper 들을 만든다 

  - 여러 디렉토리에서 task를 로딩하거나 또는 Npm-installed grunt plugin 을 로딩한다 

  - task 관련 파일들 로딩하기 

    + api : grunt.loadTasks(tasksPath)

  - task와 helper 로딩하기 

    + api : grunt.loadNpmTasks(pluginName)

  - npm module 호출 

    + api : grunt.npmTasks(npmModuleName)



9) Helper 정의하고 실행하기 

  - 이미 만들어지 helper들 존재 (참조)

  - helper 만들기 

    + api : grunt.registerHelper(helperName, helperFunction)

//////////////////////////////////////////////
grunt.registerHelper('add_two_nums', function(a, b) {
  return a + b;
});

  - helper 이름 바꾸기 

    + api : grunt.renameHelper(oldname, newname)


  - helper 호출하기 

    + api : grunt .helper(helperName, [, agruments...])



10) Warning 과 Fatal Error

  - api 호출하여 화면에 출력 한다 

  - grunt.warn(error [, errorCode])

  - grunt.fatal(error [, errorCode])



<참조>

  - Grunt API

posted by 윤영식