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

Publication

Category

Recent Post

2015. 10. 22. 10:41 AngularJS



본 서적은 자바스크립트와 앵귤러 프레임워크를 프로젝트에 도입해 보려는 개발자 또는 프로토타입을 해보고 싶은 개발자 또는 사용해 본 경험이 있는 개발자를 대상으로 한다. 앵귤러에 대해 처음 공부하는 분에게는 다소 어려울 수 있으므로 기초서적을 권장드린다. 책 제목처럼 3장이후 부터 실전 프로젝트 실습을 위한 상세 소스를 GitHub에서 제공한다. 1~2장은 개념 정리이므로 읽고 나중에 참조하는 장으로 사용한다. 참고로 2장은 실습이 없이 개념을 설명하는 장이기에 소스를 제공하지 않고 있다. (소스의 Git Branch는 장이 끝나는 시점에 언급하고 있다. 먼저 전체 소스를 보고 싶다면 GitHub 내용을 참조하자)








출판의 여정 


8개월의 원고작성, 3개월의 편집기간을 거쳐 드디어 책이 출간되었다. 책을 통해 개발자들과 공유하자는 의기투합은 2013년 겨울로 거슬러 올라간다. 이강훈님을 통해 알게된 이규원님, 김충섭님, 김대권님, 박유진님, 구교준님과 함께 MEAN 스택을 기획했었다. 그 당시 미국에 있었던 지라 구글 행아웃을 통해 주말마다 화상미팅을 하며 깃헙과 페이스북을 통해 서로의 의견과 결과물을 공유했다. 2014년 봄 귀국후 함께 오프라인에서 헤커톤도 하면서 책의 샘플을 만들며 진행했지만 각자의 일정으로 인해 MEAN 스택 집필을 흐지부지 되어갔다. 2014년 7월쯤 결단을 내리고 이렇게 진행하면 끝나지 않겠다 싶어서 다음 기회를 기약하였고, 홀로 책을 쓰기로 결심했다. 


2014년 8월 이강훈님 회사인 스터디지피에서(https://bagle.io)의 서비스를 개발하면서 미국 플젝에서 얻은 AngularJS 경험과 개념정리가 덜 된 부분을 하나하나 집어가며 집필을 시작했다. 처음에는 한 페이지를 나가는데 하루의 시간이 걸리더니 조금씩 속도가 붙으면서 한달만에 100p 가량을 썼다. 하지만 다시 가을 미국 프로젝트로 2달간 집필 중단 후 한국에 돌아와 마음을 다잡고 12년전 내 책을 출판해 보자는 꿈을 다시한번 상기했다. 위키북스의 박찬규 대표님도 은근히 압력을 넣어주시며 언제쯤 나올까요 물어볼때마다 곧 나올겁니다 대답하곤 하루 1~2시간씩 짬을 내어 집필을 계속했다. 2015년 3월 집필을 완료하고 출판사에 전달했지만 피드백으로 날아온 것은 맞춤법과 문장 난해함에 대한 엄청난 지적질의 빨간줄이었다. 


한달간 주말마다 빨간 선생님과 싸움하며 "그래 글쓰는 것도 배우는 거다"라고 생각하고 나의 국어실력을 한탄하며 글을 풀어서 이야기식으로 고쳐나갔다. 사실 블로그를 쓰다보니 블릿(점, 점으로 요약한 내용)으로 내용을 요약해 표현하다 보니 책도 그렇게 썼드랬다. 블릿 내용을 다 풀어쓰는 것만도 한달. 다시 피드백받아 또 고치고 피드백받아 또 고치고, "아 무한루프의 피드백". 점점 스트레스와 화가 살짝 났다. 인생 목표 10가지중 1가지가 1년에 책한권씩 내자였던 것이 여지없이 깨지는 순간이었다. 이렇게 하다가는 2년에 한권내는 것도 힘들겠다 싶었다. 하지만 일에는 끝이 있는 법. 5월초 거의 마무리 피드백을 보내고, 책 추천사를 받고 인덱스를 보내고, 몇가지 피드백을 마무리하며 3개월의 수정작업은 6월 5일 마무리되었고, 예약 판매가 모든 온라인 서점에서 시작되었다. 그렇게 나온 것이 "실전 프로젝트로 배우는 AngularJS" 이다. 


본 서적은 AngularJS가 하도 유행이라 하여 한번쯤은 기초서적을 구매하거나 빌려서 본적이 있고, 온라인 튜토리얼을 통해 프로토타입핑을 해보았지만 당췌 AngularJS로 서비스를 어떻게 만들어야 할지 모르는 개발자를 위한 책이다. "나도 내가 원하는 서비스 뚝딱 만들어 보고 싶어 근데 어떻게 시작해야는 거야?"라고 생각하는 모든 개발자를 위한 책이다. AngularJS는 생태계를 가지고 있고 인식의 전환을 해야하는 새로운 용어들이 존재한다. 


처음 1장에서는 간단한 ToDo 서비스를 만들면서 주변의 생태계 도구와 개념을 이해하고 2장에서는 AngularJS의 장점들과 그중에 지시자(Directive)에 대해 좀 더 심도있게 설명을 했다. 3장, 4장에서 서비스를 바로 만들 줄 알았다면 오산이다. 이제 서비스를 만들 준비운동단계이다. 먼저 요건정의를 하고 이에 맞는 코딩 컨벤션 부터 AngularJS를 이용한 SPA 개발시 준비할 것들을 프론트앤드 아키텍처로 접근해 보았다. 5장에서 이제 좀 개발들어가려 했더니 그래도 요즘 많이 사용하는 NodeJS, MongoDB는 알고가자는 취지에서 개념과 실습코드를 넣었다. 1장~5장이 준비운동과 스타트 단계였다면 6장, 7장은 엄청난 스피도로 골인점을 향해가는 단계이다. 올초 2개월간 TossLab의 JANDI(http://www.jandi.com)에서 AngularJS에 대한 컨설팅 경험을 적용한 장이다. 





목차


▣ 01장: 단일 페이지 애플리케이션 개발 준비
1-1. 개발 도구 설치 
   - 깃 설치 
   - 노드 설치 
   - 요맨 설치 
   - 서브라임 텍스트 편집기 설치 

1-2. 단일 페이지 애플리케이션 생성 
   - yo generator 선택과 설치 
   - Yo를 이용한 ToDo 애플리케이션 생성 
1-3. 애플리케이션 컴포넌트 생성 
   - 앵귤러를 위한 index.html 설정 이해하기 
   - yo를 이용한 앵귤러 컨트롤러 추가 
   - bower를 이용한 앵귤러 지시자 추가 
1-4. 애플리케이션 테스트 및 빌드 
   - grunt를 이용한 테스트 
   - grunt를 이용한 배포 
정리 

▣ 02장: AngularJS 프레임워크 이해
2-1. MV* 프레임워크 
2-2. 양방향 데이터 바인딩 
   - 스코프 내부와 상속 관계  
   - MyToDo 애플리케이션에서 양방향 데이터 바인딩 
   - 스코프 생명 주기(Life Cycle) 
   - 그 외 $scope 객체 메서드 
2-3. 의존성 주입(DI, Dependency Injection) 
2-4. 클라이언트 템플릿 
2-5. 지시자(Directive) 
   - 지시자가 DOM에 적용되는 순서 
   - 지시자 정의 
   - 지시자의 스코프 객체의 범위 종류 
   - Template, TemplateUrl, TemplateCache, replace와 ng-template 사용 
   - compile, link의 $watch 등록을 이용한 양방향 데이터 바인딩 
   - controller, require와 link 네 번째 파라미터와의 관계 
   - transclude, ng-transclude 사용 
2-6. 테스트 프레임워크(단위, E2E) 
   - 카르마 기반 단위 테스트 
   - 프로트랙터 기반 E2E 테스트 
정리 

▣ 03장: 싱글 페이지 애플리케이션 기획및 생성
3-1. 애플리케이션 기획
   - 메인 페이지 
   - 그룹 정보 페이지 
   - 그룹 활동 페이지 
   - 설문 생성 페이지 
3-2. 애플리케이션 제너레이터 설계 
   - 애플리케이션의 폴더 구조 전략 
   - 애플리케이션 제너레이터 선정 
   - 앵귤러 코드 스타일 전략 
   - 스타일 가이드에 따른 제너레이터 템플릿 수정 방법 
   - IE8 지원을 위한 index.html 설정 
3-3. SPA 생성 
   - 애플리케이션의 모듈 구성 
   - 라우팅 설정 방식 
3-4. 단위 업무를 위한 앵귤러 컴포넌트 조합 
   - $resource를 통한 REST 모델 사용 
   - promise와 $q Async 호출에 대한 이해 
정리

▣ 04장: 애플리케이션을 위한 공통 프레임워크 개발
4-1. 공통 프레임워크 모듈 개발 
   - 다국어 처리 
   - 메시지 처리 
   - 팝업 메시지창 지시자 
   - HTTP 에러 처리 
   - 사용자 정의 Bower 컴포넌트 등록 
   - 로컬 저장소 서비스 
   - 유틸리티 지시자 
4-2. 로그인 화면 개발 
   - 트위터 부트스트랩 기반의 화면 디자인 및 폰트 사용 
   - 폼 유효성(Form Validation) 검사 
   - 인증을 위한 토큰과 쿠키 
4-3. OAuth를 이용한 인증 처리 
   - 백엔드에서 Passport 모듈을 이용한 인증 처리 
   - 페이스북 인증 처리 
   - 크롬 브라우저 개발자 도구를 이용한 클라이언트 디버깅 
   - 노드 인스팩터를 이용한 서버 디버깅 
정리

▣ 05장: 메인 페이지 개발
5-1. 백엔드 API 개발 
   - REST API 별 서버 모듈 조합 
   - 노드 모듈의 exports 이해 
   - 몽고디비와 몽구스 이해 
   - 서버 모델 개발 
   - 그룹 REST API 개발 
   - 포스트맨을 이용한 REST API 검증 
   - 백엔드 단위 테스트 수행 
5-2. 메인 화면 개발 
   - 공통 컴포넌트 재구성 
   - 메인 화면 레이아웃 개발 
   - 그룹 생성 
5-3. 그룹 목록 및 정보 표현 
정리 

▣ 06장: 그룹 페이지 개발
6-1. 그룹 정보 페이지 
   - 그룹 상세 정보 조회 
   - 그룹 프로필 이미지 변경 
   - 그룹 가입, 탈퇴 
6-2. 그룹 활동 페이지 
   - 그룹 활동 화면 레이아웃 개발 
   - 그룹 멤버 목록 표현 
6-3. 설문 카드 생성 
   - 설문 카드 생성 
   - 카드 지시자 개발 
6-4. 설문 종류별 카드 표현 
6-5. 설문 응답 및 결과 표현 
정리

▣ 07장: 실시간 반응 개발
7-1. Socket.IO 기반 실시간 연동 
   - 노드 기반 백엔드 Socket.IO 
   - AngularJS 기반 프런트엔드 Socket.IO 
   - 상단 알림 메뉴 추가 
7-2. 카드 목록 UX 개선 
   - 카드에 동영상 추가 
   - 무한 스크롤 적용 
   - 애니메이션 효과 적용 
7-3. AngularJS 성능 옵션 
   - 일회 바인딩 
   - ngModelOptions 지시자 
   - 디버깅 정보 비활성화 
   - $applyAsync 적용 

정리




구매


예스24 온라인 서점


알라딘 온라인 서점


인터파크 온라인 서점


교보문고 온라인 서점


G마켓 온라인 서점


현재는 예약 판매로 10% 싸게 구매 할 수 있다. 6월 17~19일간 배송을 시작한다. 당초 높은 가격이 책정되었지만 위키북스 대표님에게 가격이 높아 개발자에게 부담이 될 것 같다하였더니 파격적인(?) 가격에 판매를 시작해 주셨다. 지금까지 독자로 책을 사보면서 철자하나 틀리면 왠지 기분이 나쁘고 지적을 해주고 싶었는데 이제부터는 너그러이 용서해 줄것 같다. 정말 많은 공력과 시간이 투여되는 시간이었다. 하지만 새로운 경험을 하게 되었고 이렇게 해서 책 한권 한권이 출판된다는 생각을 하니 한권의 책을 사도 감사히 볼 마음가짐이 생긴다.  


이번달 중으로 출판사의 양해를 얻어 1장과 2장은 블로그에 공개하려 한다. 2장은 AngularJS v1.* 이 계속 사용되는 한 유용한 레퍼런스가 되리라 생각한다. 이렇게 생애 첫 책 출판을 자축하며... 내년에는 "Data Visualization using D3.js" 이고, 여기에 ReactJS 또는 AngularJS v2.* 와 Meteor를 접목한 경험을 출판할 계획이다. 글쓰기도 가끔은 중독이다. 자전거 처럼 잘 타지는 못하지만 타고 있는 동안은 자유다. 나를 표현하고 느낄 수 있는 시간이랄까~~~




소스 


책의 소스는 모두 깃헙에 있습니다. 책 챕터마도 브랜치에 대한 정보가 담겨 있습니다. 


책 소스를 위한 깃헙 그룹 : https://github.com/AngularJS-SPA-Development



posted by 윤영식
2014. 8. 3. 23:26 AngularJS/Concept

AngularJS를 배우기 위해 좌충우돌 하며 읽고, 보고, 듣고, 코딩해본 코스를 나름 정리해 보았다. 




1. 개념잡기

  - Angular's father인 미스코님의 AngularJS 소개 동영상을 본다 : 단계별로 jQuery와 잘 비교하고 있다

    

  - Art of AngularJS를 보고서 이제 배워야할 필요성을 느껴보세요. 이제 시작하세요. 

    


  - AngularJS의 중요 요소와 기본기를 다져보자 (60분 동강)

    

     + AngularJS 전체 구성 요소 : 각각에 대해 간단히 알아보자

   

      + AngularJS 흐름

   


  - 개발자 가이드에서 Bootstrap, HTML Compiler, Conceptual Overview, Directives 를 꼭 읽는다 (내 포스팅에도 정리했다)

  - AngularJS 홈페이지에서 제공하는 튜토리얼 보기

  - 요약 정리 내역을 다시 보자




2. 프로토타입핑 해보기

  - 전체 flow를 간단히 코딩해 보자

  - egghead.io 에서 모든 동강을 따라해 본다 : 100개 넘는 강좌가 있고 짧은 대신 꼭 코딩해본다 

    

  - AngularJS 팀의 Meetup 동영상들 보기 : Angular 기능별 설명을 해준다 (이건 개당 1시간씩 넘어서 틈틈히 보자)

    + Best Practices :  미스코님이 직접 설명한다.

    

  - AngularJS에서의 Deferred and Promise에 대한 이해

    

  - http://www.yearofmoo.com/ 의 AngularJS 강좌들 코딩

    + Use AngularJS to Power

    + More AngularJS Magic

  - AngularJS Design Patterns 

  - MEAN Stack 사용 예제 : MEAN is MongoDB + Express + AngluarJS + Node.js




3. Angular 생태계

  - Angular-UI : Twitter Bootstrap, Grid 등 지속적으로 AngularJS Directives 를 만들어 내고 있다 

  - angular modules는 http://ngmodules.org/ 먼저 찾아보자

    

  - angular-strap : http://mgcrea.github.io/angular-strap/

  - Learn AngluarJS : Thinkster.io

  - AngularJS-Tips




4. 데이터 연동

  - AngularJS에서 제공하는 $resource를 사용하여 RESTful 하게 개발한다

    + 동영상에서 $resource를 어떻게 사용하는지 익히자 (GitHub Demo 소스)

    

  - RestangularJS를 이용한  RESTful 서버 연동

  - Real-time을 위한 AngularJS와 Socket.io 연동하기 seed 구성




5. 개발환경 구축하기 

  - 개발 소스 코드 저장소는 DVCS인 Git + GitHub 을 사용한다 : Git 을 통하여 성공적인 브랜칭 전략을 세우자

  - Yeoman을 통하여 AngularJS의 스케폴딩 소스를 만들어 개발한다 : AngularJS 개발환경 구성하기

  - Yeoman generator Angular 와 Express.js 연동하기




6. 참여와 공유

  - AngularJS 구글 그룹스 참여

  - 공개 그룹 활동하기

    + Facebook AgularJS 오픈 그룹 

    + Google+ AngularJS 오픈 그룹 

  - JSFiddle을 통하여 예제파일 공유하기

  - StackOverflow 통하여 Q&A 하기

  - AngularJS 트위터 팔로잉

최근 -213.10.11- 으로 AngularJS에 대한 관심이 높아지고 있고, 다양한 블로그와 관련 글이 많이 올라오고 있다. 이중 AngularJS 배우기의 종결자 블로깅을 들어가서 배워보자 



7. AngularJS v1.* 에서 v2.* 으로  
  - AngularJS는 올해 v2.* 버전이 나올 예정이고 큰 변화를 예고 하고 있다. 하지만 이것은 피할 수 없는 대세로 보여진다. 이유는 간단하다. 좀 더 단순하고 좀 더 성능이 뛰어나며 인지 가능한 단순 문법으로 하는 길로 가고 있다. 
  - v1.* 에서 v2.* 로 바뀌니 어쪄냐고 호들갑 떨지 말자. v1.*도 쓰지 않으면서 v2.* 의 변화를 논하지도 말자. 지금 당장 v1.*를 써보고 좀 더 쉽게 웹 애플리케이션을 개발해 보는 경험이 중요하다. v2.*가 성숙할 때 쯤이면 우리는 더 많은 변화 앞에 놓여 있을 것이다. 
  - v2.* 간결함과 Web Components, ECMAScript 6 로의 방향의 핵심은 Componen를 사용한 Composition 패턴의 애플리케이션이라 보며 새롭지도 않으며 어렵지도 않은 방향으로 대중적으로 사용할 수 있게 만들어 가는 능력에 찬사를 보낸다. 땡큐 AngularTeam!!!
  
  



8. Directives $compile 서비스에 대한 이해 

2015 ng vegas에서 발표한 $compile에 대한 구현과정을 상세히 설명하고 있다. 예로 대시보드 빌더를 개발한다고 했을 때 대시보드 화면에 차트를 가져다 놓을 때 차트에 대한 디렉티브가 있다고 하면 동적으로 디렉티브를 컴파일하고 $scope와 링크를 맺우어주어야 한다. 이런 일련의 과정이 어떻제 진행되는지 알 수 있다. 또한 디렉티브에 대한 상호 관계로 상속(Inheritance)와 격리(Isolate)부분도 설명한다.  

- 발표 동영상 

  
  
  발표중에 나온 장표 

  




<참조>

  - 배우는 과정을 잘 요약한 블로깅 : http://blog.whydoifollow.com (강추)

  - AngularJS 내용 요약 (필독)

  - Angular v1.3 변경 사항들

  - 몇가지 참조할 만한 사이트 

    + AngularJS 포스팅 in codingsmackdown.tv

       tiny -> medium -> large project 확장하는 방법 (소스)

    + 페이지 플래그먼트의 라우팅 : http://onehungrymind.com/building-a-website-with-angularjs-routes-and-partials/

    + $apply 사용 이유http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

    + $provide 사용 : http://slides.wesalvaro.com/20121113/#/

    + AngularJS에서 Dependency Injection에 대한 이해

    + 요분 유명하다 와인샐러 샘플 : http://coenraets.org/blog/2012/02/sample-application-with-angular-js

    + 전체 구성요소 설명

    + Directive 통하여 재사용가능 컴포넌트 만들기

    + Lazing Loading in AngularJS

    + Animation in AngularJS

    + AngularJS CheetSheet

  - 처음 개발할 때 8가지 유용한 개발 접근법 ($rootScope, $locationProvider 사용예)



posted by 윤영식
2014. 6. 28. 19:07 Big Data/ElasticSearch

ElasticSearch(이하 ES) 엔진에 수집된 데이터에 대하여 Kibana 도움 없이 직접 Data Visualization 하는 기술 스택을 알아보고, 실데이터를 통한 화면 1본을 만들어 본다. 




ES 시각화를 위한 다양한 방식의 시도들


사전조사-1) 직접 클라이언트 모듈 제작하여 Data Visualization 수행 

  - elasticsearch.js 또는 elatic.js 사용하지 않고 REST 호출 통해 데이터 시각화 수행 

    (Protovis 는 D3.js 기반 Chart를 사용함)

  - FullScale.co에서는 dangle 이라는 시각화 차트를 소개

    (D3.js 기반의 AngularJS Directives 차트)

  - D3.js 기반의 전문적인 차트를 사용하는 방법을 익힐 수 있다. 하지만 제대로 갖춰진 ES 클라이언트 모듈의 필요성 대두


사전조사-2) elasticsearch.js 사용하여 Data Visualization 수행

  - elasticsearch.js와 D3.js, jquery, require.js를 통해서 샘플 데이터를 시각화 수행

    (AngularJS는 사용하지 않고, 전문적인 차트 모듈사용하지 않음)

  - AngularJS 기반으로 Protovis 또는 Dangle 차트를 사용하여 표현해 본다.


사전조사-3) elastic.js 사용하여 Data Visualization 수행

  - elastic.js 홈페이지에서 API를 숙지한다.

  - DSL API를 살펴보자. DSL을 이해하기 위해서는 ES의 Search API에 대한 이해가 필요하다.

  - Query를 작성하고 Filtering 하면 group by having과 유사한 facets (지금은 aggregation 을 사용)하여 검색을 한다.

    Query -> Filter -> Aggregation에 대해 알면 DSL구성을 이해할 수 있다.

  - 자신의 Twitter 데이터를 가지고 elastic.js와 angular.js를 사용하여 트윗 내용을 표현하는 방법 (GitHub 소스)




ES Data Visualization을 위한 나만의 Tech Stack 만들기 


  - ES 클라이언트 모듈 : elastic.js 의 DSL(Domain Specific Language)를 숙지한다. 

    elastic.js는 ElasticSearch의 공식 클라이언트 모듈인 elasticsearch.js 의 DSL 화 모듈로 namespace는 ejs 이다.  

  - 시각화를 위한 D3.js 의 개념 이해 (D3.js 배우기)

  - Kibana에서 사용하고 있는 Frontend MV* Framework인 AngularJS (AngularJS 배우기)

  - AngularJS 생태계 도구인 yeoman 을 통해 개발 시작하기 (generator-fullstack,  Yeoman 사용방법)

  - 물론 Node.js는 기본이다. 


그래서 다음과 같이 정리해 본다. 


  - AngularJS 기반 Frontend 개발

    1) Node.js 기초

    2) Yeoman + generator-angular 기반 

  - D3.js 기반의 Chart 이며 AngularJS 바로 적용가능토록 Directives 화 되어 있는 차트 중 선택사용

    1) Protovis

    2) Dangle

    3) Angular nvd3 charts (추천)

    4) Angular-Charts

    5) Angular Google Charts 

  - elasticsearch.js를 DSL로 만든 elastic.js 사용


그래서 다시 그림으로 정리해본 기술 스택



ES Data Visualization 개발을 위한 구성 stack 그림






== 이제 만들어 봅시다!!! ==


 

환경설정

  - node.js 및 yeoman 설치 : npm install -g generator-angular-fullstack 설치 (generator-angular는 오류발생)

  - twitter bootstrap RWD 메뉴화면 구성 (기본 화면 구성)

  - angular-ui의 angular-bootstrap 설치 :  bower install angular-bootstrap --save

  - elasticsearch.js 설치 : bower install elasticsearch --save

  - elastic.js 설치 : bower install elastic.js --save

  - angular-nvd3-directives chart 설치 : bower install angularjs-nvd3-directives --save



angular layout 구성 

  - 애플리케이션 생성 : GitHub Repository를 만들어서 clone 한 디렉토리에서 수행하였다

$ git clone https://github.com/elasticsearch-kr/es-data-visualization-hackerton 

$ cd es-data-visualization-hackerton 

$ yo angular-fullstack esvisualization

  - main.html 과 scripts/controllers/main.js 를 주로 수정함 

// main.html 안에 angular-nvd3.directives html 태그 및 속성 설정 

    <div class="row">

      <div class="col-xs-12 col-md-12">

        <div class="panel panel-default">

          <div class="panel-heading">

            <button type="button" ng-click="getImpression()" class="btn btn-default">Impression Histogram</button>

          </div>


          <div class="panel-body">


            <!-- angular-nvd3-directives : multi-bar chart -->

            <div class="col-xs-12 col-md-12">

              <nvd3-multi-bar-chart

                  data="impressionData"

                  id="dataId"

                  xAxisTickFormat="xAxisTickFormatFunction()"

                  width="550"

                  height="350"

                  showXAxis="true"

                  showYAxis="true">

                    <svg></svg>

              </nvd3-multi-bar-chart>

            </div>


          </div>

        </div>

      </div>

    </div>



// main.js 안에서 elasticsearch.js를 직접 호출하여 사용함 

angular.module('esvisualizationApp')

  .controller('MainCtrl', function ($scope, $http) {


    // x축의 값을 date으로 변환하여 찍어준다 

    $scope.xAxisTickFormatFunction = function(){

      return function(d){

        return d3.time.format('%x')(new Date(d));

      }

    }


    // 화면에서 클릭을 하면 impression index 값을 ES에서 호출하여 

    // ES aggregation json 결과값을 파싱하여 차트 데이터에 맵핑한다

    $scope.getImpression = function() {


      // ES 접속을 위한 클라이언트를 생성한다 

      var client = new elasticsearch.Client({

                                              host: '54.178.125.74:9200',

                                              sniffOnStart: true,

                                              sniffInterval: 60000,

                                            });


// search 조회를 수행한다. POST 방식으로 body에 실 search query를 넣어준다 

      client.search({

          index: 'impression',

          size: 5,

          body: {

            "filter": {

                "and": [

                    {

                      "range": {

                        "time": {

                            "from": "2013-7-1", 

                            "to": "2014-6-30"

                        }

                      }

                    }

                ]

            },

            "aggs": {

              "events": {

                "terms": {

                  "field": "event"   

                },

                "aggs" : {   

                  "time_histogram" : {

                      "date_histogram" : {

                          "field" : "time",

                          "interval" : "1d",   

                          "format" : "yyyy-MM-dd" 

                      }

                  }

                }

              }

            }


            // End query.

          }

      }).then(function (resp) {

         var impressions = resp.aggregations.events.buckets[0].time_histogram.buckets;

         console.log(impressions);


         var fixData = [];

         angular.forEach(impressions, function(impression, idx) {

          fixData[idx] = [impression.key, impression.doc_count];

         });

   

   // 결과에 대해서 promise 패턴으로 받아서 angular-nvd3-directives의 데이터 구조를 만들어 준다

   // {key, values}가 하나의 series가 되고 배열을 가지면 다중 series가 된다. 

         $scope.impressionData = [

            {

              "key": "Series 1",

              "values": fixData

            }

          ];


  // apply 적용을 해주어야 차트에 데이터가 바로 반영된다.

        $scope.$apply();

      });

    }


  });




결과 화면 및 해커톤 소감

  - "Impression Histogram" 버튼을 클릭하면 차트에 표현을 한다.

  - elastic.js의 DSL을 이용하면 다양한 파라미터에 대한 핸들링을 쉽게 할 수 있을 것같다. 

  - AngularJS 생태계와 elasticsearch.js(elastic.js)를 이용하면 Kibana의 도움 없이 자신이 원하는 화면을 쉽게 만들 수 있다. 

  - 관건은 역시 ES에 어떤 데이터를 어떤 형태로 넣느냐가 가장 먼저 고민을 해야하고, 이후 분석 query를 어떻게 짤 것인가 고민이 필요!



* 헤커톤 소스 위치 : https://github.com/elasticsearch-kr/es-data-visualization-hackerton



<참조> 

  - elasticsearch.js 공식 클라이언트 모듈을 DSL로 만든 elastic.js 

  - elastic.js를 사용한 ES Data Visualization을 AngularJS기반으로 개발

  - Protovis 차트를 이용한 facet 데이터 표현

  - ElasticSearch Data Visualization 방법

  - D3.js 와 Angular.js 기반으로 Data Visualization

  - ElasticSearch의 FacetAggregation 수행 : 향후 Facet은 없어지고 Aggregation으로 대체될 것이다.

  - AngularJS Directives Chart 비교

posted by 윤영식
2014. 1. 26. 07:50 AngularJS/Start MEAN Stack

yeoman은 자바스크립트 기반의 프론트앤드 개발을 도와주는 자동화 툴이다. 자바에서 요즘 많이 사용되는 Maven과 유사하다. 



1. 사용이유

  서비스 개발의 규모가 커지고 자바스크립트의 각 모듈별의 버전 의존성을 관리하려면 어떻게 해야 할까? 그리고 필요한 자바스크립트 모듈을 다운로드하기 위하여 각 사이트를 방문하여 다운로드 해야할까? 기본적인 코드 골격과 코딩 컨벤션은 최초에 어떻게 해야할까? 개발하고 나서 테스트 및 빌드 자동화는 어떻게 해야할까? 이러한 의문에 대한 해답을 주는 것이 Yeoman이다.

  - 스케폴딩 생성 : 기본적인 코드 골격을 만들어 주고 이후 추가되는 앵귤러 코드는 명령을 통해 생성한다 

  - 라이브러리 의존성 관리 : 프론트앤드에서 사용하는 다양한 jquery 모듈과 angular.js 모듈의 설치 및 버전 관리를 한다 

  - 테스트 및 빌드 자동화 : 테스트 코드를 작성하였다면 테스트 수행 및 코드 압축과 문법오류 검사 그리고 배포파일의 생성을 한다 

  - 사전 점검 : 프론트단의 코드를 Node.js기반 수행하여 브라우져에서 개발한 화면을 사전에 테스트 점검 가능하다



2. 설치하기  

  설치는 의외로 간단하다. 사전 준비로 Node.js를 설치 하였다면 NPM (Node Package Manager)을 통해 설치한다. yo, bower, grunt 의 특징은 자바스크립트로 개발하여 node.js기반위애 구동하는 도구이다 

// 1) yo 설치 

$ npm install -g yo


// 2) bower 설치 

$ npm install -g bower


// 3) grunt 설치 

$ npm install -g grunt-cli

  * http://yeoman.io, http://bower.iohttp://gruntjs.com 에서 설치관련 자세한 사항을 참조한다. 



3. 주요 기능 

  yeoman은 크게 3가지 기능으로 구분된다. 각 기능의 구분이 명확하고 사용하는 목적이 틀리기 때문에 잘 알아 두기 바란다. 기본적으로 yo를 yeoman팀에서 자체적으로 만들었고, bower와 grunt는 이미 존재하였던 도구로써 yeoman이라는 이름으로 통합한 것이다. 따라서 bower와 grunt를 별개의 독립적인 도구로 사용할 수도 있다


  yo 

  - 프론트앤드 개발을 위한 기본 구조를 만들어 준다. yeoman에서는 스켈폴딩 코드를 만들어 준다고 말한다 

  - 스케폴딩 파일을 생성하려면 목적에 맞는 제너레이터를 사전에 설치해야 한다.

    1) 제너레이터 명칭 구성 : generator-<UserDefine> 로서 UserDefine 명칭을 정한다. 예) generator-angular

    2) npm 을통하여 글로벌 설치한다 

    3) UserDeinfe 명칭이 angular 라면 yo 명령 다음에 제너레이터의 구분을 위하여 항시 해당 UserDefine 명령이 온다 

        yo angular <Subject>  또는 yo angular:<SubCommand>  <Subject>

    4) yo angular <Subject> 를 통해 초기 프로젝트의 명칭을 정하고 기본 골격을 생성한다 

    5) yo angular:<SubCommand> <Subject> 를 통해 기본골격 밑으로 기능을 추가한다. SubCommand는 제너레이터에 따라 사용자 정의 할 수 있다 

  - 프로젝트에 필요한 골격 코드 생성을 위한 자신만의 제너레이터를 만들 수 있다. 

  - 사용법

    1) angular 제너레이터 설치

    2) 프로젝트 폴더생성

    3) angular 프로젝트 생성을 하고 Sass 미사용, Bootstrap을 사용체크하면 필요한 파일과 모듈을 자동 설치한다

    4) 프로젝트 기본 골격코드 자동 생성하면 app 폴더가 프론트 개발 ROOT 폴더가 된다

// 1) 

$ npm install -g generator-angular


// 2) 

$ mkdir meanstack & cd meanstack


// 3) 

$ yo angular meanstack

     _-----_

    |       |

    |--(o)--|   .--------------------------.

   `---------´  |    Welcome to Yeoman,    |

    ( _´U`_ )   |   ladies and gentlemen!  |

    /___A___\   '__________________________'

     |  ~  |

   __'.___.'__

 ´   `  |° ´ Y `


Out of the box I include Bootstrap and some AngularJS recommended modules.


[?] Would you like to use Sass (with Compass)? No

[?] Would you like to include Twitter Bootstrap? Yes

[?] Which modules would you like to include? (Press <space> to select)

❯⬢ angular-resource.js

 ⬢ angular-cookies.js

 ⬢ angular-sanitize.js

 ⬢ angular-route.js


// 4) 


bower

  - bower는 트위터에서 개발한 프론트앤드 라이브러리 설치 및 버전 의존성 관리 도구이다 

  - yo를 통하여 스케폴딩 파일이 생성하면 bower 사용을 위한 기본 환경파일도 자동 생성된다 

    1) 환경파일은 bower.json 으로 현재 설치된 라이브러리 명칭과 버전을 자동 기록한다 

    2) 라이브러리 설치 위치정보는 .bowerrc 에서 변경한다. 기본값으로 "bower_components" 를 사용한다 

// 1) bower.json 최초 설치 정보 

{

  "name": "meanstack",

  "version": "0.0.0",

  "dependencies": {

    "angular": "1.2.6",

    "json3": "~3.2.6",

    "es5-shim": "~2.1.0",

    "jquery": "~1.10.2",

    "bootstrap": "~3.0.3",

    "angular-resource": "1.2.6",

    "angular-cookies": "1.2.6",

    "angular-sanitize": "1.2.6",

    "angular-route": "1.2.6"

  },

  "devDependencies": {

    "angular-mocks": "1.2.6",

    "angular-scenario": "1.2.6"

  }

}


// 2) .bowerrc 위치정보

{

    "directory": "app/bower_components"

}


  - 사용법 

   1) 검색 : "bower search <명칭>"

   2) 설치 : "bower install <명칭>  --save (또는 --save-dev)"

   3) 보기 : "bower list"

   3) 도움말 : "bower help" 또는 "bower help <명령어>"

$ bower list

bower check-new     Checking for new versions of the project dependencies..

meanstack#0.0.0 ~/meanstack

├── angular#1.2.6 (latest is 1.2.11-build.2184+sha.319dd1a)

├─┬ angular-cookies#1.2.6 (latest is 1.2.11-build.2184+sha.319dd1a)

│ └── angular#1.2.6 (latest is 1.2.11-build.2184+sha.319dd1a)

├─┬ angular-mocks#1.2.6 (latest is 1.2.11-build.2184+sha.319dd1a)

│ └── angular#1.2.6

├─┬ angular-resource#1.2.6 (latest is 1.2.11-build.2184+sha.319dd1a)

│ └── angular#1.2.6

├─┬ angular-route#1.2.6 (latest is 1.2.11-build.2184+sha.319dd1a)

│ └── angular#1.2.6

├─┬ angular-sanitize#1.2.6 (latest is 1.2.11-build.2184+sha.319dd1a)

│ └── angular#1.2.6

├─┬ angular-scenario#1.2.6 (latest is 1.2.11-build.2184+sha.319dd1a)

│ └── angular#1.2.6

├─┬ bootstrap#3.0.3

│ └── jquery#1.10.2 (2.1.0 available)

├── es5-shim#2.1.0 (latest is 2.3.0)

├── jquery#1.10.2 (latest is 2.1.0)

└── json3#3.2.6 (latest is 3.3.0)

  * angular 개발시점에 정식 릴리즈된 가장 최신버전을 사용할 예정이고 bower를 통하여 업데이트할 것이다. 


Grunt

  - grunt는 자바의 ant와 같은 기능을 수행한다

  - 다양한 플러그인을 통하여 기능을 첨부하여 확장할 수 있다. 

  - yo을 통해 프로젝트 골격 코드생성시 Gruntfile.js 환경파일이 기본 생성된다 

  - 또한 골격 코드 생성시 기본적으로 사용되는 플러그인은 node_moudles 폴더에 자동 설치된다 

// 1) node_modules에 기본 설치된 grunt 플로그인 


// 2) Gruntfile.js 내역 중 명령 일부

module.exports = function (grunt) {

  // Load grunt tasks automatically

  require('load-grunt-tasks')(grunt);


  // Time how long tasks take. Can help when optimizing build times

  require('time-grunt')(grunt);


  // Define the configuration for all the tasks

  grunt.initConfig({


    // Project settings

    yeoman: {

      // configurable paths

      app: require('./bower.json').appPath || 'app',

      dist: 'dist'

    },

    ... 중략...


grunt.registerTask('serve', function (target) {

    if (target === 'dist') {

      return grunt.task.run(['build', 'connect:dist:keepalive']);

    }


    grunt.task.run([

      'clean:server',

      'bower-install',

      'concurrent:server',

      'autoprefixer',

      'connect:livereload',

      'watch'

    ]);

  });


  grunt.registerTask('server', function () {

    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');

    grunt.task.run(['serve']);

  });


  grunt.registerTask('test', [

    'clean:server',

    'concurrent:test',

    'autoprefixer',

    'connect:test',

    'karma'

  ]);


  grunt.registerTask('build', [

    'clean:dist',

    'bower-install',

    'useminPrepare',

    'concurrent:dist',

    'autoprefixer',

    'concat',

    'ngmin',

    'copy:dist',

    'cdnify',

    'cssmin',

    'uglify',

    'rev',

    'usemin',

    'htmlmin'

  ]);


  grunt.registerTask('default', [

    'newer:jshint',

    'test',

    'build'

  ]);

};


  - 사용법

   1) 테스트 : grunt test

   2) 빌드 : grunt build

   3) 프리뷰 : grunt serve

// 1) 

$ grunt test

Running "clean:server" (clean) task


Running "concurrent:test" (concurrent) task


    Running "copy:styles" (copy) task

    Copied 1 files


    Done, without errors.



    Execution Time (2014-01-25 22:42:19 UTC)

    loading tasks   4ms  ▇▇▇▇ 25%

    copy:styles    10ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 63%

    Total 16ms


Running "autoprefixer:dist" (autoprefixer) task

Prefixed file ".tmp/styles/main.css" created.


Running "connect:test" (connect) task

Started connect web server on 127.0.0.1:9001.


Running "karma:unit" (karma) task

INFO [karma]: Karma v0.10.9 server started at http://localhost:8080/

INFO [launcher]: Starting browser Chrome

WARN [watcher]: Pattern "/Users/nulpulum/prototyping/yeomain/meanstack/test/mock/**/*.js" does not match any file.

INFO [Chrome 32.0.1700 (Mac OS X 10.9.1)]: Connected on socket nUaNX14YFrQJ_aeDkWM5

Chrome 32.0.1700 (Mac OS X 10.9.1): Executed 1 of 1 SUCCESS (2.184 secs / 0.033 secs)


Done, without errors.



Execution Time (2014-01-25 22:42:17 UTC)

concurrent:test  2.2s  ▇▇▇▇▇▇▇▇▇▇▇26%

karma:unit       6.2s  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 73%

Total 8.4s


// 2) 브라우져가 자동 실행된다 

$ grunt serve 


Yeoman에 대한 이해와 기본적인 설치, 사용법을 익혔다. 프론트 앤드 개발을 하면서 계속 사용하게 되므로 잘 익혀 놓도록 하자 


posted by 윤영식
2013. 11. 16. 05:46 My Projects/BI Dashboard

Spring MVC의 RESTful 방식을 사용하면서 AngularJS를 Eclipse에서 개발하기 위한 제반 설정 환경을 만들어 보도록 한다. 핵심은 Java를 위한 라이브러리 의존성 관리와 빌드를 위하여 Maven을 사용하고 JavaScript는 의존성 관리는 bower를 사용하고 빌드도구는 grunt를 사용하게 된다. 따로 따로 사용하지 않고 하나의 프로젝트로 합치는 과정을 생각해 보자 



1. Maven을 이용한 Spring MVC 환경 만들기 

  - 이미 Eclipse Juno 기반에서 Maven + Spring MVC 환경 설정 블로깅을 하였다

  - pom.xml 에 logback 관련 내용 추가 (참조)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.ysyun</groupId>

<artifactId>DashboardTest</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>war</packaging>

<url>http://maven.apache.org</url>


<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<spring.version>3.2.0.RELEASE</spring.version>

<junit.version>4.11</junit.version>

<jdk.version>1.6</jdk.version>

</properties>


<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>${spring.version}</version>

<exclusions>

<exclusion>

<artifactId>commons-logging</artifactId>

<groupId>commons-logging</groupId>

</exclusion>

</exclusions>

</dependency>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>${spring.version}</version>

</dependency>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>${spring.version}</version>

<exclusions>

<exclusion>

<groupId>commons-logging</groupId>

<artifactId>commons-logging</artifactId>

</exclusion>

</exclusions>

</dependency>


<!-- use logback logger -->

<dependency>

<groupId>ch.qos.logback</groupId>

<artifactId>logback-access</artifactId>

<version>1.0.13</version>

</dependency>

<dependency>

<groupId>ch.qos.logback</groupId>

<artifactId>logback-core</artifactId>

<version>1.0.13</version>

</dependency>

<dependency>

<groupId>ch.qos.logback</groupId>

<artifactId>logback-classic</artifactId>

<version>1.0.13</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

<version>1.7.5</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>jcl-over-slf4j</artifactId>

<version>1.7.5</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>log4j-over-slf4j</artifactId>

<version>1.7.5</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-jcl</artifactId>

<version>1.7.5</version>

</dependency>


<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>${junit.version}</version>

<scope>test</scope>

</dependency>

</dependencies>


<build>

<finalName>DashboardTest</finalName>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.0</version>

<configuration>

<source>${jdk.version}</source>

<target>${jdk.version}</target>

</configuration>

</plugin>

</plugins>

</build>

</project>

  - 다음에 logback.xml 환경파일을 resource에 놓아 classpath에 잡아준다. 개발/배포 따로 구성한다 

<?xml version="1.0" encoding="UTF-8"?>

<configuration scan="true">

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">

        <encoder>

            <charset>utf-8</charset>

            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>

        </encoder>

    </appender>

    <logger name="ch.qos.logback" level="WARN"/>

    <logger name="org.apache" level="WARN"/>

    <logger name="org.springframework" level="WARN"/>

    <logger name="org.springframework.web" level="WARN"/>

    <logger name="org.springframework.security" level="WARN"/>

    <logger name="org.springframework.cache" level="WARN"/>


    <root level="DEBUG">

        <appender-ref ref="CONSOLE"/>

    </root>

</configuration>




2. SPA 환경 잡아주기 

  - Yeoman을 통하여 angular 프로젝트 만들기 (참조)

$ yo angular SolarDasbhoard


  - 위의 파일을 각각 다음과 같이 이동한다 

    + app/ 폴더에 있는 것을 src/main/webapp로 복사한다 

    + node_modules 및 test 폴더 그리고 나머지 모든 파일을 eclipse 프로젝트 root로 복사한다 

      여기서 node_modules안의 모듈은 grunt와 karma 테스트 모듈들로 운영에 배포될 필요가 없다. 

      운영 배포는 webapp/ 밑에 있는 파일들이고, 사용하는 모듈은 src/main/webapp/bower_components/ 밑에 위치한다 

      


  - app폴더 밑의 내용이 src/main/webapp로 이동하였으므로 관련 환경설정 내역을 수정한다 

// bower 설정파일인 .bowerrc  변경 

{

    "directory": "src/main/webapp/bower_components"

}


// karm.conf.js 파일 내역 수정

    files: [

      'src/main/webapp/bower_components/angular/angular.js',

      'src/main/webapp/bower_components/angular-mocks/angular-mocks.js',

      'src/main/webapp/bower_components/angular-resource/angular-resource.js',

      'src/main/webapp/bower_components/angular-cookies/angular-cookies.js',

      'src/main/webapp/bower_components/angular-sanitize/angular-sanitize.js',

      'src/main/webapp/scripts/*.js',

      'src/main/webapp/scripts/**/*.js',

      'test/mock/**/*.js',

      'test/spec/**/*.js'

    ],


// grunt build를 위한 Gruntfile.js 내역 수정 

// 소스의 위치와 grunt build시에 dist 폴더에 .html과 WEB-INF/* 파일까지도 copy 하도록 수정 

 yeoman: {

      // configurable paths

      app: require('./bower.json').appPath || 'src/main/webapp',

      dist: 'dist'

    },

... 중략 ...

 copy: {

      dist: {

        files: [{

          expand: true,

          dot: true,

          cwd: '<%= yeoman.app %>',

          dest: '<%= yeoman.dist %>',

          src: [

            '*.{ico,png,txt,html}',

            '.htaccess',

            'bower_components/**/*',

            'images/{,*/}*.{gif,webp}',

            'styles/fonts/*',

            'WEB-INF/*'

          ]

        }, {

          expand: true,

          cwd: '.tmp/images',

          dest: '<%= yeoman.dist %>/images',

          src: [

            'generated/*'

          ]

        }]

      },

      styles: {

        expand: true,

        cwd: '<%= yeoman.app %>/styles',

        dest: '.tmp/styles/',

        src: '{,*/}*.css'

      }

    },



3. .war 배포파일 만들기 

  - Maven(java 서버)와 Yo(javascript 클라이언트) 환경설정을 완료하였다면 빌드했을 때 최종파일을 .war파일로 묶어보자 

  - grunt build를 했을 경우 프로젝트의 root/dist 디렉토리가 신규 생성되어 src/main/webapp/* 파일이 minification 되어 들어있다

  - 해당 파일을 .war안에 묶기 위하여 pom.xml 에 플러그인 설정 추가

<build>

<finalName>DashboardTest</finalName>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.0</version>

<configuration>

<source>${jdk.version}</source>

<target>${jdk.version}</target>

</configuration>

</plugin>

<!-- grunt build 수행하여서 생성되는 폴더인 dist 를 지정한다 -->

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-war-plugin</artifactId>

<version>2.4</version>

<configuration>

<warSourceDirectory>dist</warSourceDirectory>

</configuration>

</plugin>

</plugins>

</build>


  - 배포파일 war 만들기 순서

$ grunt build (if error ocurred, option --force)

$ mvn clean install

[INFO] Scanning for projects...

[INFO] ------------------------------------------------------------------------

[INFO] Building DashboardTest 0.0.1-SNAPSHOT

[INFO] ------------------------------------------------------------------------

.. 중략 ..

[INFO] ------------------------------------------------------------------------

[INFO] BUILD SUCCESS

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 5.109s

[INFO] Finished at: Fri Nov 15 15:43:09 EST 2013

[INFO] Final Memory: 12M/81M

[INFO] ------------------------------------------------------------------------

  * eclipse 의 "Run As..." 의 "5 Maven Build"를 해도 같은 결과를 받음 


이제 eclipse 상에서 Spring Framework + AngularJS Framework 으로 개발을 해보자 

GitHub URL : https://github.com/ysyun/SPA_Angular_SpringFramework_Eclipse_ENV



<참조>

  - SLF4J를 통하여 logback 사용하기

  - Yeoman을 통한 AngularJS + Express 환경구성하기

  - Maven 기본 디렉토리 layout, pom.xml 에서 변경하는 방법

posted by 윤영식
2013. 10. 30. 14:31 My Services/PlayHub

프론트 개발을 위해 준비해야할 것들은 무엇이 있을까? 우선 개발 및 테스트 프레임워크와 라이브러리 관리, 테스트/코드커버리지/빌드 자동화 수행등 준비할 것들이 많다. 이것을 한번에 준비하고 자동화할 방법은 없을까?



1. Yeoman

  - yo : 코드 스케폴딩 역할 (프로젝트를 시작할 때 최초에 디렉토리구조와 템플릿 파일일 제공해 준다) generator-* 로 시작

  - grunt : test, lint, concatenate, build등 Java의 Ant와 같은 Task를 자동 수행

  - bower : 내부적으로 사용하는 컴포넌트의 버전 의존성 관리 및 설치/업데이트/삭제 관리

  - 참조 



2. Addy Osmani의 Frontend Workflow

  - 자동화는 반복적인 작업을 효율적으로 만드는 과정

  - Frontend Automation = Scaffolding + Download Libraries + Download Template + Download Framework



3. PlayHub Workflow 만들기 

  - 자신의 개발환경에 GitHub 저장소 설정하기

    + mac 또는 windows

    + nitrous.io 같은 PaaS 에도 설정가능 

// Node Version Manager 설치 

$ curl https://raw.github.com/creationix/nvm/master/install.sh | sh

$ exit

logout

Connection to 127.0.0.1 closed.


// 현재 CentOS에 설치된 Node version 정보가 나오고 원하는 버전정보를 선택하여 사용할 수 있다. 명령은 help 참조

$ nvm list

       N/A

current: v0.11.5


// playhub 디렉토리 만듦 - 해당 디렉토리 밑으로 playhub의 저장소를 놓을 것임 

$ mkdir playhub 


// playhub의 저장소를 git clone하기 위하여 자신의 ssh 공개키가 없다면 생성한다

// 생성방법 참조

$ cd .ssh

$ ssh-keygen -t rsa -C ysyun@yuwin.co.kr  // 이후 쭉 enter

Generating public/private rsa key pair.

Enter file in which to save the key (/home/vagrant/.ssh/id_rsa):

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/vagrant/.ssh/id_rsa.

Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub.

The key fingerprint is:

8a:32:de:ef:de:fd:22:8f:8d:38:70:b0:d7:56:e1:da ysyun@yuwin.co.kr

The key's randomart image is:

+--[ RSA 2048]---+

|                            |

|          .                 |

|         . .                |

|    .     o                |

|     o .S+               |

|    o.o.+ E              |

|  o .+..                  |

| . +  .o.=.              |

|  . .+=.+o+o.         |

+------------------+

$ ssh-add id_rsa

Could not open a connection to your authentication agent.


// 두개의 id_rsa 파일 생성 

$ ls -lart

-rw-rw-r--  1 vagrant vagrant  399 2013-10-30 05:59 id_rsa.pub

-rw-------  1 vagrant vagrant 1675 2013-10-30 05:59 id_rsa

drwx------  2 vagrant root    4096 2013-10-30 05:59 .


$ cat id_rsa.pub

ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAyvfJRNE/Kx+VwuGcQX8+PYbFadT6mCLZ1.. 중략 ..XS0U0uQ== ysyun@yuwin.co.kr


// GitHub -> "Account Settings" -> "SSH Keys"에서 SSH key값 등록



// 이제 GitHub에서 PlayHub의 Palette를 clone 해 보자 (git 기본 설치를 전제로 함)

$ cd ../playhub/

$ git clone git@github.com:playground-ko/palette.git

Initialized empty Git repository in /home/vagrant/playhub/palette/.git/

.. 중략 ..


$ ls - lart

drwxr-xr-x  5 vagrant vagrant 4096 2013-10-30 06:07 palette


// submodule에 대하여 초기화 하고 업데이트 한다 (Git 환경만들기 참조)

$ cd palette

$ git submodule init

Submodule 'backend' (git@github.com:playground-ko/palette.backend.git) registered for path 'backend'

Submodule 'frontend' (git@github.com:playground-ko/palette.frontend.git) registered for path 'frontend'

$ git submodule update

Initialized empty Git repository in /home/vagrant/playhub/palette/backend/.git/

.. 중략 ..

Submodule path 'backend': checked out 'f8276822e8a12a15f2af19e0c62cbd74a9172d84'

Initialized empty Git repository in /home/vagrant/playhub/palette/frontend/.git/

.. 중략 ..

Submodule path 'frontend': checked out 'e1b7201011321e1df2cc990c4eb2042c765c8a3c'


// playhub 디렉토리로 이동하여 bankend, frontend 저장소를 별도로 받아서 개발을 시작한다 

$ cd ..

$ git clone git@github.com:playground-ko/palette.backend.git

Initialized empty Git repository in /home/vagrant/playhub/palette.backend/.git/

.. 중략 ..

$ git clone git@github.com:playground-ko/palette.frontend.git

Initialized empty Git repository in /home/vagrant/playhub/palette.frontend/.git/

.. 중략 ..


  - yo/grunt/bower, generator-angular 를 설치 또는 업그레이드 하고, frontend 디렉토리로 이동하여 프로젝트를 만든다 

// yo를 설치하면 grunt와 bower가 같이 설치된다 

sudo npm install -g yo

// 현재 버전은 1.0.4 (2013.10.31 기준)

$ yo --version

1.0.0-rc.1.4

$ grunt --version

grunt-cli v0.1.9

grunt v0.4.1

$ bower --version

1.2.7


// 이미 설치되어 있다면 최신버전으로 업데이트  한다 

$ sudo npm update -g yo

$ sudo npm update -g grunt-cli

$ sudo npm update -g bower


// angular framework 설치

sudo npm install -g generator-angular


// angular 웹앱을 만든다 

$ cd  palette.frontend/

$ yo angular Palette


// 빌드하면 배포할 수 있는 dist 배포 디렉토리가 나온다. 

// dist는 온전한 html, css, js 파일들이고 이것은 어느 웹서버에 가져다 놓아도 구동이 된다

// 즉, 굳이 node.js위에 구동되지 않아도 됨 

// 기본적으로 build를 하면 관련 js 파일을 minification하여 사이즈를 줄여준다 

// Sublime Text에 Grunt build를 설정할 수 있다

$ grunt build

// karma 통하여 unit, e2e 테스트 수행

$ grunt test

// node.js 기반으로 서버가 열리면서 브라우져(Chrome)도 자동으로 열린다 

$ grunt server


// dist 배포본은 python을 통하여 간단히 테스트 해 볼 수도 있다 

// 브라우져에서 8000 port를 열어서 배포본이 정상적으로 작동하는지 아이체킹

$ cd dist 

python -m SimpleHTTPServer 8000


이제 Frontend를 Yeoman을 통하여 개발해 보자



4. BootFlat 적용하기 

  - yeoman의 generator-bootstrap은 v2.* 버전이 적용되어 있다. Bootstrap v3.* 버전이 적용된 BootFlat 확장판을 적용하기 위한 방법은 기존 블로깅을 참조한다. 

  - Twitter Bootstrap 고도화



<참조>

  - Yeoman을 통해 AngularJS 프로젝트 자동 구성하기

  - nvm 설치 방법

  - GitHub을 위한 SSH 키 생성방법

  - Sublime Text에 Grunt build 설정하기

  - BootFlat Homepage

posted by 윤영식
2013. 9. 25. 09:16 My Services/Smart Visualization

SPA 방식의 개발을 위해서는 Client에 MV* Framework을 선택해야 한다. 초창기는 Backbone.js(이하, 백본)를 많이 사용하였고, 구현체로 Trello가 있으니 해당 서비스의 아키텍쳐를 참조해 보자. 그리고 SKT에서 코너스톤이라는 이름의 Framework도 백본을 사용하여 "웹앱"을 만들 수 있도록 안드로이드/iOS용 런타임 환경도 제공한다. 백본은 가벼우면서 광범위하게 많이 사용을 하고 있지만 개발 복잡성 비교에서 중간정도에 위치한다. 


<Trello 아키텍쳐>



브라우져에서 동작하는 애플리케이션의 템플릿이 .html 이면서 <chart ../> 와 같이 사용자 정의 html tag를 사용하여 View단을 좀 더 단순화 및 컴포넌트화 할 수 있는 AngularJS를 사용하기로 한다. AngularJS에는 여러 장점이 있지만 "웹 애플리케이션을 견고하게 만드는 방법" 블로깅을 통해 백본대신 왜 AngularJS를 선택했는지 갈음한다. AngularJs 프레임워크 기반의 SPA 개발을 위하여 쉽게 접근하는 방법은 도구를 통하여 하는 것인데, 오스마니님이 개발한 Yeoman을 통하여 AngularJS기반 프로젝트를 쉽게 구성할 수 있다. 



1. Yeoman 사용하기

  - 사전에 NodeJS 최신버전이 설치되어 있어야 한다. 

    설치후 npm (Node Package Manager)를 통하여 Yeoman(이하, yo)을 설치함

  - Yo 설치하기  : 가이드를 따라서 설치하면 된다 

    + yo : angular, express 등 관련 framework에 대한 scaffolding 프로젝트를 자동으로 만들어 주는 기능을 한다 

              generator-angular, generator-express와 같이 generator-*가 앞에 붙는다. npm 통하여 설치함 

              generator 만드는 방법은 "generator-angular와 express 연동하기" 블로그 참조한다 

    + bower : client단의 필요한 컴포넌트를 자동설치할 수 있다. 의존성관계 bower.json 파일에 설정한다. npm 과 유사함

    + grunt : 개발된 소스를 테스트, 빌드하는 javascript의 ant과 같은 역할을 한다. Gruntfile.js 에 설정한다 

    


  - yo 설치후 "yo -h" 수행하면 설치된 generator 목록을 볼 수 있다. 또는 yo라고 수행해도 된다 (보여지는 형식만 틀리다)

// generator와 관련된 MUST HAVE generator

$ sudo npm install -g generator-generator


// angularjs 관련 generator 설치 

$ sudo npm install -g generator-angular


// AngularJS 관련 scaffolding 명령 목록 

$ yo -h 

Angular

  angular:app  (default : angular) 

  angular:common

  angular:constant

  angular:controller

  angular:decorator

  angular:directive

  angular:factory

  angular:filter

  angular:main

  angular:provider

  angular:route

  angular:service

  angular:value

  angular:view


// express generator도 설치하자 

sudo npm install -g generator-express


* 여기서 잠깐!

만일 사용하는 OS가 Windows라면 지금 당장 Linux를 설치해서 사용한다. 우리가 배포하고 서비스하는 서버는 Cloud환경일 가능성이 다분히 높기 때문이다. Windows Server같은 곳에서 Node.js를 운영하는 것은 상상조차 하고 싶지 않다. 

  - Vagrant를 Windows에 설치해서 쉽게 Linux환경에 접근토록 하자



2. AngularJS 스케폴딩 만들기

  - yo를 통하여 AngularJS 기반의 SPA 프로젝트를 만든다. 여기에는 Node.js로 동작하는 서버 코드는 생성되지 않는다 

  - GitHub에 SmartVisualization 라고 생성을 한다. 각자의 계정에 만든다 

// GitHub의 저장소 clone 하고 angular 스케폴딩 명령 수행

$ git clone https://github.com/<자신의 아이디>/SmartVisualization.git  SmartVisualization

$ cd SmartVisualization

$ yo angular:app SmartVisualization

[?] Would you like to include Twitter Bootstrap? Yes

[?] Would you like to use the SCSS version of Twitter Bootstrap with the Compass CSS Authoring Framework? No

[?] Which modules would you like to include? (Press <space> to select)

❯⬢ angular-resource.js

 ⬢ angular-cookies.js

 ⬢ angular-sanitize.js


... 모듈들 자동 설치 중략 ...


// npm : package.json

// bower : .bowerrc, bower.json

// grunt : Gruntfile.js

// test 도구인 karma: karma*

// git 관련 : .git*

$ ls -alrt

-rw-r--r--   1 nulpulum  staff    11  2 21  2013 .gitattributes

-rw-r--r--   1 nulpulum  staff   415  4 16 00:02 .editorconfig

-rw-r--r--   1 nulpulum  staff   394  6 10 21:31 .jshintrc

-rw-r--r--   1 nulpulum  staff    56  6 10 21:31 .gitignore

-rw-r--r--   1 nulpulum  staff    44  6 10 21:31 .bowerrc

-rw-r--r--   1 nulpulum  staff   120  7 15 06:32 .travis.yml

-rw-r--r--   1 nulpulum  staff  1304  8 12 05:33 karma.conf.js

-rw-r--r--   1 nulpulum  staff  1348  8 12 05:33 karma-e2e.conf.js

drwxr-xr-x   5 nulpulum  staff   170  9 25 08:51 ..

drwxr-xr-x   5 nulpulum  staff   170  9 25 09:04 test

-rw-r--r--   1 nulpulum  staff   404  9 25 09:04 bower.json

-rw-r--r--   1 nulpulum  staff  8217  9 25 09:04 Gruntfile.js

drwxr-xr-x  12 nulpulum  staff   408  9 25 09:04 app

drwxr-xr-x  16 nulpulum  staff   544  9 25 09:04 .

drwxr-xr-x  39 nulpulum  staff  1326  9 25 09:04 node_modules

-rw-r--r--   1 nulpulum  staff  1466  9 25 09:05 package.json


  - Yeoman을 통하여 AngularJS 프로젝트 스케폴딩을 만들었다면 Grunt명령을 통하여 테스팅을 위한 서버를 기동할 수 있다 

// 명령을 수행하면 Node.js를 기반으로 서버가 기동하고 9000 port로 Chrome브라우져가 자동 실행되어 호출된다

// Grunt는 Java의 Ant와 같은 도구이다 

$ grunt server

Running "server" task


Running "clean:server" (clean) task

Cleaning .tmp...OK


Running "concurrent:server" (concurrent) task


    Running "copy:styles" (copy) task

    Copied 2 files

    

    Done, without errors.


    Elapsed time

    copy:styles  15ms

    Total        16ms


    Running "coffee:dist" (coffee) task


    Done, without errors.


    Elapsed time

    coffee:dist  10ms

    Total        10ms


Running "autoprefixer:dist" (autoprefixer) task

File ".tmp/styles/bootstrap.css" created.

File ".tmp/styles/main.css" created.


Running "connect:livereload" (connect) task

Started connect web server on localhost:9000.


Running "open:server" (open) task


Running "watch" task

Waiting...


// 브라우져 자동 실행 및 9000 포트 자동 호출된 결과물 


다음은 AngularJS 에 대하여 알아보자



<참조>

  - Client MV* Framework에대한 ToDoMVC 개발 복잡성 비교

  - Yeoman의 generator-angular와 express 연동하기

  - Vagrant를 통하여 개발환경 꾸미기

posted by 윤영식
2013. 4. 25. 11:45 Dev Environment/Build System

구글 플러스 보다가 여맨 개발자인 오스마니님의 Generator 문서 정리했다는 글을 보고 얼른 들어와 봤다. AngularJS를 하면서 Yeoman을 필수로 상요하고 있어서 필요한 모듈이나 라이브러리를 스케폴딩하도록 수정하고 있기 때문에 어째 잘 정리되었는지 살펴본다 



1. 소개

  - 제너레이터의 종류는 두가지이다 

    + Boilerplate : 프로젝트 껍데기를 만들어준다. 프로젝트 구조화에 도움 예) HTML5 boilerplate, Twitter Bootstrap boilerplate 등 

    + Scaffolder : boilerplate외에 빌드시스템, sub-generator, 의존성관리, 자동화 업무수행(workflow)을 한다 

  - 공식적인 제너레이터들을 사용하거나 fork해서 수정 사용해도 된다 예) AngularJS+Express 연동



2. Boilerplate  Generator 만들기 

  - awesome 이란 걸 만들어 보자 

    + 원문은 사실 왜 이렇게 명령을 하는지 친절하게 설명은 하지 않고 있다. 기본은 알고 있다는 전제로 간단히 설명했다 

    + html5 boilerplate generator를 만들어 본다 

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

// yeoman의  boilerplate generator를 가장 먼저 클론한다

$ git clone git://github.com/addyosmani/generator-boilerplate.git

Cloning into 'generator-boilerplate'...

.. 중략..

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


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

// git submodule add 명령(참조) 을 통하여 html5 bp 클론

// 여기서 중요한 것은 app/templates 으로 반드시 지정

// app/templates은 yeoman의 복제 템플릿이 놓이는 위치

// 다른 방법 : yo boilerplate https://github.com/h5bp/html5-boilerplate/archive/master.tar.gz

$ cd generator-boilerplate/

$ generator-boilerplate> git submodule add git://github.com/h5bp/html5-boilerplate.git app/templates

Cloning into 'app/templates'...

remote: Counting objects: 4955, done.

..중략...

warning: LF will be replaced by CRLF in .gitmodules.

The file will have its original line endings in your working directory.


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

// templates 밑으로 html5-boilerplate 코드가 들어감

$ tree

.

├── README.md

├── app

│   ├── index.js

│   └── templates

│       ├── 404.html

│       ├── CHANGELOG.md

│       ├── CONTRIBUTING.md

│       ├── LICENSE.md

│       ├── README.md

│       ├── apple-touch-icon-114x114-precomposed.png

│       ├── apple-touch-icon-144x144-precomposed.png

│       ├── apple-touch-icon-57x57-precomposed.png

│       ├── apple-touch-icon-72x72-precomposed.png

│       ├── apple-touch-icon-precomposed.png

│       ├── apple-touch-icon.png

│       ├── crossdomain.xml

│       ├── css

│       │   ├── main.css

│       │   └── normalize.css

│       ├── doc

│       │   ├── TOC.md

│       │   ├── crossdomain.md

│       │   ├── css.md

│       │   ├── extend.md

│       │   ├── faq.md

│       │   ├── html.md

│       │   ├── js.md

│       │   ├── misc.md

│       │   └── usage.md

│       ├── favicon.ico

│       ├── humans.txt

│       ├── img

│       ├── index.html

│       ├── js

│       │   ├── main.js

│       │   ├── plugins.js

│       │   └── vendor

│       │       ├── jquery-1.9.1.min.js

│       │       └── modernizr-2.6.2.min.js

│       └── robots.txt

└── package.json


7 directories, 34 files


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

// git 상태정보 .gitmodule 모듈 환경파일 자동 생성됨 

$ git status

warning: LF will be replaced by CRLF in .gitmodules.

The file will have its original line endings in your working directory.

# On branch master

# Changes to be committed:

#   (use "git reset HEAD <file>..." to unstage)

#

# modified:   .gitmodules

# new file:   app/templates

#


$ cat .gitmodules

[submodule "app/templates"]

path = app/templates

url = git://github.com/h5bp/html5-boilerplate.git


$ cat .git/config

[core]

repositoryformatversion = 0

filemode = true

bare = false

logallrefupdates = true

ignorecase = true

precomposeunicode = false

[remote "origin"]

url = git://github.com/addyosmani/generator-boilerplate.git

fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]

remote = origin

merge = refs/heads/master

[submodule "app/templates"]

url = git://github.com/h5bp/html5-boilerplate.git


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

// Node.js는 기본 설치되어 있어야 한다

// node package manager를 통하여 yeoman관련 모듈설치

$ npm install


  - 원문에서 다음으로 자신이 원하는 프로젝트를 만들라고 하는데, 중간과정이 생략되었다. 이제 만든 generator-boilerplate  사용법을 보자 

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

// awesome이라는 명칭으로 변경한다

// yeoman 명명규칙으로 generator- prefix는 꼭 붙인다

// package.json 과 README.md 파일 내역을 수정한다 

$ mv generator-boilerplate generator-awesome

$ cd generator-awesome

$ vi package-json  // 이름과 버전 및 설명을 수정

$ vi README.md   // 내용 수정


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

// yo 명령은 node를 기반으로 한다. 

// 따라서 global하게 찾을 수 있게 node_modules 밑에

// symbolic link을 걸어주었다

$ cd /usr/local/lib/node_modules

$ sudo ln -s <Your Directory Full Path>/generator-awesome  generator-awesome

Password:

/usr/local/lib/node_modules> ls -alrt

 ..중략..

drwxr-xr-x  13 nobody  staff   442  4 12 13:45 generator-karma

drwxr-xr-x  18 nobody  staff   612  4 12 14:30 npm

drwxr-xr-x  15 nobody  staff   510  4 12 14:31 bower

drwxr-xr-x  13 nobody  staff   442  4 12 15:03 grunt-cli

drwxr-xr-x   7 nobody  staff   238  4 18 09:57 yo

drwxr-xr-x  26 nobody  staff   884  4 18 10:42 generator-angular

drwxr-xr-x  16 nobody  staff   544  4 18 16:59 grunt-init

drwxr-xr-x  10 nobody  staff   340  4 19 23:46 grunt-express

drwxr-xr-x  16 nobody  staff   544  4 19 23:46 grunt

drwxr-xr-x  16 nobody  staff   544  4 22 11:04 generator-express

drwxr-xr-x  14 nobody  staff   476  4 22 11:31 generator-generator

drwxr-xr-x  13 nobody  staff   442  4 22 11:44 generator-bootstrap

lrwxr-xr-x   1 root    wheel    48  4 22 17:08 generator-angular-sd -> /Users/development/generator-angular-sd

drwxr-xr-x  16 nobody  staff   544  4 24 15:15 jshint

lrwxr-xr-x   1 root    wheel    52  4 25 10:40 generator-awesome -> /Users/prototyping/yeoman/generator-awesome


$ yo -h

Please choose a generator below.

Awesome

  awesome:app


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

// 자신의 프로젝트 디렉토리를 만든다 

// 프로젝트 디렉토리로 이동하여 yo awesome 수행! 

$ mkdir  dowonProject 

$ cd dowonProject

 yo awesome  (또는 yo awesome:app)

Generating from Generator Boilerplate v0.1.4...

   create .gitattributes

 .. 중략 ..

   create js/vendor/jquery-1.9.1.min.js

   create js/vendor/modernizr-2.6.2.min.js

   create robots.txt



3. Scaffolding Generator 만들기 

  - generator-generator 를 사용하여 만든다 

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

// 사실 yo, bower, grunt-cli를 설치해야 한다 (참조)

// 스케폴딩 제너레이터를 만들어 주는 제너레이터 설치

$ sudo npm install -g yo

$ sudo npm install -g generator-generator


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

// 사용할 수 있는 yeoman generator list를 보자 

$ yo -h 

Generator

  generator

  generator:app

  generator:subgenerator


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

// 스케폴딩 제너레이터 디렉토리를 만들고 명령수행

// generator- 는 반드시 붙인다. 뒤에 오는 이름에는 

// 절대로 - 를 사용하지 않는다. underbar 사용함!

$ mkdir generator-angularjs_express

$ cd generator-angularjs-express

$ yo generator:app

     _-----_

    |       |

    |--(o)--|   .--------------------------.

   `---------´  |    Welcome to Yeoman,    |

    ( _´U`_ )   |   ladies and gentlemen!  |

    /___A___\   '__________________________'

     |  ~  |

   __'.___.'__

 ´   `  |° ´ Y `


Would you mind telling me your username on Github? (someuser) ysyun

What's the base name of your generator? (generator-angularjs_express)

   create package.json

   create .editorconfig

   ..중략..

   create app/templates/_component.json

npm http GET https://registry.npmjs.org/yeoman-generator


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

// app 밑으로 index.js 파일과 templates 폴더 생성

// yo 는 generator 밑의 폴더(여기선 app하나) 밑에 기본

// index.js 를 찾고 해당 파일을 수행한다 

// 즉, app가 있으므로 향후 명령은 yo angularjs-express:app 가 된다 

//

// mocha와 yeoman-generator가 설치됨

tree

.

├── LICENSE

├── README.md

├── app

│   ├── index.js

│   └── templates

│       ├── _component.json

│       ├── _package.json

│       ├── editorconfig

│       ├── jshintrc

│       └── travis.yml

├── node_modules

│   ├── mocha

│   └── yeoman-generator

├── package.json

└── test

    ├── test-creation.js

    └── test-load.js


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

// app이외의 다른 generator를 만들고 싶다면 subgenerator 이용

$ yo generator:subgenerator dowon

   create dowon/index.js

   create dowon/templates/somefile.js


$ cat index.js

'use strict';

var util = require('util');

var yeoman = require('yeoman-generator');


var DowonGenerator = module.exports = function DowonGenerator(args, options, config) {

  // By calling `NamedBase` here, we get the argument to the subgenerator call

  // as `this.name`.

  yeoman.generators.NamedBase.apply(this, arguments);


  console.log('You called the dowon subgenerator with the argument ' + this.name + '.');

};


util.inherits(DowonGenerator, yeoman.generators.NamedBase);


DowonGenerator.prototype.files = function files() {

  this.copy('somefile.js', 'somefile.js');

};


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

// angularjs-express라고 만든 Scaffoliding generator 사용하기 

/usr/local/lib/node_modules> sudo ln -s <your full path>/generator-angularjs_express generator-angularjs_express

/usr/local/lib/node_modules> yo -h


Angularjs_express

  angularjs_express:app

  angularjs_express:dowon


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

// 이제 명령어를 사용할 수 있다

$ yo angularjs_express:app 또는 dowon


다음에는 index.js 확장하는 방법을 알아보자 



<참조> 

  - 원문 : http://yeoman.io/generators.html

posted by 윤영식
2013. 4. 22. 23:42 Dev Environment/Build System

Yeoman은 generator-* 를 통하여 스케폴딩 코드 껍데기를 만들어준다. 이중 angular를 위해서 generator-angular와 테스트를 위한 generator-karma등 다양한 generator가 있고, 사용자가 원하는 generator를 만들 수가 있다. generator-angular안에는 클라이언트단만을 고려한 스케폴딩만 존하여 generator-angular를 GitHub에서 forking하여 ExpressJS를 붙여 프로젝트에 실제 필요한 스케폴딩을 만들어 본다



1) generator-angular forking

  - https://github.com/yeoman/generator-angular 에서 fork를 했다


  - 로컬로 복제한다 

    + git clone https://github.com/ysyun/generator-angular 

  - yeoman 1.0 beta 부터는 명령이 yo 로 바뀌었다. 포스팅 보고서 설치를 한다

  - yo 로 수행할 수 있는 generator 목록을 보자 

    + 만일 generator-angular 를 설치했다면 Angular 라고 나온다

    + Naming convention 규칙에 따라서 generator-[Name] 으로 generator가 만들어지고 [Name]만을 취한다

    + generator들은 npm install -g 옵션으로 설치하여 맥(Mac) 기준으로 /usr/local/lib/node_modules/* 밑에 설치된다 

$ yo --help

 Usage: yo GENERATOR [args] [options]


General options:

  -h, --help     # Print generator's options and usage

  -f, --force    # Overwrite files that already exist


Please choose a generator below.


Angular  <<=== generator-angular 

  angular:app

  angular:common

  angular:controller

  angular:directive

  angular:filter

  angular:main

  angular:route

  angular:service

  angular:view


Bootstrap

  bootstrap:app


Express

  express:app

  express:basic

  express:common


Generator

  generator

  generator:app

  generator:subgenerator


Karma

  karma:app


Mocha

  mocha:app

  mocha:generator


Webapp

  webapp:app


$ cd /usr/local/lib/node_modules && ls -alrt

drwxr-xr-x  13 nobody  staff   442  4 12 13:45 generator-karma

drwxr-xr-x  18 nobody  staff   612  4 12 14:30 npm

drwxr-xr-x  15 nobody  staff   510  4 12 14:31 bower

drwxr-xr-x  13 nobody  staff   442  4 12 15:03 grunt-cli

drwxr-xr-x   7 nobody  staff   238  4 18 09:57 yo

drwxr-xr-x  26 nobody  staff   884  4 18 10:42 generator-angular

drwxr-xr-x  16 nobody  staff   544  4 18 16:59 grunt-init

drwxr-xr-x  10 nobody  staff   340  4 19 23:46 grunt-express

drwxr-xr-x  16 nobody  staff   544  4 19 23:46 grunt

drwxr-xr-x  12 nobody  staff   408  4 22 10:20 coffee-script

drwxr-xr-x  16 nobody  staff   544  4 22 11:04 generator-express

drwxr-xr-x  14 nobody  staff   476  4 22 11:31 generator-generator

drwxr-xr-x  13 nobody  staff   442  4 22 11:44 generator-bootstrap

drwxr-xr-x  29 root    wheel   986  4 22 15:53 generator-angular_dowon

lrwxr-xr-x   1 root    wheel    48  4 22 17:08 generator-angular-sd -> /Users/nulpulum/development/generator-angular-sd


  - fork한 generator-angular를 로컬머신에서 generator-angular-sd 라는 별도 디렉토리에 받고, /usr/local/lib/node_modules/밑에 symbolic link 를 걸어주었다. 

  - 다시 yo --help를 해보면 하기와 같이 angular-sd가 나온다.

    + 앞으로 명령을 yo angular-sd:app 또는 yo angular-sd:express 명령을 치면 스케폴딩 소스가 생기는 것이다. 

Angular-sd

  angular-sd:app

  angular-sd:common

  angular-sd:controller

  angular-sd:directive

  angular-sd:express  <<=== 만들 대상 

  angular-sd:filter

  angular-sd:main

  angular-sd:route

  angular-sd:service

  angular-sd:view



2) Angular Express Generator 만들기 

  - https://github.com/hmalphettes/yeoman-angular-express-example  샘플을 참조해서 작성을 시도해 보았다 

  - 일단 Yeoman 스케폴딩 방식에 대해서 알아보자 (Yeoman Wiki 설명문)

    + Yeoman은 디렉토리별로 index.js 파일을 기본으로 참조한다 

    + 디폴트 디렉토리는 app 이다

    + 그렇다면 다음과 같은 구조가 될 것이다. 즉, yo --help 했을 때 최상위 generator-angular-sd 밑의 디렉토리명이 옵션이 된다

    + 초기 generator를 만드는 도구는 npm install -g generator-generator로 설치한다 (직접 만들고 싶다면 설치,우선 참조만)

angular-sd/

    app/index.js

    common/index.js

    controller/index.js

    ... 중략 ...

    view/index.js


  - yo angular-sd:express 를 수행하려면  generator-angular-sd/express/  디렉토리를 만들고, index.js를 만든다

    + 코드는 yeoman-generator 를 사용한다 

    + 파란색 부분이 중요하다. 모든 스케폴딩 코드 템플릿을 generator-angular-sd/templates/ 밑에 관리하는 것이 일반적이다

    + templates 디렉토리 밑에 express 디렉토리를 만든다  

// index.js

'use strict';

var path = require('path');

var util = require('util');

var yeoman = require('yeoman-generator');


module.exports = ExpressGenerator;


function ExpressGenerator() {

  yeoman.generators.Base.apply(this, arguments);

}


util.inherits(ExpressGenerator, yeoman.generators.Base);


ExpressGenerator.prototype.setupEnv = function setupEnv() {

  this.sourceRoot(path.join(__dirname, '../templates/express'));

  this.directory('.', '.', true);

};


  - templates/express/ 디렉토리 밑에 express 관련 views, routes, public 등을 놓아도 되지만 여기서는 app.js 만들 놓는다. 

    + yo angular-sd를 먼저 수행하면 app 디렉토리가 express의 public 정적 디렉토리 파일 역할을 해준다. 

    + Angular를 사용한다는 것은 SPA이기 때문에 index.html 하나만 두고 전부 partial html로 사용할 것이다.

    + 따라서 Express의 jade는 사용하지 않을 것이다. app.js 파일 하나만 만듦

    + 정적 파일 디렉토리를 app로 지정하고, '/' 요청은 '/app/index.html'로 보냄. index.html 은 angular 파일이다 

var express = require('express')

  , routes = require('./server/routes')

  , http = require('http')

  , path = require('path')

  , fs = require('fs');


var app = express();


app.configure(function(){

  app.set('port', process.env.PORT || 3000);

  // angular /app/views

  // app.set('views', __dirname + '/server/views');

  // app.set('view engine', 'jade');

  app.use(express.favicon());

  app.use(express.logger('dev'));

  app.use(express.bodyParser());

  app.use(express.methodOverride());

  app.use(app.router);

  // angular app == public dir

  app.use(express.static(path.join(__dirname, 'app')));

});


app.configure('development', function(){

  app.use(express.errorHandler());

});


app.get('/', function(req, res) {

  res.sendfile(__dirname + '/app/index.html');

});

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

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


http.createServer(app).listen(app.get('port'), function(){

  console.log("Express server listening on port " + app.get('port'));


  - package.json 내역에 express 포함시킴 

    + 스케폴딩 위치는 generator-angular-sd/templates/common 밑에 package.json 파일이 존재한다 (수정할 파일)

    + package.json의 내역을 참조하여 node_modules에 필요 모듈을 다운로드 한다 

    + 맨 마지막에 fork 하였던 https://github.com/ysyun/generator-angular 을 travis ci에 연동하기 위해 scripts{ test:...} 넣음

    + grunt express-server를 위하여 grunt-express를 넣음 

{

  "name": "anulgar-express",

  "description": "Grunt task for running an Express Server for Smart Dashboard",

  "homepage": "http://mobincon.tistory.com",

  "author": {

    "name": "Yun Young Sik",

    "email": "ysyun@yuwin.co.kr"

  },

  "repository": {

    "type": "git",

    "url": "https://github.com/ysyun/generator-angular"

  },

  "version": "0.0.1",

  "scripts": {

    "test": "grunt travis --verbose"

  },

  "dependencies": {

    "express": "~3.2.0",

    "jade": "~0.29.0"

  },

  "devDependencies": {

    "grunt": "~0.4.1",

    "grunt-contrib-copy": "~0.4.0",

    "grunt-contrib-concat": "~0.1.3",

    "grunt-contrib-coffee": "~0.6.4",

    "grunt-contrib-uglify": "~0.2.0",

    "grunt-contrib-compass": "~0.1.3",

    "grunt-contrib-jshint": "~0.3.0",

    "grunt-contrib-cssmin": "~0.5.0",

    "grunt-contrib-connect": "~0.2.0",

    "grunt-contrib-clean": "~0.4.0",

    "grunt-contrib-htmlmin": "~0.1.1",

    "grunt-contrib-imagemin": "~0.1.2",

    "grunt-contrib-livereload": "~0.1.2",

    "grunt-bower-requirejs": "~0.4.1",

    "grunt-usemin": "~0.1.10",

    "grunt-regarde": "~0.1.1",

    "grunt-rev": "~0.1.0",

    "grunt-karma": "~0.3.0",

    "grunt-open": "~0.2.0",

    "matchdep": "~0.1.1",

    "grunt-google-cdn": "~0.1.1",

    "grunt-ngmin": "~0.0.2",

    "grunt-express": "git://github.com/hmalphettes/grunt-express.git",

    "socket.io": "*"

  },

  "engines": {

    "node": ">=0.8.0"

  }

}


  - 명령을 수행해 본다

    + yo angular-sd  : angular-sd:app 와 동일하고 generator-angular-sd/app/index.js 설정한 내역을 수행한다 

    + yo angular-sd:express : express 관련 파일을 스케폴딩한다. 초기에 jade도 넣었다가 그냥 app.js 만 놔두었다 

$ mkdir angular-express

$ cd angular-express

$ yo angular-sd

  ... 쭉 엔터치고 한참 의존관계있는 파일을 받는다 ...

$ ls -alrt

drwxr-xr-x   4 nulpulum  staff   136  4 22 23:15 ..

drwxr-xr-x   4 nulpulum  staff   136  4 22 23:16 test

-rw-r--r--   1 nulpulum  staff  1491  4 22 23:16 package.json

-rw-r--r--   1 nulpulum  staff  1273  4 22 23:16 karma.conf.js

-rw-r--r--   1 nulpulum  staff  1134  4 22 23:16 karma-e2e.conf.js

-rw-r--r--   1 nulpulum  staff   360  4 22 23:16 component.json

-rw-r--r--   1 nulpulum  staff  8189  4 22 23:16 Gruntfile.js

-rw-r--r--   1 nulpulum  staff   409  4 22 23:16 .jshintrc

-rw-r--r--   1 nulpulum  staff    50  4 22 23:16 .gitignore

-rw-r--r--   1 nulpulum  staff    11  4 22 23:16 .gitattributes

-rw-r--r--   1 nulpulum  staff   415  4 22 23:16 .editorconfig

-rw-r--r--   1 nulpulum  staff    38  4 22 23:16 .bowerrc

drwxr-xr-x  12 nulpulum  staff   408  4 22 23:16 app

drwxr-xr-x  15 nulpulum  staff   510  4 22 23:16 .

drwxr-xr-x  30 nulpulum  staff  1020  4 22 23:17 node_modules


$ yo angular-sd:express

   create app.js



3) Grunt file 만들기

  - Express에 대해서 grunt를 통하여 test, build, preview를 수행하기 위하여 Gruntfile.js를 수정한다

     + generator-angular-sd/templates/common/Gruntfile.js 가 수정파일이다 

     + package.json 파일 에서  "grunt-express": "git://github.com/hmalphettes/grunt-express.git" 꼭 들어가야 함

  - Gruntfile.js : 기존 generator-angular의 Gruntfile.js에서 express 관련 내역을 첨부한다 (파일참조)

'use strict';

var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;

var mountFolder = function (connect, dir) {

  return connect.static(require('path').resolve(dir));

};

var path = require('path');


module.exports = function (grunt) {

  // load all grunt tasks

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);


  // configurable paths

  var yeomanConfig = {

    app: 'app',

    dist: 'dist',

    server: 'server'

  };


  try {

    yeomanConfig.app = require('./component.json').appPath || yeomanConfig.app;

  } catch (e) {}


  grunt.initConfig({

    yeoman: yeomanConfig,

    watch: {

      coffee: {

        files: ['<%%= yeoman.app %>/scripts/{,*/}*.coffee'],

        tasks: ['coffee:dist']

      },

      coffeeTest: {

        files: ['test/spec/{,*/}*.coffee'],

        tasks: ['coffee:test']

      },

      compass: {

        files: ['<%%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],

        tasks: ['compass']

      },

      livereload: {

        files: [

          '<%%= yeoman.app %>/{,*/}*.html',

          '{.tmp,<%%= yeoman.app %>}/styles/{,*/}*.css',

          '{.tmp,<%%= yeoman.app %>}/scripts/{,*/}*.js',

          '<%%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',

          '<%%= yeoman.server %>'

        ],

        tasks: ['livereload']

"Gruntfile.js" [dos] 349L, 8192C

        ],

        tasks: ['livereload']

      }

    },

    connect: {

      options: {

        port: 9000,

        // Change this to '0.0.0.0' to access the server from outside.

        hostname: 'localhost'

      },

      livereload: {

        options: {

          middleware: function (connect) {

            return [

              lrSnippet,

              mountFolder(connect, '.tmp'),

              mountFolder(connect, yeomanConfig.app)

            ];

          }

        }

      },

      test: {

        options: {

          middleware: function (connect) {

            return [

              mountFolder(connect, '.tmp'),

              mountFolder(connect, 'test')

            ];

          }

        }

      }

    },

    express: {

      livereload: {

        options: {

          port: 9000,

          bases: [ path.resolve('.tmp'), path.resolve(yeomanConfig.app) ],

          monitor: {},

          debug: true //,

          // server: path.resolve('/app')

        }

      },

      test: {

        options: {

          port: 9000,

          bases: [ path.resolve('.tmp'), path.resolve(yeomanConfig.app) ],

          port: 9000,

          bases: [ path.resolve('.tmp'), path.resolve(yeomanConfig.app) ],

          monitor: {},

          debug: true //,

          // server: path.resolve('/app')

        }

      }

    },


  ... 중략 ...

  grunt.registerTask('default', ['build']);



  // for express

  grunt.registerTask('express-server', [

    'clean:server',

    'coffee:dist',

    'compass:server',

    'livereload-start',

    'express:livereload',

    'open',

    'watch'

  ]);


  grunt.registerTask('express-test', [

    'clean:server',

    'coffee',

    'compass',

    'connect:test',

    'karma'

  ]);


  grunt.registerTask('travis', ['jshint', 'test']);


  - 명령 수행하기 

    + grunt express-test : 테스트 

    + grunt : 빌드

    + grunt express-server : 미리보기 수행


    + 명령을 수행하면 자동으로 브라우져가 뜨면 성공



모든 것이 성공했다면 Remote Repository로 push한다. 그리고 Travis-ci에 forking한 프로젝트를 연결한다. 해당 부분은 다음에 보도록 하자.


결과물 : https://github.com/ysyun/generator-angular



<참조>

  - Travis CI 연동하기

  - 2013.11 Monthly Digest for Yeoman

  - Yeoman : generator-fullstack with angular and express

  - Yeoman : generator-mean with angular and express, mongodb, node

posted by 윤영식
2013. 4. 15. 11:44 Dev Environment/Build System

AngularJS 개발시 반복적인 작업을 제거하고 생산성을 높일 수 있는 통합 도구인 Yeoman의 사용법에 대해 알아보고, 처음 개발을 시작할 때 코드의 틀을 잡아 주는 몇가지 Seed 프로젝트를 통하여 어떤 구조로 애플리케이션을 만들어야 하는지 알아두자



1. 필요 요소 기술

  - UI : Bootstrap from Twitter  간혹 Foundation을 이용

  - Build/Preview : Grunt

  - Test : 기본은 Karma이고, Mocha를 사용하고 싶다면 Karma-Mocha Karma구동을 위한 Mocha adapter 존재

  - Package Management : Bower from Twitter

이들의 통합적으로 사용하기 위한 툴로 yeoman 을 설치하면 된다. 간단한 명령으로 AngularJS 관련 코드를 자동 생성하여 준다



2. Yeoman startup

  

yo - the scaffolding tool from Yeoman

bower - the package management tool  

  + component.json : 의존관계 설정

  + .bowerrc : 컴포넌트 설치 위치정보

grunt - the build tool 

  + Gruntfile.js : ant와 같은 수행 Task 정의

  + package.json : Node.js위에 구동되므로 package.json에 Grunt contributor 라이브러리 정의

karma - grunt test 시에 수행 

  + karma.conf.js : 로컬 테스트 환경

  + karma-e2e.conf.js : Real Browser 테스트 환경 즉, end-to-end (Client<->Server) 테스트 수행. 사용 port 8080


  - Yeoman command for AngularJS

// 설치 : grunt-cli, bower가 같이 설치된다 

npm install -g yo


// Yeoman을 위한 generator 설치 for AngularJS & Karam

// 하기 에러 내역 참조하여 generator-angular의 script-base.js 파일 수정

// Generator는 Yeoman에서 생성하는 boilerplate 나 scaffolding 코드를 만들어주는

// Yeoman의 플러그인이라 생각하면 된다. 이미 만들어지 Generator 목록이 존재한다

// > https://github.com/yeoman (generator-* 목록들)

// > Generator 만들기 참조

npm install -g generator-webapp generator-angular generator-karma


// 명령어 (프로젝트 디렉토리에서 수행)

yo angular 또는 yo angular:app 애플리케이션 생성

yo angular:controller myControllerName 컨트롤러 생성

yo angular:directive myDirectiveName 디렉티브 생성

yo angular:filter myFilterName 필터 생성

yo angular:service myServiceName 서비스 생성


  - yo angular:* 사용시 에러 발생 해결방법

예) yo angular:controller Test 수행시 하기와 같은 에러 발생

~/angularjs/sd_01> yo angular:controller Test


path.js:360

        throw new TypeError('Arguments to path.join must be strings');

              ^

TypeError: Arguments to path.join must be strings

    at path.js:360:15

    at Array.filter (native)

    at Object.exports.join (path.js:358:36)

    at Generator (/usr/local/lib/node_modules/generator-angular/script-base.js:38:29)

    at new Generator (/usr/local/lib/node_modules/generator-angular/controller/index.js:10:14)


==> 해결하기 

1) /usr/local/lib/node_modules/generator-angular/script-base.js 의 38 번째 줄 내용을 하기와 같이 수정함

 37     if (!this.options.coffee &&

 38       //this.expandFiles(path.join(this.appPath, '/scripts/**/*.coffee'), {}).length > 0) {  // 주석처리 

 39       this.expandFiles(path.join(process.cwd(), '/scripts/**/*.coffee'), {}).length > 0) {  // process.cwd() 로 바꿈

 40       this.options.coffee = true;

 41     }


2) 재수행 : 친절하게도 TestCase까지 자동 생성해 준다 

   ~/angularjs/sd_01> yo angular:controller Test

   create app/scripts/controllers/Test.js

   create test/spec/controllers/Test.js


  - Yeoman command for Bower : 의존관계 라이브러리에 대한 관리 담당 

// 명령어

bower search <dep> - search for a dependency in the Bower registry

bower install <dep>..<depN> - install one or more dependencies

bower list - list out the dependencies you have installed for a project

bower update <dep> - update a dependency to the latest version available


// 설치하기 

// .bowerrc 에 설정된 디렉토리로 다운로드된 라이브러리가 설치된다

$ bower install angular-ui

bower cloning git://github.com/angular-ui/angular-ui.git

bower cached git://github.com/angular-ui/angular-ui.git

bower fetching angular-ui

bower checking out angular-ui#v0.4.0

bower copying /Users/nulpulum/.bower/cache/angular-ui/bd4cf7fc7bfe2a2118a7705a22201834

bower installing angular-ui#0.4.0


$ cd app/components/

$ ls

angular angular-scenario es5-shim json3

angular-mocks angular-ui jquery


$ cd ../..

$ cat .bowerrc

{

    "directory": "app/components"

}


  - Yeoman command for Grunt : 프러덕션 빌드, 미리보기, 테스팅 

    + grunt는 task에 대한 여러 target들이 존재하는 구조이다. 

    + 명령을 grunt <task> 로 주면 task밑의 모든 target이 순서대로 수행된다

    + 명령을 grunt <task>:<target> 을 지정하여 특정 target만 수행할 수도 있다

    + task와 관련한 여러가지 Plugins 이 이미 만들어져 있고 직접 만들 수도 있다 (기존 Plugins 목록)

// 명령어

grunt test  - 테스트하기. run the unit tests for an app  

grunt server - 브라우져에서 보기. 변경사항 실시간 반영됨. preview an app you have generated (with Livereload)

grunt - 배포본 빌드하기.  build an optimized, production-ready version of your app  (warning 무시 옵션 --force 사용가능)


// 브라우져 미리보기 in app root folder

grunt server

// warning -jslint 같은- 무시하고 계속 build하기

grunt  --force 



3. 기본 코드 생성

  - Grunt-Express : Grunt와 Express 연동하기

  - Yeoman-Angular-Express : Yeoman을 이용하여 Angular project 생성한 후 Express와 통합하는 예제

  - Angular-Socket.io-Seed : Angular와 Socket.io를 접목 시키고자 할때 사용 (포스팅)



4. Addy Osmani 님이 이야기 하는 Automation Front-end workflow



결론적으로 Yeoman을 사용하여 기반 코드를 생성하고 빌드/테스팅 자동화를 한다. 그리고 필요한 코드들은 Seed 프로젝트를 참조하여 자기것으로 만들면 되겠다



<참조>

  - 원문 : Google, Twitter and AngularJS

  - 보다 많은 AngularJS와 BackboneJS에 대한 기사 in DailyJS

  - Grunt를 위한 express 플러그인 테스트

posted by 윤영식

AngularJS의 테스트툴로 Testacular를 사용하는데 명칭이 Karma로 바뀌었다. WebStorm에 설정하고 사용하는 방법을 알아보자 



1) Karma 설치하기

  - 홈페이지 : http://karma-runner.github.io/0.8/index.html

  - 선조건 : WebStorm 설치 및 Node.js 설치

  - Karma를 global로 설치 : npm install -g karma



2) Yeoman을 통한 Karma 환경설정 

  - 일반적으로 Yeoman을 통하여 스케폴딩 코드를 만들어 사용하는 것이 좋다 : Yeoman 홈페이지

  - yeoman 설치 : npm install -g yo grunt-cli bower

  - angular 프로젝트 만들기 : yo angular 또는 yo angular:app

    

    <자동 생성된 파일 및 디렉토리 구조>


  - 자동 생성된 karma 테스트 환경파일 : karma.conf.js

/ Karma configuration
 
// base path, that will be used to resolve files and exclude
basePath = '';
 
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'app/components/angular/angular.js',
'app/components/angular-mocks/angular-mocks.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
];
 
// list of files to exclude
exclude = [];
 
// test results reporter to use
// possible values: dots || progress || growl
reporters = ['progress'];
 
// web server port
port = 8080;
 
// cli runner port
runnerPort = 9100;
 
// enable / disable colors in the output (reporters and logs)
colors = true;
 
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
 
// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;
 
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
 
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 5000;
 
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;



3) WebStorm 환경설정

  - Server 설정하기 

    + 웹스톰 상단의 메뉴에서 Edit Configurations... 클릭

    

   + Node.js로 "Karma Server" 생성 : node.js, karma 설치 위치와 프로젝트 위치, 파라미터로 start 입력

      카르마의 테스트 서버 역할을 수행


    + Karma Run 생성 : 파라미터로 run 입력, 테스트를 수행한다 


    + Karma Debug : JavaScript Debug의 Remote로 생성 

       Remote URL 로 "http://localhost:8080/" 입력 



4) 테스트 수행하기 

  - Karma Server 시작하기 

    + Karma Server 선택하고 > 시작 버튼 클릭

    + 하단에 localhost:8080 으로 Listen하는 서버 구동됨 

    + 브라우져가 자동 실행 : 자동 실행안되면 브라우져 띄워서 8080 호출 



  - Karma Run 테스트 하기 

    + 테스트 수행하기 

    + 테스트가 정상 수행되면 SUCCESS가 나온다. 비정상이면 FAILED 메세지


  - Karma Debug

    + 소스 코드에 Break point를 만들고 디버그 수행

    + 테스트 해본 결과 잘 안되는데 향후 다시 한번 체크해 봐야 겠다



5) 테스트 코드 

  - BDD 방식의 테스트 코드를 짠다 

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

// 업무 코드 

'use strict';
 
var app = angular.module('eggheadioApp');
 
app.controller('MainCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
}) ;
 
app.factory('Data', function() {
return {message: 'shared data'}
});
 
app.filter('reverse', function(Data) {
return function(text) {
return text.split("").reverse().join("");
}
});


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

// 필터에 대한 테스트 코드 

describe('filter', function() {
beforeEach(module('eggheadioApp'));
 
describe('reverse', function() {
it('should reverse a string', inject(function(reverseFilter){ //reverse라는 Filte 파라미터
expect(reverseFilter('ABCD')).toEqual('DCBA');
}))
})
})



<참조>

  - 원본 : 유튜브 동영상

posted by 윤영식
prev 1 next