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

Publication

Category

Recent Post

Linear Regression의 Tensorflow 실습 강좌를 정리해 본다. 





Hypothesis & Cost function (예측과 비용 함수)



학습을 통해 cost function의 W와 b를 minimized하는게 목적이다. 

- step-1: Node라는 operation 단위를 만든다. 

- step-2: Session.run을 통해 operation한다. 

- step-3: 결과값을 산출한다. 



Tensorflow는 W, b를 Variable로 할당한다. Variable이란 tensorflow가 변경하는 값이다라는 의미이다. 


H(x) 가설 구하기


$ python3

>>> import tensorflow as tf

>>> x_train = [1,2,3]

>>> y_train = [1,2,3]

>>> W = tf.Variable(tf.random_normal([1]), name='weight')

>>> b = tf.Variable(tf.random_normal([1]), name='bias')

>>> hypothesis = x_train * W + b


cost(W,b) 구하기

- reduce_mean: 전체 평균

- square: 제곱

>>> cost = tf.reduce_mean(tf.square(hypothesis - y_train))



minimize Cost 구하기

- GradienDescent 를 사용해서 minimize한다.

>>> optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

>>> train = optimizer.minimize(cost)





Graph 실행하기


Tensorflow의 Session을 만들고, 글로벌 변수값을 초기화 해준다. 

- 2000번을 돌리면서 20번만다 출력해 본다. 

- sess.run(train): 학습을 시킨다. 처음 Cost를 랜덤하게 가면서 학습할 수록 값이 작이진다. 

   sess.run(W): 1에 수렴하고

   sess.run(b): 작은 값이 수렴한다.

>>> sess = tf.Session()

>>> sess.run(tf.global_variables_initializer())

>>> for step in range(2001):

...     sess.run(train)

...     if step % 20 == 0:

...             print(step, sess.run(cost), sess.run(W), sess.run(b))

...

0 8.145951 [-0.13096063] [-0.43867812]

20 0.0741704 [0.87371004] [0.00051325]

40 0.0009571453 [0.9702482] [0.04034551]

   ... 생략 ...

1960 2.7972684e-08 [0.9998057] [0.00044152]

1980 2.5414716e-08 [0.99981487] [0.00042076]

2000 2.3086448e-08 [0.9998234] [0.00040107]


위의 train은 여러 Node가 연결된 graph가 된다. 






Placeholder로 수행하기


수행시 필요할 때 값을 동적으로 전달하여 train해 본다. 

- X, Y placeholder를 만든다. 

- feed_dict를 통해 값을 할당한다.

>>> X = tf.placeholder(tf.float32)

>>> Y = tf.placeholder(tf.float32)

>>> for step in range(2001):

...     cost_val, W_val, b_val, _ = sess.run([cost, W, b, train], feed_dict={X: [1,2,3], Y:[1,2,3]})

...     if step % 20 == 0:

...             print(step, cost_val, W_val, b_val)

...

0 2.3086448e-08 [0.9998238] [0.00040011]

20 2.0964555e-08 [0.99983215] [0.00038142]






참조


- 김성훈교수님의 Linear Regression의 Tensorflow 실습

- Github 실습 코드

posted by 윤영식

성김님의 Linear Regression강좌 개념을 정리해 본다. 





Regression


- 범위에 관한 문제를 다룬다. 예측을 위한 기본적인 범위(x)를 통해 결과(y)에 대한 학습을 수행한다.

- Linear Regression 가설

  + 예: 학생이 공부를 많이 할 수록 성적이 높아지고, 훈련을 많이할 수록 기록이 좋아진다.

  + 아래와 같은 선을 찾는 것이 Linear Regression의 목적이다. 



H(x): 우리가 세운 가설

Wx: x 값

W, b 에 따라 선의 모양이 달라진다. 


예) 파란선: H(x) = 1 * x + 0

     노란선: H(x) = 0.5 * x + 2





Cost function


Linear Regression의 가설 선과 실제 값사이의 거리가 가까우면 잘 맞은 것이고, 아니면 잘 맞지 않은 것 일 수 있다. 이를 계산하는 산술식을 Cost(Lost) function이라 한다. 


- 예측값 H(x) 와 실제값 y 를 뺀 후 제곱을 한다. 제곱을 하는 이유는

  + 음수를 양수로 만들고

  + 차이에 대한 패널티를 더 준다. 

  cost = (H(x) - y) 2



수식에 대한 일반화



최종 목표는 W, b에 대해 가장 작은 값을 학습을 통해 찾는 것이다. - Goal: Minimize cost



minimize cost(W, b)





참조


- 김성훈교수님의 Linear Regression


posted by 윤영식

인프런의 모두를 위한 딥러닝을 공부하기 위해 Tensorflow를 설치해 보았다. 





Python 설치


python은 3.6.6을 설치한다. 3.7를 설치하고 Tensorflow를 설치하니 오류가 있었다. 


- Python v3.6.6설치

- pip python package 매니져를 업데이트 한다. 

curl https://bootstrap.pypa.io/get-pip.py | python


- virtualenv를 통해 특정 폴더에 대해 python version을 적용한다. 맨뒤 옵션이 특정 폴더이다.

$ virtualenv --system-site-packages -p python3 /Users/prototyping/machine-learning

$ cd machine-learning 

$ source ./bin/activate

(machine-learning)

~/prototyping/machine-learning

$




Tensorflow 설치


pip3를 이용해서 설치하는 방법이 실패하여 직접 download url을 입력한다. 

$ pip3 install --upgrade tensorflow (실패하면 아래 직접 URL 지정한다)

$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl



이제 시작해 보자...



참조


- Mac에서 virtualenv설치하기

posted by 윤영식
2017. 11. 15. 16:31 Meteor/Angular + Meteor

Angular CLI와 Meteor를 분리하고, Meteor를 단순히 API 서버로 사용하면서 Angular CLI는 Webpack Dev Server를 통해 4200 port로 브라우져에서 접속하면 Meteor Client는  3000 port를 통해 Meteor Server와 DDP 통신을 한다. (이전 블로그 참조) 이번에는 외부 라이브러리로 Clarity CSS Framework을 추가해 본다. 





Clarity CSS Framework


Twitter Bootstrap 처럼 CSS Framework이지만, clarity-ui, clarity-icon, clarity-angular 3개의 파트로 구분된다. clarity-ui는 css만 존재하고, clarity-icon은 이름처럼 아이콘에 관련된 부분이며, clarity-angular는 Angular 컴포넌트를 제공한다. 


  - Clarity 홈페이지

  - Clarity 소스

  - Clarity Seed 소스


// 아이콘 관련

$ npm install clarity-icons --save

$ npm install @webcomponents/custom-elements@1.0.0 --save


// UI CSS

$ npm install clarity-ui --save


// Angular 컴포넌트 

$ npm install clarity-angular --save


Clarity-Angular는 ngModule에서 import를 하면되고 나머지는 아래 장의 설명처럼 ng eject 이전 상태라면 angular-cli.json 에 설정하고, ng eject가 되었다면 webpack.config.js에 설정한다. 

// 메인 모듈

import { ClarityModule } from 'clarity-angular';


@NgModule({

imports: [

BrowserModule,

ClarityModule.forRoot()

],

...

})

export class AppModule {} 





@angular/cli 설정을 webpack.config.js로 옮기기


Clarity Seed를 보면 @angular/cli 기반으로 생성되어 있고, angluar-cli.json 안에 설정이 다음과 같이 되어있다. 진행중인 프로젝트에 Clarity icons, ui에 대한 외부 경로 설정을 한다. 

"styles": [
"styles.css",
"../node_modules/clarity-icons/clarity-icons.min.css",
"../node_modules/clarity-ui/clarity-ui.min.css"
],
"scripts": [
"../node_modules/@webcomponents/custom-elements/custom-elements.min.js",
"../node_modules/clarity-icons/clarity-icons.min.js"
],


해당 설정을 이전강좌의 Angular CLI + Meteor 프로젝트의 angular-cli.json을 넣고 ng eject를 하게 되면 다음과 같은 내용이 webpack.config.js에 자동 설정된다. 

  - Module안에 "exclude"와 "include"의 "src/styles.css"이 있는 모든 곳에 설정.

  - Plugin안에 new ConcatPlugin내용 추가

"module": {

{

"exclude": [

path.join(process.cwd(), "src/styles.css"),

path.join(process.cwd(), "node_modules/clarity-icons/clarity-icons.min.css"),

path.join(process.cwd(), "node_modules/clarity-ui/clarity-ui.min.css")

]

...

},

{

"include": [

path.join(process.cwd(), "src/styles.css"),

path.join(process.cwd(), "node_modules/clarity-icons/clarity-icons.min.css"),

path.join(process.cwd(), "node_modules/clarity-ui/clarity-ui.min.css")

]

...

}

...

},

"plugins": [

new ConcatPlugin({

"uglify": false,

"sourceMap": true,

"name": "scripts",

"fileName": "[name].bundle.js",

"fileToConcat": [

"node_modules/@webcomponents/custsom-elements/custom-elements.min.js",

"node_modules/clarity-icons/clarity-icons.min.js"

]

})

]





Clarity 테스트


Clarity CSS Framework은 업무적으로 요하는 컴포넌트 요소를 잘 정리해 놓았다. Application Layout에 대한 내역을 app.component.html에 추가한다. 

<div class="main-container">
<div class="alert alert-app-level">
Alert
</div>
<header class="header header-6">
Angular Meteor
</header>
<nav class="subnav">
Navigation
</nav>
<div class="content-container">
<div class="content-area">
Main
</div>
<nav class="sidenav">
Side Menu
</nav>
</div>
</div>


결과 화면





Clarity Icon 선택적으로 적용하기


plugins부분에 clarity-icons/clarity-icons.min.js 은 전체 아이콘을 포함하고 있다. 전체을 적용하지 않고, Core와 일부분만 적용하고 싶을 경우 다음과 같이 한다. 


// webpack.config.js에서 clarity-icons.min.js 제거

"plugins": [

new ConcatPlugin({

"uglify": false,

"sourceMap": true,

"name": "scripts",

"fileName": "[name].bundle.js",

"fileToConcat": [

"node_modules/@webcomponents/custsom-elements/custom-elements.min.js"

]

})

]


src/main.ts안에 import

import 'clarity-icons';
import 'clarity-icons/shapes/essential-shapes';
import 'clarity-icons/shapes/technology-shapes';


app.component.html안에 clr-icon 적용 테스트. 자세한 사항은 문서를 참조한다. Clarity-icons은  svg icon으로 사용자 정의 아이콘을 추가 할 수도 있다.

<div class="content-area">
<p><clr-icon shape="user" size="24"></clr-icon> lives in the Core Shapes set.</p>
<p><clr-icon shape="pencil" size="24"></clr-icon> lives in the Essential Shapes set.</p>
<p><clr-icon shape="tablet" size="24"></clr-icon> lives in the Technology Shapes set.</p>
</div>


posted by 윤영식
2017. 11. 8. 17:20 Meteor/Angular + Meteor

Ionic CLI 와 Meteor CLI 로 프로젝트 구성하기는 모바일 프로젝트를 진행할 때 사용하면 되고, 이번에는 Angular CLI 와 Meteor CLI를 통해 프로젝트 구성을 어떻게 하는지 살펴본다. 




Webpack 기반 프로젝트 초기화


Angular CLI를 통해 프로젝트를 생성한다. @angular/cli v1.5.0이 설치되고, webpack은 v3.8.1 이고, 내부적으로 @angular-devkit, @ngtools/webpack, @schematics등이 사용된다.

$ npm install -g @angular/cli


@angular/CLI 설치후 프로젝트를 생성한다. ng <command>의 상세 내용은 위키를 참조한다.

$ ng new <projectName>


Webpack 환경파일을 수정해야 하므로, eject 명령을 수행하고, 결과로 출력된 가이드에 따라 "npm install" 명령을 수행한다. eject 명령에 대한 다양한 options은 위키를 참조한다. eject시에 옵션을 주면 옵션이 적용된 webpack.config.js가 생성된다.

$ ng eject --aot --watch


====================================================

Ejection was successful.


To run your builds, you now need to do the following commands:

   - "npm run build" to build.

   - "npm test" to run unit tests.

   - "npm start" to serve the app using webpack-dev-server.

   - "npm run e2e" to run protractor.


Running the equivalent CLI commands will result in an error.

====================================================

Some packages were added. Please run "npm install".


$ npm install

$ npm run build


eject를 수행한 경우에는 "ng serve" 명령으로 테스트 서버를 뛰울 수 없다. package.json에 적용된 스크립트인 "npm start"를 수행하고 4200 port로 브라우져에서 

$ npm start


 10% building modules 3/3 modules 0 activeProject is running at http://localhost:4200/

webpack output is served from /

....


Webpack 환경 내역은 크게 entry, output, module (for loader), plugins 로 구성된다. (참조)

  - entry: 파일 위치

  - output: 결과 위치

  - module: css, .ts, .html 파일 관리 및 변환기 -> 자바스크립트 모듈로 만들기 위한 것. postfix가 "-loader" 이다. 로더는 파일단위 처리

  - plugins: 압축, 핫로딩, 복사, 옮기기등. 플러그인은 번들된 결과물을 처리





Angular CLI 환경에 Meteor 설정



이전 포스트처럼 루트에 api 폴더를 만들고 이를 Meteor의 백앤드로 사용토록 설정한다.

// webpack.config.js


const webpack = require('webpack');

...

resolve: {

  alias: {

    'api': path.resovle(__dirname, 'api/server'),

    ...

  }

}


externals: [ resolveExternals ],


plugins: [ ..., new webpack.ProvidePlugin({ __extends: 'typescript-extends' }) ],


node: { ..., __dirname: true }


// 맨 마지막에 넣음 

function resolveExternals(context, request, callback) {

  return resolveMeteor(request, callback) ||

    callback();

}

 

function resolveMeteor(request, callback) {

  var match = request.match(/^meteor\/(.+)$/);

  var pack = match && match[1];

 

  if (pack) {

    callback(null, 'Package["' + pack + '"]');

    return true;

  }

}


루트에 있는 tsconfig.json에 Meteor 백앤드 관련 내용을 추가한다.

"compilerOptions: {

"baseUrl": ".",

"module": "commonjs",

...

"skipLibCheck": true,

"stripInternal": true,

"noImplicitAny": false,

"types": [ "@types/meteor" ]

},

"include": [ ..., "api/**/*.ts" ],

"exclude": [ ..., "api/node_modules", "api" ]


src/tsconfig.app.json과 tsconfig.spec.json안에 api에 대한 exclude도 설정해야 한다.

// src/tsconfig.app.json

"exclude": [

   ...,

   "../api/node_modules"

]


// src/tsconfig.spec.json

"exclude": [ "../api/node_modules" ]


관련 패키지를 설치한다.

$ npm install --save-dev typescript-extends

$ npm install --save-dev @types/meteor

$ npm install --save-dev tmp




Meteor Server API 생성 및 설정


Meteor CLI를 설치하고 api 명으로 Meteor 프로젝트를 생성한다.

$ curl https://install.meteor.com/ | sh

$ meteor create api


api 폴더 밑의 필요없는 폴더를 삭제하고 루트에 있는 것으로 대체한다.

$ cd api

// 삭제

api$ rm -rf node_modules client package.json package-lock.json


// 심볼릭 링크

api$ ln -s ../package.json

api$ ln -s ../package-lock.json

api$ ln -s ../node_modules

api$ ln -s ../src/declarations.d.ts


Meteor 백앤드를 Typescript 기반으로 개발하기 위한 패키지를 설치한다.

api$ meteor add barbatus:typescript


api$ cd ..

$ npm install --save babel-runtime

$ npm install --save meteor-node-stubs

$ npm install --save meteor-rxjs


Typescript의 tsconfig.json 파일을 api 폴더안에 생성하고 다음 내역을 붙여넣는다.

{

  "compilerOptions": {

    "allowSyntheticDefaultImports": true,

    "declaration": false,

    "emitDecoratorMetadata": true,

    "experimentalDecorators": true,

    "lib": [

      "dom",

      "es2017"

    ],

    "module": "commonjs",

    "moduleResolution": "node",

    "sourceMap": true,

    "target": "es6",

    "skipLibCheck": true,

    "stripInternal": true,

    "noImplicitAny": false,

    "types": [

      "@types/meteor"

    ]

  },

  "exclude": [

    "node_modules"

  ],

  "compileOnSave": false,

  "atom": {

    "rewriteTsconfig": false

  }

}


Meteor의 server/main.js를 main.ts로 바꾼다. 위에서 설치한 meteor-rxjs는 클라이언트단의 Meteor를 RxJS Observable기반으로 사용할 수 있도록 한다.

// 예) Meteor 클라이언트단 Collection 구성

import { MongoObservable } from 'meteor-rxjs';


export const Chats = new MongoObservable.Collection('chats');




Meteor Client 준비


Meteor Server <-> Client 연동을 위해 Client를 Bundling한다.

$ sudo npm install -g meteor-client-bundler


번들링시에 Meteor Server 기본 주소는 localhost:3000 으로 설정된다. Meteor Client는 DDP를 이용하기 때문에 번들할 때 --config 옵션 또는 --url 옵션으로 Meteor Server 위치를 지정한다.  -s 옵션을 주면 Client<->Server 같은 버전의 패키지를 사용하고 -s 옵션을 주지않으면 config 설정내용을 참조한다. (참조)

$ meteor-client bundle --destination meteor.bundle.js --config bundler.config.json


// config file

{ "release": "1.6", "runtime": { "DDP_DEFAULT_CONNECTION_URL": "http://1.0.0.127:8100" }, "import": [ "accounts-base", "mys:accounts-phone", "jalik:ufs@0.7.1_1", "jalik:ufs-gridfs@0.1.4" ] }


package.json에 번들링 명령을 등록하고 수행한다. 

"scripts": {

   ...,

   "meteor-client:bundle": "meteor-client bundle -s api"

}


//번들링 - 최초 한번만 수행한다.

$ npm run meteor-client:bundle


Angular 클라이언트에서 Meteor Client를 사용하기 위해 src/main.ts에서 "meteor-client"를 import한다.

import "meteor-client";




Collection 생성하고 Meteor 기능 사용 테스트


api/server 에 model을 하나 만든다. Angular와 Meteor가 같이 사용하는 모델 타입이다.

// api/server/models.ts

export enum MessageType {

  TEXT = <any>'text'

}


export interface Chat {

  _id?: string;

  title?: string;

  picture?: string;

  lastMessage?: Message;

  memberIds?: string[];

}


export interface Message {

  _id?: string;

  chatId?: string;

  senderId?: string;

  content?: string;

  createdAt?: Date;

  type?: MessageType;

  ownership?: string;

}


api/server/collections 폴더를 생성하고 Chat 컬렉션을 생성한다. meteor-rxjs 는 RxJS로 Mongo Client를 wrapping해 놓은 것으로 Rx방식으로 Mongo Client를 사용할 수 있게 한다.

// api/server/collections/chats.ts

import { MongoObservable } from 'meteor-rxjs';

import { Chat } from '../models';


export const Chats = new MongoObservable.Collection<Chat>('chats'); 


// api/server/collections/messages.ts

import { MongoObservable } from 'meteor-rxjs';

import { Message } from '../models';


export const Messages = new MongoObservable.Collection<Message>('messages');


api/server/main.ts안에 샘플 데이터를 넣는다.

$ npm install --save moment


// api/server/main.ts

import { Meteor } from 'meteor/meteor';

import { Chats } from './collections/chats';

import { Messages } from './collections/messages';

import * as moment from 'moment';

import { MessageType } from './models';


Meteor.startup(() => {

  // code to run on server at startup

  if (Chats.find({}).cursor.count() === 0) {

    let chatId;


    chatId = Chats.collection.insert({

      title: 'Ethan Gonzalez',

      picture: 'https://randomuser.me/api/portraits/thumb/men/1.jpg'

    });


    Messages.collection.insert({

      chatId: chatId,

      content: 'You on your way?',

      createdAt: moment().subtract(1, 'hours').toDate(),

      type: MessageType.TEXT

    });


    chatId = Chats.collection.insert({

      title: 'Bryan Wallace',

      picture: 'https://randomuser.me/api/portraits/thumb/lego/1.jpg'

    });


    Messages.collection.insert({

      chatId: chatId,

      content: 'Hey, it\'s me',

      createdAt: moment().subtract(2, 'hours').toDate(),

      type: MessageType.TEXT

    });

  }

});


다음으로 Angular에 Chat 컬렉션을 사용한다.

// src/app/app.component.ts

import { Component, OnInit } from '@angular/core';

import { Chats } from '../../api/server/collections/chats';

import { Chat } from '../../api/server/models';


@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})

export class AppComponent implements OnInit {

  title = 'app';

  chats: Chat[];

  ngOnInit() {

    Chats.find({}).subscribe((chats: Chat[]) => this.chats = chats );

  }

}


// src/app/app.component.html 에 추가

<div> {{ chats | json }} </div>




Angular & Meteor 기동


Meteor 기동

$ cd api

api$ meteor


Angular 기동

$ npm start


Webpack dev server는 4200이고meteor client는 server에 websocket 3000 port로 접속을 한다. Meteor 의 mongo로 접속해서 chats collection을 확인해 본다.

$ meteor mongo

MongoDB shell version: 3.2.15

connecting to: 127.0.0.1:3001/meteor

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

http://docs.mongodb.org/

Questions? Try the support group

http://groups.google.com/group/mongodb-user

meteor:PRIMARY> show collections

chats

messages



하단에 Chat 내역이 json 형식으로 출력된다.




<참조>


- Webpack v3 환경설정 요약

- Meteor Client bundler의 작도방식 by Uri

- Meteor Client Bundler Github


posted by 윤영식
2017. 11. 6. 15:57 Meteor/Angular + Meteor

angular-meteor.com의 Socially Merge를 따라하며 내용을 요약해 보았다. socially merge는 meteorionic의 조합을 webpack으로 묶어 프로젝트를 구성해보는 과정이다. 여기서 익힐 수 있는 것은 Angular 로 작성된 ionic을 프론트앤드로 사용하고 metetor를 백앤드로 구성하는 방법을 배울 수 있다.




Webpack 기반 프로젝트 초기화


meteor와 ionic는 서로의 CLI를 제공한다. ionic을 먼저 설정한다.

$ npm install -g ionic cordova


초기 프로젝트 구성을 ionic CLI를 통해 생성한다.

ionic start whatsapp blank --cordova --skip-link

...

? Install the free Ionic Pro SDK and connect your app? (Y/n) n


$ cd whatsapp

$ ionic serve


Ionic은 Angular를 사용하기 때문에 Typescript 최신버전을 설치한다.

$ npm install --save typescript


타입스크립트기반에서 외부라이브러리를 사용하기 위해서 src/declarations.d.ts 파일을 생성해 놓는다. d.ts작성법은 공식문서를 참조한다. 다음으로 Ionic 3가 Webpack을 기반으로 빌드되는 설정을 package.json에 추가한다.

//  package.json

"config": {

    "ionic_webpack": "./webpack.config.js"

}


Ionic은 webpack config에 대한 샘플 파일을 제공하고 이를 복사한다. webpack.config.js안에는 dev와 prod환경 기본값이 설정되어 있다.

$ cp node_modules/@ionic/app-scripts/config/webpack.config.js .




Ionic 에 Meteor 설정


프로젝트 폴더의 루트에 api 폴더를 만들고 이를 Meteor의 백앤드로 사용하는 설정을 webpack.config.js에 한다. meteor 관련된 것은 external로 취급하는 것 같다.

// dev, prod양쪽에 넣는다.

resolve: {

...

alias: {

'api': path.resolve(__dirname, 'api/server')

}

},


externals: [ resolveExternals ],


plugins: [ ..., new webpack.ProvidePlugin({ __extends: 'typescript-extends' }) ],


node: { ..., __dirname: true }


// 맨 마지막에 넣음 

function resolveExternals(context, request, callback) {

  return resolveMeteor(request, callback) ||

    callback();

}

 

function resolveMeteor(request, callback) {

  var match = request.match(/^meteor\/(.+)$/);

  var pack = match && match[1];

 

  if (pack) {

    callback(null, 'Package["' + pack + '"]');

    return true;

  }

}


다음으로 Meteor를 외부 의존하는 것으로 tsconfig.json에 Meteor관련 내용을 추가한다.

"compilerOptions": {

  "baseUrl": ".",

  "modules": "commonjs",

  "paths": { "api/*": ["./api/server/*"],

  ...,

  "skipLibCheck": true,

  "stripInternal": true,

  "noImplicitAny": false,

  "types": [

      "@types/meteor"

  ] 

},

"include": [ ..., "api/**/*.ts" ],

"exclude": [ ..., "api/node_modules", "api" ]


typescript-extends 패키지와 meteor 타입 패키지를 설치한다.

$ npm install --save-dev typescript-extends

$ npm install --save-dev @types/meteor


Ionic serve를 실행하고 브라우져의 console을 보면 다음 오류가 나온다. 이를 위해 src/app/app.component.ts에 cordova 설정을 한다.

// Chrome devtools 메세지

Native: tried calling StatusBar.styleDefault, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator


// src/app/app.component.ts 설정




Meteor Server 생성 및 설정


Ionic의 webpack과 tsconfig안에 Meteor 서버 설정을 했고, Meteor CLI를 이용해 백앤드를 구성한다.

// 미티어 설치

$ curl https://install.meteor.com/ | sh


// api 폴더 미티어 초기화

$ meteor create api


api 폴더 밑으로 생성된 node_modules, client 폴더를 삭제하고, package.json, package-lock.json 파일도 삭제한다.

$ rm -rf api/node_modules

$ rm -rf api/client

$ rm api/package.json

$ rm api/package-lock.json


Meteor에서 사용하는 것을 Ionic 으로 심볼릭 링크를 건다.

$ cd api

api$ ln -s ../package.json

api$ ln -s ../pack-lock.json

api$ ln -s ../node_modules

api$ ln -s ../src/declarations.d.ts


Meteor 백앤드를 Typescript기반으로 개발하기 위해 다음 패키지를 설치한다.

api$ meteor add barbatus:typescript


// 별도 필요 패키지 설치 

$ npm install --save babel-runtime

$ npm install --save meteor-node-stubs

$ npm install --save meteor-rxjs


Typescript의 tsconfig.json 파일을 api 폴더안에 생성하고 다음 내역을 붙여넣는다.

{

  "compilerOptions": {

    "allowSyntheticDefaultImports": true,

    "declaration": false,

    "emitDecoratorMetadata": true,

    "experimentalDecorators": true,

    "lib": [

      "dom",

      "es2015"

    ],

    "module": "commonjs",

    "moduleResolution": "node",

    "sourceMap": true,

    "target": "es5",

    "skipLibCheck": true,

    "stripInternal": true,

    "noImplicitAny": false,

    "types": [

      "@types/meteor"

    ]

  },

  "exclude": [

    "node_modules"

  ],

  "compileOnSave": false,

  "atom": {

    "rewriteTsconfig": false

  }

}


Meteor의 server/main.js를 main.ts로 바꾼다. 위에서 설치한 meteor-rxjs는 클라이언트단의 Meteor를 RxJS Observable기반으로 사용할 수 있도록 한다.

// 예) Meteor 클라이언트단 Collection 구성

import { MongoObservable } from 'meteor-rxjs';


export const Chats = new MongoObservable.Collection('chats');




Meteor Client 준비


Meteor Server에 접속하기 위해 Meteor Client가 필요하기 때문에 하나의 bundler로 만들어 import해서 사용한다. 번들링도구를 설치한다.

$ sudo npm install -g meteor-client-bundler


// 필요 패키지를 설치

$ npm install --save-dev tmp


package.json 에 번들링 명령어를 설정하고, 번들링 명령을 수행한다.

// package.json

"scripts": {

...,

"meteor-client:bundle": "meteor-client bundle -s api"

}


// 번들링

$ npm run meteor-client:bundle


클라이언트 main.ts에 번들 내역을 import한다. 

// src/app/main.ts

import "meteor-client";




Ionic & Meteor 기동


Ionic 기동

$ ionic serve


Meteor 기동

$ cd api

api$ meteor


ionic HTTP는 8100이고, meteor client는 server에 websocket 3000 port로 접속을 한다.


posted by 윤영식
2017. 9. 4. 15:51 카테고리 없음

Angular 최신 버전이 v5 beta-6를 향해 가고 있다. 9월에는 v5 release가 될 것으로 보인다. Angular에서 툴 기능으로 @angular/cli를 제공하고 있는데 오늘은 이것의 내부구조에 대해 연구해 본다. 



@angular/cli 설치 및 프로젝트 생성

설치는 npm 또는 yarn을 이용한다.

$> npm i -g @angular/cli


or 


$> yarn add global @angular/cli


Angular 기반 프로젝트를 생성해 보자.

$> ng new jamong


실행해 보자

$> ng serve




폴더 구조

angular/cli는 Automation Tool 과 Module loader로 webpack을 사용하고 있다. 웹팩의 환경파일을 루트 폴더에 생성한다. 
$> ng eject
=====================================================
Ejection was successful.

To run your builds, you now need to do the following commands:
   - "npm run build" to build.
   - "npm test" to run unit tests.
   - "npm start" to serve the app using webpack-dev-server.
   - "npm run e2e" to run protractor.

Running the equivalent CLI commands will result in an error.

=====================================================
Some packages were added. Please run "npm install".


설명에 따라 추가 명령을 수행한다. 

$> npm run build && npm start


// package.json의 build 와 start 스크립트 설정내역

  "scripts": {

    "ng": "ng",

    "start": "webpack-dev-server --port=4200",

    "build": "webpack",

    "test": "karma start ./karma.conf.js",

    "lint": "ng lint",

    "e2e": "protractor ./protractor.conf.js",

    "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"

  },



webpack 오류가 난다면 webpack이  global설치가 않되어 있기때문이다. webpack을 설치한다. 

$> yarn add webpack --dev

또는

$> yarn add global webpack 

또는 

$> npm install -g webpack





Webpack 환경파일

webpack의 기본은 초기 참조할 entry파일과 결과 번들파일을 지정하는 것이다. 

$> webpack <entry file path> <output bundle file path>


예) webpack ./entry.js bunlde.js


간단한 번들링은 CLI를 사용해도 무방하지만 복잡한 옵션이 적용되어야 한다면 환경파일을 사용한다. 예) webpack.config.js 아래 예에서 ouput의 filename에 [name]은 entry의 'app' 키값이다. 

module.exports = {

  context: __dirname + '/app',

  entry: {

    app: './app.js'

  },

  output: {

    path: __dirname + '/dist',

    filename: '[name].bundle.js'

  }

}


환경설정 자세한 옵션은 공식문서를 참조한다. 여기서 주의할 것은 entry는 String, Object, Array로 설정가능하다. 

- String: 하나만 설정

- Array: output 번들링 파일에 순서적으로 합쳐진다.

- Object: SPA처럼 index.html에 적용되는 것이 아니라, index1.html 또는 index2.html 등 output이 각각의 html에 포함될 때 사용한다. 





Webpack Loader

Webpack에는 자바스크립트가 아닌 확장형식의 파일을 자바스크립트에서 동작할 수 있도록 해주는 로더(Loader)가 있다. 즉, 모든(CSS, Images, HTML...)을 모듈로 취급하게 해주는 핵심역할을 로더가 수행한다. 말 그대로 다양한 파일 확장자의 Module Loader의 줄임말이라 보면된다. (전체 목록 참조) 만일 설정중에 module, rules를 사용하지않고 loaders를 쓰거나, options대신 query를 쓰면 webpack 1에 대한 설명이다.


- 스타일: style, css

- 변환: typescript, coffeescript, ES2015


환경파일안에 module 밑으로 설정한다. 


module.exports = {

  entry: ...

  output: ...

  module: {

    rules: [

      {

        test: /\.css$/,

        use: [ 'style-loader', 'css-loader']

      }

    ]

    ...

  }


}


특히 Angular 개발시에는 Typescript를 사용하므로 sourcemap을 남기려면 'source-map-loader'를 module 프로퍼티에 설정한다. (sourcemap에 대해 webpack3에서는 plugin으로 설정도 가능하다.) enforce 설정값을 "pre"로 하면 자바스크립트 변환전에 sourcemap 을 만든다.

{

        "enforce": "pre",

        "test": /\.js$/,

        "loader": "source-map-loader",

        "exclude": [

          /(\\|\/)node_modules(\\|\/)/

        ]

}


개발시에는 Node.js기반의 webpack-dev-server를 통해 개발 페이지를 테스트할 수 있다. 옵션은 --inline (전체 페이지 리로딩) --hot (변경 컴포넌트만 리로딩)한다. 

// 전체 및 부분 리로딩 옵션 설정

$> webpack-dev-server --inline --hot




Webpack Plugins

플러그인은 Output 번들의 Chunk 또는 Compilation 레벨 파일에 대한 추가 작업을 수행한다. 예로 ulgifyJSPlugin은 번들 파일 사이즈를 줄이고, 코드를 못 알아보게 만들어 준다. 또는 extract-text-webpack-plugin의 경우는 css-loader, style-loader의 결과를 하나의 별도 외부 파일로 만들어 준다. (플러그인 목록 참조)


@angular/cli에서  ng eject로 나온 webpack.config.js안의 plugins설정 내역

"plugins": [

    new NoEmitOnErrorsPlugin(),

    new GlobCopyWebpackPlugin({

      "patterns": [

        "assets",

        "favicon.ico"

      ],

      "globOptions": {

        "cwd": path.join(process.cwd(), "src"),

        "dot": true,

        "ignore": "**/.gitkeep"

      }

    }),

    new ProgressPlugin(),

    new CircularDependencyPlugin({

      "exclude": /(\\|\/)node_modules(\\|\/)/,

      "failOnError": false

    }),

    new NamedLazyChunksWebpackPlugin(),

    new HtmlWebpackPlugin({

      "template": "./src/index.html",

      "filename": "./index.html",

      "hash": false,

      "inject": true,

      "compile": true,

      "favicon": false,

      "minify": false,

      "cache": true,

      "showErrors": true,

      "chunks": "all",

      "excludeChunks": [],

      "title": "Webpack App",

      "xhtml": true,

      "chunksSortMode": function sort(left, right) {

        let leftIndex = entryPoints.indexOf(left.names[0]);

        let rightindex = entryPoints.indexOf(right.names[0]);

        if (leftIndex > rightindex) {

          return 1;

        } else if (leftIndex < rightindex) {

          return -1;

        } else {

          return 0;

        }

      }

    }),

    new BaseHrefWebpackPlugin({}),

    new CommonsChunkPlugin({

      "name": [

        "inline"

      ],

      "minChunks": null

    }),

    new CommonsChunkPlugin({

      "name": [

        "vendor"

      ],

      "minChunks": (module) => {

        return module.resource &&

          (module.resource.startsWith(nodeModules) ||

            module.resource.startsWith(genDirNodeModules) ||

            module.resource.startsWith(realNodeModules));

      },

      "chunks": [

        "main"

      ]

    }),

    new SourceMapDevToolPlugin({

      "filename": "[file].map[query]",

      "moduleFilenameTemplate": "[resource-path]",

      "fallbackModuleFilenameTemplate": "[resource-path]?[hash]",

      "sourceRoot": "webpack:///"

    }),

    new CommonsChunkPlugin({

      "name": [

        "main"

      ],

      "minChunks": 2,

      "async": "common"

    }),

    new NamedModulesPlugin({}),

    new AotPlugin({

      "mainPath": "main.ts",

      "replaceExport": false,

      "hostReplacementPaths": {

        "environments/environment.ts": "environments/environment.ts"

      },

      "exclude": [],

      "tsConfigPath": "src/tsconfig.app.json",

      "skipCodeGeneration": true

    })

]


JHipster로 자동생된 webpack.config.dev.js의 plugins 설정 내역

plugins: [

        new BrowserSyncPlugin({

            host: 'localhost',

            port: 9000,

            proxy: {

                target: 'http://localhost:9060',

                ws: true

            }

        }, {

            reload: false

        }),

        new webpack.NoEmitOnErrorsPlugin(),

        new webpack.NamedModulesPlugin(),

        new writeFilePlugin(),

        new webpack.WatchIgnorePlugin([

            utils.root('src/test'),

        ]),

        new WebpackNotifierPlugin({

            title: 'JHipster',

            contentImage: path.join(__dirname, 'logo-jhipster.png')

        })

 ]




Production vs Development

개발과 운영 시점에 webpack 환경을 달리 적용하기 위해 보통  webpack.config.dev.js 와 webpack.config.prod.js를  따로 만들고 package.json의 script에 적용해 사용한다. package.json에 적용하고 싶지 않다며 gulp를 사용해도 된다. 


@angular/cli의 script 내역

 "scripts": {

    "ng": "ng",

    "start": "webpack-dev-server --port=4200",

    "build": "webpack",

    "test": "karma start ./karma.conf.js",

    "lint": "ng lint",

    "e2e": "protractor ./protractor.conf.js",

    "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"

}


JHipster script 내역

"scripts": {

    "lint": "tslint --type-check --project './tsconfig.json' -e 'node_modules/**'",

    "lint:fix": "yarn run lint -- --fix",

    "ngc": "ngc -p tsconfig-aot.json",

    "cleanup": "rimraf target/{aot,www}",

    "clean-www": "rimraf target//www/app/{src,target/}",

    "start": "yarn run webpack:dev",

    "serve": "yarn run start",

    "build": "yarn run webpack:prod",

    "test": "karma start src/test/javascript/karma.conf.js",

    "test:watch": "yarn test -- --watch",

    "webpack:dev": "yarn run webpack-dev-server -- --config webpack/webpack.dev.js --progress --inline --hot --profile --port=9060",

    "webpack:build:main": "yarn run webpack -- --config webpack/webpack.dev.js --progress --profile",

    "webpack:build": "yarn run cleanup && yarn run webpack:build:main",

    "webpack:prod:main": "yarn run webpack -- --config webpack/webpack.prod.js --progress --profile",

    "webpack:prod": "yarn run cleanup && yarn run webpack:prod:main && yarn run clean-www",

    "webpack:test": "yarn run test",

    "webpack-dev-server": "node --max_old_space_size=4096 node_modules/webpack-dev-server/bin/webpack-dev-server.js",

    "webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js",

    "e2e": "protractor src/test/javascript/protractor.conf.js",

    "postinstall": "webdriver-manager update && node node_modules/phantomjs-prebuilt/install.js"

}


to be continued...



<참고>

- Webpack core concept

- 네이버 webpack 소개

- Webpack의 혼란스러운 사항들

- Webpack3에서 주의할 점


posted by 윤영식
2017. 4. 23. 15:51 Angular/Concept

Angular CLI를 통해 프로젝트를 생성하고 Docker에 Nginx를 띄워서 간단히 연결해 보자. 




Angular CLI 기반 프로젝트 생성


NodeJS버전은 6최신을 사용한다. 

$ npm install -g @angular/cli 


설치가 되었다면 ng 명령을 통해 프로젝트를 생성한다. 

$ ng new angular-docker


프로젝트가 생성되었으면 프로젝트 폴더로 이동해서 소스를 빌드한다. 

$ cd angular-docker

$ ng build

Hash: cfba09939df99de45615

Time: 7424ms

chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 165 kB {4} [initial] [rendered]

chunk    {1} main.bundle.js, main.bundle.js.map (main) 3.61 kB {3} [initial] [rendered]

chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 9.77 kB {4} [initial] [rendered]

chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.09 MB [initial] [rendered]

chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]





Docker CE 기반 Nginx 관리


Docker를 잘 모른다면 Docker CE를 설치해 사용한다. 

  - download docker CE (Community Edition)

 - Mac 버전을 설치하면 Docker 가 기동이 된다.

 

     


다음으로 Nginx image 를 docker명령을 통해 내려받는다. 만일 사용하지 않는 Docker image들이 있다면 다 삭제를 한고 작업을 해보자.

// Delete all docker containers

$ docker rm $(docker ps -a -q)


// Delete all docker images

$ docker rmi $(docker images -q)


// Install docker image

$ docker pull nginx

Using default tag: latest


// 설치 내역 확인

$ docker images 

REPOSITORY        TAG                 IMAGE ID            CREATED             SIZE

nginx                  latest              5766334bdaa0   2 weeks ago         183 MB


Angular 빌드 폴더로 이동해서 Nginx를 수행한다. 

$ cd dist

$ docker run -d -p 8080:80 -v $(pwd):/usr/share/nginx/html nginx:latest

48db2f0626c5a10429e95cbbbaf3cc58769cda45a9c1e7084b4f3a260e576838


// 이미지 실행 확인

$ docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                           NAMES

48db2f0626c5        nginx:latest        "nginx -g 'daemon ..."   2 minutes ago       Up 2 minutes        443/tcp, 0.0.0.0:8080->80/tcp   loving_lumiere


수행되고 있는 이미지를 멈추고 제거해 보자. stop, rm 다음은 Container ID의 처음 두자를 입력한다. 

// 멈춤 

$ docker stop 48

48


// 제거

$ docker rm 48

48


// 확인

$ docker ps -a

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES


Kinetic 애플리케이션을 사용해서 CLI 명령과 동일하게 GUI 기반으로 Container를 관리할 수 있다.




Docker Compose 사용하기


컴포즈는 환경을 기반으로 다양한 도커 이미지들을 동시에 기동하고 연결하는 역할을 수행한다. Nginx, NodeJS, MongoDB등을 서로 다른 Docker image기반으로 기동하고 연결하는 환경설정을 docker_compose.yml에 한다. angular-seed 예는 다음과 같다. 

version: '2'


services:


  angular-seed:

    build:

      context: .

      dockerfile: ./.docker/angular-seed.development.dockerfile

    command: npm start

    container_name: angular-seed-start

    image: angular-seed

    networks:

      - dev-network

    ports:

      - '5555:5555'


networks:

  dev-network:

    driver: bridge


빌드하고 수행하기 

$ docker-compose build

$ docker-comopse up


ng-conf 2017 의 docker 이야기




<참조>



posted by 윤영식
2017. 4. 11. 20:40 Big Data

RethinkDB는 리얼타임 웹을 위한 NoSQL 저장소이다. 




설치하기


가이드에 따라 OS에 맞게 설치한다. (맥기준)

$ brew update && brew install rethinkdb

또는 

다운로드 (.dmg)


docker로 실행할 경우

$ docker run -d -P --name rethink1 rethinkdb


저장소를 설치했으면 다음으로 NodeJS에서 사용할 클라이언트 드라이버를 설치한다. 




실행하기


설치확인

$ which rethinkdb

/usr/local/bin/rethinkdb


실행하기

$ rethinkdb --bind all

Running rethinkdb 2.3.5 (CLANG 7.3.0 (clang-703.0.31))...

Running on Darwin 16.5.0 x86_64

Loading data from directory /Users/dowonyun/opensource/rethinkdb_data

Listening for intracluster connections on port 29015

Listening for client driver connections on port 28015

Listening for administrative HTTP connections on port 8080


브라우져기반 Admin(http://localhost:8080)을 통해 실시간 변경사항 조회, 테이블 생성, 서버관리, 데이터 조회등을 할 수 있다.




NodeJS환경에서 RethinkDB 접속하기


npm으로 노드환경을 만들고 rethink driver를 설치한다. 

$ npm init -y

$ npm i rethinkdb --save


신규 파일을 만들고 Connect를 하고, 기본 데이터베이스인 test안에 신규 테이블을 생성해 보자. 

// connect.js

r = require('rethinkdb');


let connection = null;

r.connect({ host: 'localhost', port: 28015 }, function (err, conn) {

    if (err) throw err;

    connection = conn;

    

    r.db('test').tableCreate('authors').run(connection, function (err, result) {

        if (err) throw err;

        console.log(JSON.stringify(result, null, 2));

    })

})


실행을 해보면 테이블이 생성되고 Admin화면에서도 확인해 볼 수 있다. rethinkDB 또한 Shard, Replica를 제공함을 알 수 있다. 

$ node connect.js

{

  "config_changes": [

    {

      "new_val": {

        "db": "test",

        "durability": "hard",

        "id": "05f4b262-9e01-477e-a74c-3d4ccb14cf84",

        "indexes": [],

        "name": "authors",

        "primary_key": "id",

        "shards": [

          {

            "nonvoting_replicas": [],

            "primary_replica": "DowonYunui_MacBook_Pro_local_bcb",

            "replicas": [

              "DowonYunui_MacBook_Pro_local_bcb"

            ]

          }

        ],

        "write_acks": "majority"

      },

      "old_val": null

    }

  ],

  "tables_created": 1

}


다음으로 rethinkDB는 자체 query 엔진을 가지고 있고, rethinkDB를 위한 쿼리 언어를 ReQL이라 한다. ReQL의 3가지 특성은 다음과 같다. 

  - ReQL embeds into your programming language: 펑션으로 만들어짐

  - All ReQL queries are chainable: Dot ( . ) 오퍼레이터를 통해 체이닝 메소드 호출이다. 

  - All queries execute on the server: run을 호출해야 비로서 쿼리를 수행한다.


예제는 3가지의 특성을 보여주고 있다. query를 json 또는 SQL query statement으로 짜는게 아니라. 메소드 체이닝을 통해 쿼리를 만들고, 맨 나중에 Connection 객체를 파라미터로 넘겨주면서 run() 메소드를 실행한다. 

r.table('users').pluck('last_name').distinct().count().run(conn)




일반 SQL 문과 자바스크립트 기반의 ReQL 차이점


구문의 차이저을 보자. row가 document이고, column이 field라는 차이점만 존재한다. 


 Insert


Select



다른 예제는 가이드 문서를 참조하자.




Horizon을 이용한 클라이언트 & 서버 구축하기


Horizon은 rehtinkDB를 사용해 realtime서비스 개발을 돕는 Node.js기반의 서버 프레임워크이면서 클라이언트에서 서버단의 접속을 RxJS 기반의 라이브러리를 통해 가능하다. 마치 Meteor 플랫폼과 유사한 리얼타임 아키텍트를 제공한다. Horizon의 CLI를 글로벌로 설치한다.

$ npm install -g horizon


호라이즌 실행은 hz 이다. 애플리케이션 스켈레톤을 hz을 이용해 만든다.

$ hz init realtime_app

Created new project directory realtime_app

Created realtime_app/src directory

Created realtime_app/dist directory

Created realtime_app/dist/index.html example

Created realtime_app/.hz directory

Created realtime_app/.gitignore

Created realtime_app/.hz/config.toml

Created realtime_app/.hz/schema.toml

Created realtime_app/.hz/secrets.toml


hz 서버 구동하고 http://localhost:55584/ 로 접속하면 http://localhost:8080 접속화면과 동일한 Admin화면을 볼 수 있다.

$ hz serve --dev

App available at http://127.0.0.1:8181

RethinkDB

   ├── Admin interface: http://localhost:55584

   └── Drivers can connect to port 55583

Starting Horizon...

🌄 Horizon ready for connections


http://127.0.0.1:8181/을 호출하면 샘플 웹 화면을 볼 수 있다. 보다 자세한 사항은 홈페이지를 참조하고, 차후에 다시 다루어 보기로 하자.




<참조>

  - rethinkDB 10분 가이드

  - ReQL 가이드

  - Pluralsight 가이드

posted by 윤영식
2017. 4. 4. 10:59 Dev Environment/Build System

Gulp 빌드 환경에 파일이 변경되었을 때 자동으로 브라우져 화면을 업데이트해주는 Live reload환경을 접목해 본다.





Gulp 환경 만들기


gulp CLI를 설치한다.

$ npm i -g gulp-cli


npm 대신 속도가 빠르다는 yarn을 사용해 본다. yarn을 설치한다.

$ npm i -g yarn



테스트 폴를 생성하고,yarn을 이용해 package.json을 만든다. -y 플래그를 주면 모두 Yes로 응답해서 package.json을 생성해준다.

$ mkdir livereload && cd livereload

$ yarn init -y

yarn init v0.21.3

warning The yes flag has been set. This will automatically answer yes to all questions which may have security implications.

success Saved package.json

✨  Done in 0.06s.



index.html파일을 생성하고, gulp 패키지를 로컬에 설치한다. index.html에 간단한 body 태그를 넣는다. 

$ touch index.html

$ yarn add --dev gulp


TypeScript기반으로 파일을 작성하기 위해 다음 설정을 한다. [Typescript] NodeJS에서 Typescript 사용하기

$ yarn add --dev @types/node



gulp환경파일을 생성하고, default 태스크를 작성한다. gulp 명령을 실행하면 default 태스크가 실행된다.

$ touch Gulpfile.ts


// Gulpfile.js

const gulp = require('gulp');


gulp.task('default', function () {

  console.log('Gulp and running!')

});


// test

$ gulp

[09:27:23] Using gulpfile ~/prototyping/livereload/gulpfile.ts

[09:27:23] Starting 'default'...

Gulp and running!

[09:27:23] Finished 'default' after 71 μs





테스트 서버 환경 만들기


Express를 설치하고 정적 파일을 처리하는 서버를 생성한다.

$ yarn add --dev express


// Gulpfile.ts

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(express.static(__dirname));

  app.listen(4000);

}


gulp.task('default', () => startExpress());


index.html 을 작성하고, gulp 명령을 수행한 다음 http://localhost:4000 호출해서 hi peter가 출력하면 정상작동이다. 

<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <title></title>

  </head>

  <body>

    hi peter

  </body>

</html>


다음으로 livereload server 인 tiny-lr을 설치한다.

$ yarn add --dev tiny-lr


tiny-lr서버도 gulp환경에 넣는다. gulp명령을 실행하고 http://localhost:35729/ 접속해서 {"tinylr":"Welcome","version":"1.0.3"} 출력되면 정상작동이다. tiny-lr의 기본 포트는 35729 이다.

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(express.static(__dirname));

  app.listen(4000);

}


function startLivereload() {

  const lr = require('tiny-lr')();

  lr.listen(35729);

}


gulp.task('default', () => {

  startExpress();

  startLivereload();

});





Livereload 환경 만들기


전체 동작방식은 다음과 같다.

  - 브라우져가 열리면 livereload.js는 tiny-lr과 웹소켓 연결을 맺는다.

  - 1) gulp.watch가 파일 변경을 감지한다. 

  - 1) gulp.watch는 변경파일에 대해 tiny-lr에게 reload 하라고 호출한다. 

  - 2) tiny-lr 서버는 livereload.js 모듈과 웹소켓으로 통신한다.

  - 3) livereload.js는 파일을 다시 요청한다. 

  - 화면이 refresh되면서 livereload.js와 tiny-lr 간 웹소켓 연결을 다시 맺는다. 





Express로 서비스하는 페이지가 livereload 처리하는 자바스크립트 로직을 넣기위해 connect-livereload NodeJS 미들웨어도 설치한다.

$ yarn add --dev connect-livereload


connect-livereload를 Express 미들웨어로 설정한다.

// Gulpfile.ts

function startExpress() {

  const express = require('express');

  const app = express();

  app.use(require('connect-livereload')());

  app.use(express.static(__dirname));

  app.listen(4000);

}



gulp.watch를 통해 변경된 파일의 목록을 tiny-lr에 전달하는 코드를 작성한다. 

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(require('connect-livereload')());

  app.use(express.static(__dirname));

  app.listen(4000);

}


let lr;

function startLivereload() {

  lr = require('tiny-lr')();

  lr.listen(35729);

}


function notifyLivereload(event) {

  // `gulp.watch()` events 는 절대경로를 주기 때문에 상대 경로(relative)를 만든다.

  var fileName = require('path').relative(__dirname, event.path);


  lr.changed({

    body: {

      files: [fileName]

    }

  });

}


gulp.task('default', () => {

  startExpress();

  startLivereload();

  gulp.watch('*.html', notifyLivereload);

});


다시 gulp를 수행하고 브라우져에서 http://localhost:4000/index.html 을 호출한 후에 index.html의 내용을 변경하면 브라우져가 자동으로 refresh되는 것을 볼 수 있다. 브라우져에서 element검사를 하면 아래와 같이 livereload.js파일이 </body> 전에 자동 추가된다. (소스 참조)



위의 코드를 단순히 하기위해 gulp-livereload를 사용할 수도 있다. 샘플 파일: https://github.com/BISTel-MIPlatform/livereload-tiny-lr





참조

  - https://github.com/mklabs/tiny-lr

 - https://github.com/livereload/livereload-js

  - https://github.com/intesso/connect-livereload

  - https://github.com/vohof/gulp-livereload

posted by 윤영식
2017. 4. 3. 16:07 Dev Environment

오래된 Grunt명령을 수행 결과를 디버깅할 일이 생겨서 MS Code에서 시도해 보기로 했다. 디버깅을 위한 설정방법을 알아보자. 



설정열기


먼저 MS Code의 Debug화면으로 이동한후 설정(하단 톱니바퀴)을 클릭한다.


설정을 클릭하면 launch.json 파일이 자동으로 열린다. launch.json파일은 MS Code가 오픈하고 있는 폴더의 최상위에 .vscode 폴더밑에 존재한다. 이곳에 Grunt  디버깅용 환경설정을 추가한다. 




환경설정


launch.json파일안에 다음과 같이 추가한다. 

  - node 타입이고, launch 한다. 

  - name: 디버깅창의 목록에 표시될 이름

  - args: grunt <argument> 명령

  - program: grunt 파일 위치

  - stopOnEntry: 시작한 프로그램에서 breakpoint가 없어도 시작 프로그램에서 중단점을 자동으로 시작할지 여부

  - cwd: 현재 디렉토리, 파일 참조하는 최상위 폴더 위치

"configuration": [

    {

            "type": "node",

            "request": "launch",

            "name": "Grunt Directly",

            "args": ["serve"],            

            "program": "/Users/peter/.nvm/versions/node/v6.10.1/bin/grunt", 

            "stopOnEntry": true,

            "cwd": "${workspaceRoot}"

      },

...

]





디버깅


이제 grunt task파일을 디버깅해보자. 

  - 먼저 디버깅 중단점(break point)를 설정한다. 소스 에디터에서 좌측의 라인 번호 옆 공간을 클릭해서 설정한다. 클릭할 때 빨간점이 찍힌다.

  - 좌측 상단에서 grunt 디버깅 설정한 명칭 "Grunt Directly"를 선택한다. 

  - 실행 (녹색 삼각형 버튼)을 클릭한다.

  - 중단점에 실행이 멈추면서 우측 상단에 "debugging step"바가 나오고 실행, over, into, 멈춤을 통해 소스를 디버깅할 수 있다. 

 



상세 설정 정보는 MS Code 가이드를 참조하자.


Happy, Enjoy Coding~~~


'Dev Environment' 카테고리의 다른 글

Aptana + Spket 개발환경 구축하기  (0) 2012.11.23
posted by 윤영식
2017. 3. 29. 15:05 Angular/Concept

NodeJS에서 Typescript를 사용하기 위한 빠른 환경 설정 방법을 정리한다.



설치

먼저 테스트를 위한 폴더를 만들고 Node환경을 만든다. package.json을  파일 생성한다.

$ npm init -y


필요한 패키지를 설치한다.

$ npm i -g typescript@latest


$ npm i -g ts-node


$ npm i @types/node --save-dev




환경설정


Typescript 환경파일을 생성한다.

$ tsc --init


tsconfig.json파일 환경을 설정한다. typeRoots와 exclude를 추가한다. (tsocnfig.json의 상세내역 참조)

{

    "compilerOptions": {

        "module": "commonjs",

        "target": "es5",

        "noImplicitAny": false,

        "sourceMap": false

    },

    "typeRoots": ["node_modules/@types"],

    "exclude": [

        "node_modules"

    ]

}




테스트


테스트 파일을 생성한다.

$ touch index.ts

$ vi index.ts


const hi = 'hello peter';

console.log(hi);


테스트를 위해 소스 변경을 런타임시에 체크하고 적용하는 nodemone을 설치한다. 

$ npm i nodemon --save-dev


테스트 스크립트를 package.json의 scripts 항목에 추가한다.

$ vi package.json


{

...

  "scripts": {

    "start": "npm run build:live",

    "build:live": "nodemon --exec ./node_modules/.bin/ts-node  ./index.ts"

  },

...

}


테스트한다.

$ npm start


> typescript@1.0.0 start /Users/dowonyun/prototyping/typescript

> npm run build:live

> typescript@1.0.0 build:live /Users/dowonyun/prototyping/typescript

> nodemon --exec ./node_modules/.bin/ts-node ./index.ts


[nodemon] 1.11.0

[nodemon] to restart at any time, enter `rs`

[nodemon] watching: *.*

[nodemon] starting `./node_modules/.bin/ts-node ./index.ts`

hello peter

[nodemon] clean exit - waiting for changes before restart



또는 ts-node를 설치해서 수행해도 된다.

$ npm install --save ts-node 

$ ts-node ./index.ts



참조

https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html

- https://nodemon.io/

- https://github.com/TypeStrong/ts-node


posted by 윤영식
2016. 12. 20. 20:54 Angular/Concept

오늘은 Progressive Web Apps 개발에 대한 세미나 참석 내용을 정리해 본다. 



AMP

Progressive는 구글이 생각하는 서비스에 대한 점진적인 개발 진행 방향을 이야기 한다. 즉, 기술아니라 사용자 경험을 더 좋게 하기 위한 개념이다. AMP (Accelerated Mobile Pages) 는 모바일 페이지를 빠르게 만드는게 목표이다. 네트워크가 빠르면 모바일 웹이 느리다는 것을 느낄 수 없지만 느리면 반응이 느려진다. 해당 기술은 데스크톱에도 동일하게 적용될 수 있다. AMP는 정적 페이지를 위한 것이다. 


- amp html


<html amp>를 넣는다. <style amp-boilerplate>를 넣어 페이지 로딩바가 보이도록 한다. 

<!doctype html>

<html amp>

 <head>

   <meta charset="utf-8">

   <link rel="canonical" href="hello-world.html">

   <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

   <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>

   <style amp-custom>

    

   </style>

   <script async src="https://cdn.ampproject.org/v0.js"></script>

 </head>

 <body>Hello World!</body>

</html>


- <link rel="canonical" href="amp.html">  amp를 지원하지 않는 브라우저대응을 위한 대신할 html 지정 

- 속도를 위해 amp로 된 웹페이지를 하나 더 만들어 서비스 하는것이다. amp는 기존의 html, css를 변경해서 적용하는 것이다. 



Service Worker

Web Worker는 메인페이지와 병렬 스크립트를 실행하는 백그라운드 워커를 생성하는 API로서 메세지 전송기반의 스레드 수행과 유사하다. UI Rendering과 분리되어 수행할 수 있다. 따라서 Web Work에서는 


- DOM을 직접 건드릴 수 없다. 

- 자체적인 글로벌 스코프

- 일부 속성과 API만 허가: 보면서 디버깅할 수 있는 것이 없다


Service Worker는 오프라인일 경우에도 웹 어플리케이션의 기동을 가능토록 하는 훅(Hook)을 포함하여, 어플리케이션으로 하여금 지속적인 백그라운드 포로세싱의 장점을 취하도록 하는 방법. 브라우저에서 로컬 웹서버가 있는 것과 같다. 


- 지속적인 백그라운드 처리

- 브라우저에 무언가 설치하는 것이다


정적인 파일에 대한 요청이 있을 때 네트워크가 끊어졌을 때 로컬 브라우저에서 서비스를 할 수 있게 한다. 백그라운드에서 정적 파일을 가져와서 브라우저 요청을 로컬 Service Worker 에서 처리해 준다. Application Cache의 스펙 오류를 해결하기 위해 Service Worker가 나왔다. 


- 기본 https 에서만 작동한다. 해킹방지: 중간 공격자를 피하기 위함

- 대신 127.0.0.1, localhost 테스트는 가능하다 


예, 오프라인 웹앱, 구글의 공룡게임 - 브라우저에 함께 존재한다. 


배워야 할 것은 


- 리소스 저장을 위한 Cache Storage - promise객체를 반환 

- 이벤트 생명 연장의 꿈: .waitUntile()  이벤트가 종료되지 않도록 한다  

- 패치 onfetch() 브라우저에서 리소스 접근 요청될 때 호출되는 이벤트 -> FetchEvent 요청내용을 담고 있다. .responseWith() 통해 응답한다



NAMP-CARD 

https://ampbyexample.com 좀 더 심화된 예제 사이트 이다. sw.js를 작성한다. 


var CACHE_NAME = 'pwa-workshop.github.id-namp-card-cache-v1';

// 하기 해당하는 내용을 캐쉬에 저장한다 

var urlsToCache = [

'/namp-card',

    '/index.html',

    '/manifest.json',

    '/user.png'

];


self.addEventListener('install', function(event) {

event.waitUntil(

caches.open(CACHE_NAME).then(function(cache) {

console.log(`Opened cache for namp-card ${new Date()}`);

return cache.addAll(urlsToCache);

})

);

});


self.addEventListener('fetch', function(event) {

    event.waitUntile(

        // 캐쉬안에 브라우저 요청과 매칭되는 것이 있으면 리턴을 해준다. 

        // 없으면 fetch(event, request.url)로 원격 서버에 요청 

        caches

            .match(event.request.url)

            .then(function(res) {

                return res || fetch(event, request.url);

            })

    )

});


등록을 한다. amp-install-serviceworker 스크립트를 이용하면 하기 내용이 들어간다. 개발자가 직접 넣을 수 없다. 

navigator.serviceWorker.register('/sw.js', { scope: '/' })

          .then(function(registration) {

                console.log('Service Worker Registered');

          });


https://airhorner.com/ 예의 DevTool에서 Service Worker를 볼 수 있다. 




모바일 기기에 설치형 웹앱 만들기

설치형이란? 


- 네트워크 불안하거나 오프라인인 경우에도 동작

- 홈스크린에서 바로 실행

- 앱의 이름과 아이콘을 제공


동작 가능한 웹앱


- 서비스워커의 지원 필요

- 프리캐쉬(Pre-cache)된 애플리케이션 프레임워크(App-shell) 사용

- 서비스워커를 통해 Indexed DB 또는 히스토리컬 데이터 디스플레이 


반드시 웹 메니페이스(Manifest)를 작성해야 함


- 설치 방법을 기술: 브라우저에서 Add to Home Screen 하면 모바일 바탕화면에 아이콘이 나온다. -> 굳이 앱을 설치하지 않아도 접근 가능토록 한다

- Splash 윈도우 사용가능: 아이콘 지정, 텍스트 지정 

- Prompt (부추기기)를 통해 Add to Home Screen를 하도록 유도한다. 이를 통해 앱의 설치없이 전환율을 높인다. 

- 노드 모듈의 pwa-manifest를 설치해서 사용할 수도 있다. 



실제로 수행하는 순서 참조


-  https://github.com/pwa-workshop/roadshow/blob/master/turn-into-an-installable-webapp.md

- github.com의 개인 프로필로에서 https 를 사용토록 한다.  



<참조> 

https://github.com/pwa-workshop/namp-card

https://www.ampproject.org/ko

posted by 윤영식
2016. 11. 23. 16:50 Electron & Ionic

Electron을 통한 테스트 자동화 접근법 세션


- 정적 테스트 프로그램은 테스트 프로그램이 있는 것, 동적 테스트는 기존 애플리케이션을 통해 테스트 하는 방식. 

- ATDD 수용성 테스트는 E2E 테스트를 한다. 

  + Selenium -> WebDriver

  + Nightwatch


- Electron 

  + Node Based Desktop Application

  + View렌더링을 위한 브라우져를 가지고 있으므로 전통적은 Hybrid는 아니다. 전통적인 Hybrid는 view를 쓰기위해 webview를 쓰고 이에 대한 브라우져가 os에 설치되어 있어야 view 표현이 가능했다. 그러나 eletron은 view를 내장하고 있고 standalone으로 application구현이 가능하다.

  + render process (chrome) + main process (node) 간에 RPC통신을 한다. 


- Psyclone: Automated Dynamic Testing

  + https://github.com/firejune/psyclone 

  + Node Canvas: main process에서 수행됨

  + Environment: PTY.js, openCV (게임의 이미지 체크)




Javascript playground 세션


- Swift playground와 같은 형태이다.

- Runtime Context Visualizer 구현하기 

  > 내가 찍어 놓은 console.log를 추적 

  > let stack = new Error().stack 강제 로그 stack-trace 남기기

  > 외계어 스터디 (구글검색하면 나옴): 개발을 모르는 사람들에게 무언가 가르칠 때 힘들다. 코딩하는 것을 비쥬얼라이징 해보자. 

- V8 엔진은 Debugging이 가능한 API를 가지고 있다. 

  > node의 vm module을 사용: v8내에서 다양하게 쓰이는 것을 외부로 노출해 준다.

     runInContext, runInNewContext 등등

- node-inspector

  > IDE 수준의 code base로 꽤 큰 프로젝트

  > DEBUG=*node-debug app.js 하면 node debugging 을 inspector로 가능하다 

  > node v6.3.1 에서만 작동한다. node에 inspector를 merge하는 작업 진행중. 

     v8-debug : node <-> inspector간 내용

     devtools : inspector <-> chrome devtools간 내용


- Node debug mode 를 이용해 자바스크립트 내용을 축출한다

  > node --debug --debug-port=5859 --debug-brk app.js

      Debugger listening:5859

  > v8 debugging protocol using http

  > 전문의 body에 seq, type 이 들어간다. 

     type = request + response + event 포함 


- Node debugger Command 

  > continue : 코드 진행 next, in, out, min

  > backtrace : 코드가 멈춰있을 때 모든 정보를 가져온다 

  > frame : 방금 실행한 것을 이전 상태로 rollback에서 수행 가능하다 

  > setVariableValue : runtime의 로컬 변수를 직접 수정

  > lookup : 로컬 변수로 watching 모니터링 할 수 있다. 


해당 명령을 tcp로 node debugger에 쏴주면 된다. @node/lib/_debugger.js 가 위의 명령어를 사용하고 있다. 

  > npm install v8-debugger


- Javascript Playground 

  > 왼쪽 자바스크립트 코드 오른쪽 결과 값을 보여주기 화면을 제작한다

  > onResponse 핸들러에서 결과 값을 받는다. 

  > 코드의 의미 파악: 식, 문을 파악해야 함 -> Javascript Parser 필요, esprima 파서 

     esprima.parse(코드) 결과는 각 진행 수선의 type을 전달 하는 메타 정보를 준다

  > Runtime Context Visualizer

     https://github.com/ibare/jsplay


 


참조


http://techblog.daliworks.net/Nightwatchjs/ 

posted by 윤영식
2016. 11. 23. 14:23 Angular/Concept

오늘은 오후 일정을 비우고 PlayNode 컨퍼런스를 참석했다. 첫 시간은 늘 사용해 보아도 익숙해 지지 않는 RxJS시간이다. 



- Promise vs Observable 차이점

  + Observable에서 multi value처리 가능. stream이니깐 당연하다. 

  + lazy 기능으로 subscribe 했을 때 수행한다 

  + unsubscribe를 통해 cancelable할 수 있다. 

  + completion 콜백


- Operator

  + 200개 가량의 오퍼레이터 현재 v5.0.0-rc.4

  + create, fromEvent, mergeMap (flatMap)

    > mergeMap: 여러 observable을 하나의 observable로 만드는 오퍼레이터 

  + filtering 

    > takeUtil : 특정 Observable이 발생하면 observable생성을 멈춘다 p61

  + composition

    > combileLatest p63: 다른 observable의 마지막 값들을 합쳐서 obserbale을 만들어 준다 

    > zip : 각 observable에서 발생한 순번의 것들을 서로 묶어준다

  + error

    > retry: error 발생하면 2두번 더 실행한다 

    > retryWhen: 재시작 시점을 지정 가능하다  p72


- 비동기 코드 조합하기 p77

  + Drag & Drop

    > mousedown, mousemove, mouseup이벤트의 조합 p80: mousedown+ mousemove를 flatmap으로 조합하고 takeUtill에서 mouseup이 발생하면 대상 dom을 이동

  + Cache + DB

    > merge를 통해 가장 먼저온것을 take(1)으로 선택한다 

  + AWS Lambda p90

    > bindNodeCallback을 사용하면 node스타일 콜백을 observable로 변환가능하고 이를 다른 observable과 합친다

  + On / offline 브라우져에서 

    > retry 로 에러 발생시 재 시작토록 구현 p108

    > websocket에서 retryWhen으로 on / offline을 체크할 수 있다. 


- 장단점 p113



참조 

  - http://www.slideshare.net/kyungyeolkim39/compose-async-with-rxjs-69421413 













posted by 윤영식
2016. 11. 11. 20:18 Meteor

미티어 스쿨에서 미티어를 다시 들여다보기 시작. 



미티어 설치 


$ curl https://install.meteor.com/ | sh


프로젝트 생성


$ meteor create addressBook

 Downloading templating-compiler@1.2.1...  [====================       ] 74% 5.1s



수행하기 

  - 의존성 관리는 미티어가 알아서 한다

  - --production 옵션을 주면 여러개의 파일을 한개 파일로 번들링 해준다 

$ cd addressBook

$ meteor run 


에러 발생시 

$ meteor npm install --save babel-runtime




MongoDB


몽고디비 접근 

  - wired tiger 적용

  - 기본 3001 포트를 사용

$ meteor mongo

MongoDB shell version: 3.2.6

connecting to: 127.0.0.1:3001/meteor


local 디비 사용 

meteor:PRIMARY> show dbs

local  0.000GB

meteor:PRIMARY> use local

switched to db local

meteor:PRIMARY> show collections

me

oplog.rs

replset.election

startup_log

system.replset

meteor:PRIMARY> db.oplog.rs.find().pretty()




Meteor Shell 사용


미티어는 NodeJS위에 올라간다. 이에 대한 내용을 볼 수 있다. 

$ meteor shell



Meteor 폴더 구조


.meteor  폴더

버전 확인하기 

  .meteor/versions 파일에서 확인 가능 

$ meteor add <Module>@<version>


미티어 릴리즈 버전

  .meteor/release 에서 확인 가능

METEOR@1.4.2.1



플랫폼

  .meteor/platform

  여러 플랫폼을 지원 server, browser 또는 ios, android 등 추가 가능 

  


client

  javscript, assets 


lib

  공통 


server

  서버의 메소드를 call하고 싶을 경우, 메소드는 RPC와 유사하다 


==> client, lib, server를 자유롭게 depth로 줘서 운영이 가능하다 

posts/client

posts/lib

posts/server

house/client

house/lib

house/server


또는 


client/post

client/house

lib/post

lib/house

server/post

server/house


public 

  "/" 루트로 웹서버 구실을 한다. public을 별도의 웹서버로 올릴 수 있다. 



폴더 로딩시에 main.js파일은 가자 나중에 로딩된다. 




NPM 설치 

$ meteor npm install <module>





MongoDB 사용하기 


RDB에서의 관계에서 벗어나 도큐먼트로 표현 그리고 관계를 다시 만들어 내는 GraphDB에 관심을 가지면 종착역


  - 미티어에서는 Shard사용 안됨

  - Replica Set: Primary + Secondary1,2

  - Shard: collections을 나누어서 저장 - 키를 나누는게 중요, mongos (router)를 통해 샤드된다, 정말 큰 데이터 아닌 이상 샤드를 쓸 필요없다


GridFS


  - 바이너리 파일을 작은 Chunk단위로 쪼개서 저장한다 

  - 파일에 대한 Replication을 한다 

  - files: 파일의 정보만 존재, chunks: 실제 파일의 내용이 저장 



posted by 윤영식
2016. 10. 23. 22:59 Angular/Concept

Angular v2가 정식 릴리즈되었다. Angular v1 은 Two-way data-binding 이라는 독특한 특징으로 인해 많은 사용자 층을 확보했지만 장점 만큼이나 성능상의 단점도 존재했었다. 또한 처음엔 쉬운듯 하면서 좀 더 깊게 들어가볼려고 하면 학습곡선이 갑자기 껑충뛰기도 했다. 가장 많이 사용했던 Directive(지시자)가 대표적이다. 많은 개발자가 만들어 놓은 지시자를 쉽게 가져다 쓸 수는 있지만 직접 만들어 애플리케이션에 접목하려 할 때 첫 문턱을 만나게 된다. 그리고 jQuery사용에 익숙한 개발자에게 Angular v1 시점상의 차이로 Angular v1 방식의 개발패턴을 요구하기도 했다. 관성은 무섭다. 기존에 사용하던 방식을 버리고 Angular v1에 맞춰서 애플리케이션을 만들어 가기란 곤혹스럽다. Angular v2 또한 그런 인식의 전환을 요구할까? 그렇다 그리고 아니다. 






웹 애플리케이션 흐름

웹 애플리케이션 개발을 위해 우리가 사용하는 jQuery같은 라이브러리나 Angular, Backbone같은 프레임워크의 가장 1차적인 목적은 무엇일까? 나는 Data Projection이라 생각한다. 데이터를 화면에 출력하기 위해 DOM을 얼마나 쉽게 조작하고 상호 작용할 수 있느냐가 선택의 기준이라 생각한다. Data Projection을 일관되고 확장가능하고 배포가능하게 하는 방식으로 기술은 발전해 왔고, 현재는 화면에 대한 제어방식이 컴포넌트 기반 방식으로 발전해 오고 있다. 


Data Projection의 역사를 보면 초장기엔 Server Side Rendering 를 사용해 웹 애플리케이션을 개발했다. 예로 JSP, PHP, ASP 같이 서버 미들웨어서 데이터를 조회하고 HTML을 조작하여 결과 HTML을 브라우져에 전송하던 시대이다. 




1세대에는 AJAX가 나오고 다양한 라이브러리나 프레임워크가 나왔다. 이때는 데이터변경에 대한 DOM반영이 서버에서 클라이언트 개발자의 몫으로 넘어오게 되었다. 즉, 직접 DOM 을 얻어와서 특정 위치에 넣어 주어야 했고, DOM에서 발생하는 이벤트를 Listening해서 처리하고 DOM에 반영하는 모든 작업이 웹 개발자가 직접 코딩하던 단계였다. Java의 프레임워크 역사로 보면 Struts 로 비유할 수 있지 않을까 싶다. 




2세대로 넘어오게 되면 Model을 DOM 에 반영하는 방식은 자동화 된다. 여기에 대표적인 프레임워크가 Ember 와 Angular v1 이다. 이때 부터 Single Page Application (SPA) 개발이라는 용어가 나오게 된다. URI 변경에 대한 대응으로 Routing  개념이 나오고, Data Projection후 원하는 일부 DOM을 변경하는 역할이 프레임워크로 넘어갔고, 웹 개발자는 좀 더 애플리케이션 비즈니스 로직에 집중토록 만들었다. Java 프레임워크로 비유하자면 Struts와 Spring Framework 초기버전의 중간 지대 정도 쯤이라 생각한다.  이때부터 Frontend (프론트앤드)라는 직군이 웹 개발자와 분리되기 시작한 지점이라 생각한다. 이에 대한 자세한 설명은 태곤님이 작성한 "[번역] 프론트엔드 개발자는 왜 구하기 어렵나요?"를 참조하자. 2011년을 기점으로 2013년 웹 애플리케이션 프레임워크가 정착을 해가는 시기였고, 현재는 대부분의 스타트업이나 중견기업에서 2세대 웹 애플리케이션 프레임워크를 선택할 경우 프론트엔드 개발자와 백앤드 개발자를 구분하여 팀을 구성하고 있는 추세이다.





3세대는 2세대의 과도기를 거쳐 2세대의 장점을 흡수 하면서 성능상의 이슈를 해결하고, 점점 복잡해 지고있는 웹 애플리케이션을 보다 직관적이고 쉽게 개발할 수 있게 노력하고 있다. 대표적인 프레임워크로는 Facebook의 React와 Google의 Angular v2 (이하 Angular)이다. Angular는 Component기반 개발 방식으로 표준인 Web Components를 지원하며 Typescript를 기본 언어로 채택했다. Typescript는 Type 시스템을 제공하기 때문에 개발단계에서 버그의 가능성을 쉽게 찾을 수 있도록 도와준다. React와 Angular에 대한 장단점은 손창욱님의 "React보다 Angular v2에 더 주목해야 하는 이유"를 참조하자. Java의 Spring Framework이 성숙하면서 Annotation 같은 기능이 추가되듯, Angular v2 프레임워크는 Java의 Spring 프레임워크 최신버전과 비유할 수 있다. 



Angular v1에 대한 개발 및 컨설팅을 3년 가까이 하면서 올해 초 Angular v2를 공부하고 기존 v1 코드를 v2 코드로 전환하면서 코드 베이스는 50%가량 줄었고, 반응속도는 30%가량 개선되었다. 8명 프론트앤드 개발자와 컨버전을 진행하면서 이구동성으로 말하는 것은 "코드가 직관적으로 변했다. 코드량이 현저히 줄었다. Typescript의 타입체킹으로 인해 실수를 최소화 할 수 있었다" 이다. 



Angular v2 왜 배워야 하는가?

Angular를 왜 배워야 하는가? 답하자면 안배워도 된다. 단순 홈페이지나 업무 화면이라면 쉽고 더 빨리 만들 수 있는 워드프레스나 서비스를 이용하거나 DOM 핸들링 라이브러리나 플러그인을 사용해 개발하는 편이 낫다. 하지만 솔루션의 복잡한 요구사항을 지속적으로 반영해야 하고 DOM제어가 복잡해 질 가능성이 높다면 jQuery, React 같은 라이브러리 보다는 Angular 같은 프레임워크를 선택하는 것이 좋다. 그리고 최근에는 ES2015 표준이 확정되었고 최신 브라우져에 대부분 기능이 구현되고 있다. 2세대와 3세대 Data Projection의 가장 큰 개발 방식의 차이는 ES2015의 이해에서부터 시작한다.  즉, ES2015 문법을 잘 알고 사용하면 좀 더 쉽고 간단하게 코드 베이스를 유지하면서 오류를 최소화할 수 있다. 예로 -> 펑션은 this에 대한 오류를 방지하고, Set/Map등 Collection은 Java의 Collection과 유사한다. 



Angular v2 시작하면 초기에 배워야 하는 것들이 갑자기 늘어난다. 이것은 2세대와 3세대의 개발 패턴이 바뀌었음을 시사한다. ES2015 문법은 그대로 TypeScript에 녹아 있고, Type System과 Annotation 기능이 녹아 들어 더욱 편리한 개발을 가능토록 한다. 따라서 ES2015의 Syntax와 개념을 이해해야 한다. 그리고 Typescript를 다시 공부해야 한다. 또한 요즘 인기를 누리고 있는 Reactive Programming을 표방한 대표적인 라이브러리인 RxJS를 Angular가 근간으로 사용하고 있다. 따라서 RxJS 에 대한 개념과 사용법을 익혀야 한다. 그런후 Web Components 란 무엇인지 알아야 하고, Angular 프레임워크의 아키텍쳐를 구성하는 개념인 Change Detection 동작원리, Dependency Management, Modulization 을 알아야 하고, 다음으로 주변의 Tooling System으로 SystemJS (Webpack), Gulp 등을 알아야 한다. 


이렇게 열거해 보니 참으로 배울 것이 많다. 다시 말하지만 안 배워도 된다. 하지만 자신의 근육을 한단계 업그레이드 시키기 위해 고통스러운 인내의 시간은 필요하다. 배워야 하는 기준은 두가지 정도로 이야기 해본다. 


첫째, 서비스 버전업을 위해 요구사항이 계속 증가하고 있는가?

둘째, 더 적고 직관적인 코드 베이스를 유지하면서 성능을 높이고 싶은가?


 

프론트엔드 개발자 직군이 새롭게 자리잡게된  5년기간 동안 많은 부분이 기존의 백앤드 개발 패턴과 유사해 지고 있다. 모듈 의존성 관리, 빌드 시스템, 프레임워크의 발전은 Java개발자들이 초장기 프레임워크 없이 개발하다 Struts를 만났을 때 기쁨에서 Spring을 만나 자유를 얻었지만 여전히 배워야 할 것들은 더욱 증가했음을 알것이다. 그러나 어쩌겠는가 우리는 더 게을러 지고싶다는 욕구가 있고 프레임워크가 그것을 만족시켜줄것이라는 희망을 품고 있는 한 배움과 진보는 계속될 뿐이다. 



참조


posted by 윤영식
2016. 5. 1. 15:34 Angular/Concept

컴포넌트 기반 개발시에 어떤 설계방식으로 해야하는지 알아본다. 새롭게 알게된 GistRun 서비스를 사용해서 테스트해 볼 것이다. 예제의 내용은 최근 Rangle.io의 Angular2 Component 온라인 강좌를 참조한다.





GistRun 사용하기 


github기능중 코드 조각을 관리할 수 있는 서비스가 있다. 한번에 최대 10개까지 파일을 만들 수 있다.  여기를 클릭해 보면 Gist에 입력한 한 주제에 대한 파일을 보여주고 Gist의 내역을 테스트 해 볼 수 있다. 



plunker 또는 jsfiddle의 내용도 불러와서 나의 Gist에 저장을 할 수 있다. 각 서비스의 장점이 있지만 일단 GistRun은 UI가 깔끔하고 속도가 빠르다. 그리고 수정사항에 대한 버전을 관리할 수 있고, Github의 종속된 서비스이므로 소스를 관리한다는 입장에 일관성을 가질 수 있을 것으로 보인다. Gist만으로 모자랐던 것을 GistRun이 생명력을 불어 넣은 격이다. 





Angular2 Component 가이드


Angular2는 컴포넌트로 시작해서 컴포넌트로 끝난다. 컴포넌트기반으로 UI를 설계할 때 자주 나오는 방식이 프리젠테이션과 컨테이너의 분리이다. 


  - Container 컴포넌트

    + 데이터와 비즈니스 로직을 다룬다

    + 컴포넌트 트리(Tree)를 렌더링 한다

    + 재사용하기 어렵다 


  - Presentational 컴포넌트

    + 상태를 포함하지 않는다. 따라서 컴포넌트 속성에 대한 수순(pure) 펑션으로 구성한다

    + 표현만을 담당한다

    + 재사용이 가능하다 


Thinking in React의 내용은 Angular2의 컴포넌트 개발 방식과 거의 일치한다. Container 컴포넌트는 하위 컴포넌트의 이벤트에 대해 XHR 요청을 수행하는 Angular2 Service를 Inject해서 서버로 부터 데이터를 요청하고, Component Tree를 통해 하위로 데이터를 내려 보낼 수 있다. 



오렌지색 부분은 전체 애플리케이션을 감싸는 Container이고 초록색은 테이블의 Row를 표현한다. 프리젠테이션 부분은 상단의 Search Input, 하단의 Row들이 된다. Angular2에서 검색을 위한 Input과 Button, Title 애플리케이션을 다음과 같이 진행한다. 



Seach The Site 레이블을 표현하는 컴포넌트를 개발한다.  @은 Typescript의 Decorator를 이용해 Angular2에 구현된 것으로 Parent -> Child 방향으로 DOM Properties를 통해 값을 받고자 할 때 사용한다. 즉, RangleLabel 컴포넌트를 사용하는 Parent 컴포넌트가 name 속성에 [] 을 이용해 값을 설정한다.  

  - 컴포넌트를 사용할 때 [name]="<expression>"  [name] 부분을 target이라 하고 <expression> 부분을 source라고 한다. 

  - []을 사용할 때 source는 항상 template expression 즉, 식이어야 한다. (statement "문"은 이벤트에서 사용함) 

  - target에 []가 있으면 source는 항상 expression으로 수행된다.

import { Component, Input } from 'angular2/core';


@Component({

  selector: 'rangle-label',

  template: '<label class="rangle-label">{{ name }}</label>',

  styles: [ `

    .rangle-label {

      color: #422D3F;

      display: block;

      font-weight: bold;

      letter-spacing: .2em;

      text-transform: uppercase;

    }

  `]

})

export class RangleLabel {

  @Input() private name: string;

}


예) 부모 컨테이너에서 사용할 때: 부모 컨테이너 컴포넌트의 name 속성을 자식 컴포넌트인 rangle-label에 내려보낸다.  

     <rangle-label [name]="name"></rangle-label>


다음으로 Input 컴포넌트를 만든다. value 속성에 대해 ngModel처럼 양방향 바인딩을 주기 위해서는 컨벤션(Convention)처럼 Input은 value이고, Output은 valueChange이어야 한다. 

  - [()] 표식은 banana in the box 표현으로 양방향 데이터 바인딩이다. 

  - [] 은 Input으로 parent -> child로 속성값을 내려 보낼 수 있다. (top down)

  - () 은 Output으로 child -> parent로 값을 올려 보낼 수 있다. (bubble up)

import { Component, Input, Output, EventEmitter } from 'angular2/core';


@Component({

  selector: 'rangle-text-field',

  template: `

    <input class="rangle-text-field"

      [placeholder]="placeholder"

      #field (keyup)="handleKeyup(field.value)">

  `,

  styles: [ `

    .rangle-text-field {

      border-radius: 3px;

      border: 1px solid #ccc;

      box-sizing: border-box;

      display: inline-block;

      font-size: inherit;

      font-weight: inherit;

      height: 2.5rem;

      padding: .5rem;

    }

  `]

})

export class RangleTextField {

  @Input() private placeholder: string;

  @Input() private value: String;

  @Output() private valueChange = new EventEmitter<String>();


  handleKeyup(fieldValue: string): void {

    this.valueChange.emit(fieldValue);

  }

}


예) 부모 컨테이너에서 사용할 때 searchTerm은 부모 컨테이너 컴포넌트의 속성이다. value를 내려보내기도 하고, 이벤트를 받기도 한다. 

      <rangle-text-field 

        placeholder="Enter Keyword"

        [(value)]="searchTerm">

      </rangle-text-field>


버튼을 만들어 보자. 템플릿의 target=source 에서 target이 ()로 감싸지면 이벤트를 나타내고 source는 statement "문"을 쓴다. expression과 statement에 대한 이해는 Angular.io의 Template Syntax 설명을 참조한다.  여기서는 클릭이 되면 바로 부모의 handleSearch가 호출된다. 

import { Component, Input, Output, EventEmitter } from 'angular2/core'


@Component({

  selector: 'rangle-button',

  template: `

    <button

      [ngClass]="dynamicStyles()"

      class="rangle-button"

      (click)="onClick.emit()">

      {{ name }}

    </button>

  `,

  styles: [ `

    :host {

      display: flex;

      align-items: stretch;

    }

    .rangle-button {

      border: none;

      border-radius: 3px;

      color: white;

      font-weight: bold;

      letter-spacing: .2em;

      margin-left: 0.5rem;

      padding: 0.5rem;

      text-transform: uppercase;

    }

    .primary {

      background: #E5373A;

    }

    .normal {

      background: #422D3F;

    }

  `]

})

export class RangleButton {

  @Input() name: string;

  @Input() isPrimary: boolean;

  @Output() onClick = new EventEmitter();


  dynamicStyles() {

    return this.isPrimary ? 'primary' : 'normal';

  }

}


예) 부모 컨테이너 컴포넌트에서 사용할 때, handleSearch는 부모 컨테이너 컴포넌트의 메소드이다. 

      <rangle-button name="Search"

           [isPrimary]="true"

           (click)="handleSearch(searchTerm)">

      </rangle-button>


다음으로 Input 과 Button 컴포넌트를 재사용할 수 있는 컨테이너를 만들어 본다. Label만을 포함하고 있고 언제는 원하는 형태로 Input과 Button을 템플릿상에 포함 시킬 수 있다. 이를 위해 ng-content 태그를 사용한다. Angular v1의 transclude와 유사하다. 하지만 큰 차이점은 역시 Angular2의 컴포넌트 아키텍쳐는 Comopnent Tree이기 때문에 Change Detection(CD)는 항시 가장 위에서 아래로 점검되고 렌더링된다. Angular v1은 parent - child 관계가 있다하더라도 Parent가 먼저 렌더링 될지 Child가 먼저될지 보장을 못했다. (물론 Directive에 priority 옵션이 있지만 적용하기에 따라 순서가 정확한지 알 수 없었다.) 즉, Angular2에서 ng-content 태그를 사용해도 렌더링에 예측이 가능하다. 





import { Component, Input } from 'angular2/core';

import { RangleLabel } from './rangle-label';


@Component({

  selector: 'rangle-bar',

  directives: [ RangleLabel ],

  template: `

    <rangle-label [name]="name">

    </rangle-label>

    <div class="row">

      <ng-content></ng-content>

    </div>

  `,

  styles: [`

    :host {

      background: #F8F8F8;

      border: solid #ccc 1px;

      display: block;

      padding: 1rem;

      margin: 1rem;

    }

    .row {

      display: flex;

      margin-top: 0.5rem;

    }

  `]

})

export class RangleBar {

  @Input() name: string;

}


예) 부모 컨테이너 컴포넌트 사용 때 

    input과 button이 있는 경우 
    <rangle-bar name="Search the site">
        <rangle-text-field placeholder="Enter Keyword"
             [(value)]="searchTerm">
        </rangle-text-field>
        <rangle-button name="Search"
            [isPrimary]="true"
            (click)="handleSearch(searchTerm)">
        </rangle-button>
    </rangle-bar>

    또는 
   
   button만 있는 경우 
   <rangle-bar name="Other Stuff">
        <rangle-button name="Button 1"
            [isPrimary]="true">
        </rangle-button>
        <rangle-button name="Button 2"></rangle-button>
        <rangle-button name="Button 3"></rangle-button>
    </rangle-bar>


당연히 <ng-content>에는 input, button 컴포넌트외에 다양한 컴포넌트가 올 수 있다. 결과는 다음과 같다. 



실데이터를 요청하는 코드는 RangleBar 에서 XHR에 대한 요청을 하고 결과를 전달하는 과정을 거치면 될 된다. Redux를 사용한다면 Action Creator를 수행한다. 애플리케이션 소스를 보자. App 컴포넌트는 가장 최상위 애플리케이션으로 Container 컴포넌트와 Presentational 컴포넌트를 사용해 화면 레이아웃을 만들고 있다. 

import { ViewEncapsulation, Component } from 'angular2/core';

import { RangleBar }  from './rangle-bar';

import { RangleButton } from './rangle-button';

import { RangleTextField } from './rangle-text-field';


@Component({

  selector: 'app',

  directives: [ RangleBar, RangleTextField, RangleButton ],

  template: `

    <rangle-bar name="Search the site">

      <rangle-text-field placeholder="Enter Keyword"

        [(value)]="searchTerm">

      </rangle-text-field>

      <rangle-button name="Search"

        [isPrimary]="true"

        (click)="handleSearch(searchTerm)">

      </rangle-button>

    </rangle-bar>


    <rangle-bar name="Other Stuff">

      <rangle-button name="Button 1"

        [isPrimary]="true">

      </rangle-button>

      <rangle-button name="Button 2"></rangle-button>

      <rangle-button name="Button 3"></rangle-button>

    </rangle-bar>

    <p> inside viewCapsulation </p>

  `,

  styles: [ 'p { background: red; border: dashed yellow 2px; }' ],

  encapsulation: ViewEncapsulation.Native

})

export class App {

  private searchTerm: string;


  handleSearch(searchTerm: string): void {

    alert(`You searched for '${searchTerm}'`);

  }

}


GistRun의 소스와 Rangle.io 동영상을 참조하자.

  - Container & Presentational Component 개발 방식에 대한 소개 

  - Component LifeCycle에 대한 소개: ng-content를 특별히 View Content라 하고, 그외 템플릿에 직접 설정된 컴포넌트를 View Child라 한다. Life Cycle에서는 둘의 시점이 나뉘어져 있다. View Content가 먼저 호출된다.  

  - ElementRef 주입받아 컴포넌트의 DOM을 사용할 수 있다.





<참조>

  

  - Angular2 Component Basic (pptsrc)- Rangle.io

  - Thinking in React

  - Presentational and Container Component - Dan Abramov

  - Rangle.io's Angular2 GitBook 

  - Change Detection Reinvented - Victor Savkin's

posted by 윤영식
2016. 4. 18. 20:46 Electron & Ionic

Angular2-seed에 Desktop 애플리케이션을 만들수 있는 Electron 기술과 네이티브 모바일 앱을 만들 수있는 NativeScript을 붙여서 확장한 Seed가 Angular2-seed-advanced 이다. Advanced 시드의 내용을 보면 Typescript의 장점을 살려서 OOP 방식으로 Build 환경과 코드를 재사용하면서 Web, Desktop, Native Mobile App을 만들 수 있는 환경을 제공한다. Advanced를 참조해서 Angular2-seed를 기반으로 Hybrid Mobile App을 만들 수 있는 Ionic2 프레임워크를 합쳐서  Web, Hybrid Mobile App용 Seed를 만들고자 한다. 기존에 나와 있는 ionic2-seed도 참조해 App 개발을 위한 SDK도 포함하는 Advanced 버전을 만든다. 





1. Action Plan


어떤 작업을 해야할지 마인드 맵으로 그려보았다. 먼저 Angular2의 Seed 소스를 분석하고 Ionic2의 새로운 개념을 알아본다. 그리고 Angular2 Code Style 과 Sass 스타일을 정할 예정이다. 분석이 끝나면 Gulp 기반으로 Web과 Mobile을 위한 빌드 환경을 만든다. 그리고 Web, Mobile 개발 환경의 폴더 구조를 만든다. Ionic2는 별도의 Ionic CLI(Command Line Interface)를 제공하기 때문에 기존 Angular2-seed와 어떻게 합칠지가 관건이다. 다음으로 Framework을 Hierarchical Layer로  SDK, Biz Context, Common 로 구성할 것이다. Angular2는 ES2015와 TypeScript 둘다 지원하고 ES2015의 Module System 문법을 사용할 수 있다. 즉, 컴포넌트를 모듈단위로 나누고 역할에 따라 계층을 나누어 Framework을 구성한다. 


환경과 프레임워크가 준비되면 샘플 프로토타입핑을 통해 Angular2-seed-ionic2가 잘 도는지 확인을 하고 일반적인 화면 예제를(MVP) 만들어 다양한 예를 통해 가이드 한다.  


필요 가이드 문서는 다음과 같다. 


  - Code Style Guide

  - Environment Guide

  - Framework Guide 

  - 10-Minutes Starting Guide (with prototyping)

  - Several Sample Guide (with MVP)






2. Project seed contents


환경과 프레임워크에 대한 자세한 내용이다. 환경은 Web과 Hybrid Mobile App을 위한 빌드와 테스트 환경을 갖추는게 목표이다. 그리고 프레임워크에는 계층형 레이어를 통해 필요한 요소를 Angular2 Components로 만들어 놓을 것이다. 일단 다음과 같은 과정을 거치면 좋을 것 같다. 


  - Step 1 : Angular2-seed-ionic2를 통해 Environment와 Framework을 최초에 만든다. 

  - Step 2 : Anguar-CLI를 통해 Angular2 Component 코드를 자동생성한다. (옵션)



대략 한달간의 기간으로 바로 Prototyping이 가능한 수준의 seed를 만들어 보고자 한다. 잘 되야 할텐데...





참조


- X-Mind (free version) 파일 

Front-end Next Generation Stack.xmind

- Angular CLI 

- Angular2 Master Starter Kit

- Ionic2 Seed (*)

- Angular2 Eduction 목록

- Angular2 Awesome 목록

- Angular2 Style Guide - Rangle.io

- Angular2 Code Style Guide - Mgechev

posted by 윤영식
2016. 4. 16. 22:27 Angular/Concept

ExtJSAngular2의 기술적 차이점에 대한 질문을 받게되어 어떻게 대답을 하면 될까? 를 고민하다 정리를 해본다. ExtJS 는 일부 기능은 무료 오픈소스이지만 전체 기능을 사용하기 위해서는 유료이다. 현재 v6 까지 나와있다. 또한 최신버전은 Sencha라는 이름으로 통합되어 나오고, 현재 ExtJS v6 버전을 다운로드 받아 사용할 수도 있다. 따라서 ExtJS나 Sencha 에서 이야기하는 장점이라 말하는 부분을 토대로 Angular v2와 비교해 보기로 한다. 참조는 Top 8 Reasons Why Enterprises Prefer Sencha ExtJS over Angular 문서를 보고 ExtJS 쪽은 영문 요약을 간단히 했고, Angular 쪽은 영어로 작성해 본다.


This document is to write differences between ExtJS v6  framework and Angular v2 framework. I reference the ExtJS site (Top 8 Reasons Why Enterprises Prefer Sencha ExtJS over Angular) and I write my opinion about Angular.

*caution: AngularJS is Angular v1, Angular v2 or Angular is Angular v2. ExtJS is ExtJS v6.





Reason #1 Components, Components, Components


 - ExtJS

   + ExtJS contains components that are optimized for both desktop and mobile devices.

   + customize the theme. mobile apps can be themed to achieve an iOS, Android,  BlackBerry the look and feel.

   + Angular does not come with a component library.


 - Angular v2

  + Angular can easily make components that are usable anytime. If we want to use components i.e grids and charts, we can use the components that have already been made by many companies and open source developers.

  + Developer can build an application with components  and can also use the current web technology such as Web Components together.

  + Angular component architecture is a component-tree for improving performance to render web page views. This architecture is implemented in the ReactJS Framework from Facebook as well.

  + Angular can easily merge with the more popular CSS Framework such as Twitter Bootstrap, Material Design, Semantic UI and Foundation which can be customized to match with any company brand. One of these can be chosen for any brand style.

  + Angular is a platform for the web and mobile. Ionic v2 is a Hybrid mobile app framework. It is based on Angular v2 and has tools that can rapidly develop an app. So, the hybrid app can be developed using Angular in a friendly code style. The hybrid app gives customers a better UX(User eXperience) than mobile browsing.

  + Ionic v2 using Angular has lots of mobile components to support the look and feel for different mobile platforms such as iOS, Android and BlackBerry. We can also customize these styles.





Reason #2 ExtJS Has Ben Battle-Tested Since 2007


 - ExtJS

   + It is launched in 2007.

   + It has long-term success.

   + migration v5 to v6 smoothly


 - Angular v2

   + Angular v1 was launched on October 20, 2010 by Google.

   + Angular v1 also has had long-term success i.e NBC, Intel, ABC News and approximately 8,400 other sites out of 1 million tested in July 2015.

   + Angular v2 already has an upgrade tool to migrate v1 to v2.






Reason #3 A Robust Framework for Building Apps vs Building One's Own Framework


 - ExtJS

   + ExtJS has MVC(Model View Controller)/MVVM (Model View ViewModel) architecture.

   + ExtJS comes with an extensive component library.


 - Angular v2

   + Angular has MVC/MVVM as well.

   + Angular is easily customized for any application's architecture. It can be applied to the one-way data flow architecture like Flux from Facebook in order to easily manage any application's state.

   + Angular is an open source framework so, many developers and companies open their components like grids or charts that have been used within their applications. If there are  components with any issues, many contributors can solve the problems in the open system and components can easily be downloaded from consistency tools such as NPM (Node Package Manager) or Bower.

   + Angular v2 is a new platform for the modern web environment including Web Components, Reactive Programming and Immutable state to solve some issues which Angular v1 experienced. Applications can be developed to be more stable with better performance using these concepts.





Reason #4 Clearly-Defined Legacy Browser Compatibility By Default


 - ExtJS

   + support Internet Explorer (IE) 8


 - Angular v2

   + Angular can support IE 9 (link).

   + If IE 8 is to be supported, poly-fill can be used to support the lower version but MicroSoft has already stopped updating IE 8 securities. So, this version is not recommended because of the danger of hacking.





Reason #5 Integrated Tools Created With a Clear Vision and Purpose


 - ExtJS

   + Senchar has several tools including Senchar Cmd, IDE Plugins, and Senchar Inspector that developers can use to speed up their application development.


 - Angular v2

   + Angular uses the Gulp or Grunt tasker that can extend plugins which are required.

   + There are IDE Plugins (WebStorm, Atom, Sublime Text, MS Code) for Angular  and developers can check out an application's performance with Angular Inspector under the  chrome extension as well.

   + Angular uses the NPM (Node Package Manager) or Bower that all front-end developers use to manage the packages and components for any application.

   + Angular is oriented to use common tooling set in current front-end environments. So, the developer can use these tools in a friendlier way.





Reason #6 No Need to Learn TypeScript or other tools and component libraries with ExtJS6


 - ExtJS

   + ExtJS 6 is a JavaScript Framework.

   + Developer doesn't need to have experience with object-oriented programming (OOP)


 - Angular v2

   + Javascript before ECMAScript 5 doesn't support the OOP but ECMAScript 6 (ES2015) can support it and the developer can simply establish more complex applications with the OOP methodology.

   + TypeScript is a superset of ES2015 and has more features simply to code any sophisticated application such as Decorator. Typescript also includes a feature that transpiles code to ES5 or ES3 code, so it can be released into the production environment without worry.

   + TypeScript can support the Static Type Checking System during the development period. TypeScript can automatically suggest some problems in code so, the developer can recover the mistakes which occured in run-time.

   + If the developer has experience with Java or OOP, they can easily learn TypeScript. It is not a weakness, but rather a strength.





Reason #7 Excellent Design Tools


 - ExtJS

   + Sencha has an excellent set of design tools.

   + Sencha Architect is a perfect tool to create clickable prototypes.

   + ExtJS Stencils can be used to create wireframes and mockups that correctly reflect the look and feel of components


 - Angular v2

   + Angular doesn't have a design tool because it is optional. If it is needed, other professional design or mockup tools can be used .

   + Ionic v2 based on Angular v2 also has  a design tool such as Ionic Creator for mobile and has a testable native app in several mobile platforms (iOS, Android) such as Ionic Viewer.

   + The Angular team has been working closely together with the Ionic team.





Reason #8 Awesome Support and Training Options From the Creators of the Framework


 - ExtJS

   + Sencha has excellent support and training teams.

   + Sencha has a professional services team that can assist with a variety of enterprise development needs.


 - Angular v2

   + There are several professional Angular training companies such as Rangle.io and Egghead.io.

   + Global conferences are always held several times annually such as NG-Conf.

   + If developers want to learn Angular, they can easily get a huge range of materials like books, videos and online courses.

   + The Angular team at Google consists of 20 full-time developers and there are over 221 contributors for Angular v2.

   + It is not a level playing field when comparing ExtJS with Angular in my opinion.



ExtJS is a good framework and has a full set of tools for web development but it can restrict customization needs, because developers can just play around with ExtJS's environment and architecture. The current web trend - software and hardware - has been changing quickly so if some applications need to be adapted into the current environment, Angular v2 would be an excellent choice. Angular v2 can provide any company lots of opportunities to improve the UX and performance for applications but more time needs to be invested learning this framework. 


기회가 된다면 다음부터는 영어 블로그도 써볼 생각이다. 그리고 영어 Angular 관련 책을 출판해 보고 싶다. O'Reilly 또는 Packt Publishing 같은 곳과 연이 된다면... 그전에 열심히 영문 블로깅하면서 영작 실력을 키워야겠지만... 비오는 토요일 밤에...




Reference

  - Top 8 Reasons Why Enterprises Prefer Sencha Ext JS over Angular

posted by 윤영식
prev 1 2 3 4 5 6 7 8 ··· 26 next