티스토리 뷰

Javascript/Angular

0. Angular 2 시작하기

CU SONAR 2016. 6. 5. 13:32

 요새 많은 프론트엔드 프레임워크들이 있습니다. 아무래도 요새 대세로 떠오르는건 react가 아닐까 합니다. facebook에서 후원하는 react는 component 베이스의 프레임워크로 최근 급격히 떠오르는것 같습니다. 그래서 Angular 2가 얼마나 뜰지는 아직 모르겠습니다. 구글에서 후원하고 TypeScript를 주 언어로 사용함으로써 보다 Java 개발자에게 친숙히 다가갈 수 있는것 같아서 저는 공부해보려고 합니다. Angular 1이 인기가 많았으니 2도 기대를 조금은 해봅니다. 얼마전까지는 beta 버전이었는데, 이번에 rc 버전이 나옴으로 인해 포스팅을 해보려 합니다. 설명을 장황하게 하는것은 저랑은 맞지 않아서 바로 시작해보겠습니다. 아래는 angular.io의 getting started를 그대로 사용합니다.


0. 준비물
     . Node.js(https://nodejs.org) 가 필요합니다.
     . TextEdit가 필요합니다. (sublime을 쓰시거나 webstorm을 추천합니다.)

1. 먼저 프로젝트를 생성하고, 설정 파일들을 만듭니다.
     . 프로젝트라고 해서 거창한건 아니고 그냥 폴더를 하나 만듭니다. angular2-quickstart 이름으로 합니다.
     . angular2-quickstart 폴더 밑에 packge.json 파일을 만듭니다. 이 파일은 node.js에서 npm이라는 node package management를 통해 dependency를 관리합니다. 
{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.14",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^1.0.4"
  }
}
 . angular2-quickstart 폴더 밑에 tsconfig.json 파일을 만듭니다. 이 파일은 TypeScript Compile 설정을 담당합니다.

 

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}
. angular2-quickstart 폴더 밑에 typings.json 파일을 만듭니다. 이 파일은 TypeScript의 dependency를 관리합니다.

 

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320"
  }
}
 . 역시 angular2-quickstart 폴더 밑에 systemjs.config.js 파일을 만듭니다. 이 파일은 SystemJS의 설정 파일로 각 JS 파일을 로드하는데 사용합니다.

 

/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

 
2. Dependency 파일 내려 받기
     . 해당 폴더의 cmd 창에서 npm install 을 실행해줍니다. npm을 이용해서 package.json에 선언된 dependency들을 내려받습니다. package.json을 자세히 보시면 script 안에 postinstall이라고 되어 있습니다. install을 한 후에 typings install을 수행합니다. 이를 통해 typings.json에 선언된 dependency들도 내려받게 됩니다.
     . 완료되면 프로젝트 폴더 밑에 node_modules 폴더와 typings 폴더가 생기고 그 아래 dependency들이 내려받아져 있습니다.

3. angular2-quickstart 폴더 밑에 app이라는 폴더를 만들고 그 아래 app.component.ts 파일을 만듭니다.
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: '

My First Angular 2 App

' }) export class AppComponent { }
      . import { Component } from '@angular/core'; 부분은 @angular/core에 있는 Component 모듈을 import 한다는 것입니다.
     . @Component는 Angular에서 제공하는 모듈로 앞으로 가장 많이 사용될 겁니다. selector는 HTML에서 해당 component가 들어갈 tag 이름으로 사용되고, template은 화면을 그리는데 사용됩니다.
     . export class AppComponent는 AppComponent 클래스를 선언하고, export 하여서 다른 곳에서 또 사용할 수 있다는 것을 뜻합니다.

4. app 폴더 밑에 main.ts 파일을 만듭니다.
import { bootstrap }    from '@angular/platform-browser-dynamic';

import { AppComponent } from './app.component';

bootstrap(AppComponent);
     . import { bootstrap }    from '@angular/platform-browser-dynamic'; Browser에서 template을 compile하기 위한 bootstrap 메소드를 제공합니다.
     . import { AppComponent } from './app.component'; 앞서 만든 app.component.ts 파일에서 export 했던 AppComponent를 import 합니다. from 절에 확장자 ts는 생략 가능합니다.

5. angular2-quickstart 폴더 밑에 index.html 파일을 만듭니다.
<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>
     . core-js : ES2015(ECMAScript6)로 확장하기 위한 라이브러리
     . zone.js : TC39(ECMAScript6)로 가기 전에 Zone에 관한 스펙을 구현해놓은 라이브러리
     . Reflect.js : Angular와 TypeScript Compiler 사이에 denpendency를 공유하기 위한 라이브러리
     . system.src.js : ES6 모듈 스펙에 호환되는 동적 모듈 로더
     . systemjs.config.js : 위에서 작성한 SystemJS Config 파일
     . System.import('app').catch(function(err){ console.error(err); }); SystemJS의 app을 로딩하고, 예외 발생시 console.error로 error 출력
     . <my-app>Loading...</my-app> : app.component.ts에서 선언한 component의 selector인 my-app을 이용한 태그, 해당 태그에 component가 들어감


6. Application 띄우기
     . cmd 창에서 npm start 를 수행하면, browser가 자동으로 뜨면서 Angular App이 실행되는 것을 확인할 수 있습니다.
     . npm start는 package.json에 선언되어 있다. "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" " : tsc는 TypeScript Compiler이다. tsc를 통해 compile을 먼저 수행하고, npm run tsc:w를 통해 watch mode의 TypeScript Compile을 함과 동시에 npm run lite를 통해 lite server를 띄운다. watch mode는 변경이 발생하면 자동으로 compile을 수행합니다.
     . 실행되는 순서를 적어보면 System.import('app')을 통해 systemjs.config.js에 있는 app을 로딩합니다. app의 메인 스크립트는 main.js이므로 main.ts에서 compile된 main.js 파일을 수행합니다. main에서는 AppComponent를 bootstrap하며, AppComponent가 수행됩니다. AppComponent는 별도의 로지은 없고 my-app에 template이 bootstrap에 의해 compile되어 화면에 뿌려지게 됩니다.

지금까지 간단하게 Angular 2 시작하기를 해봤습니다.

출처
Angular 2 공식홈페이지 - quickstart : https://angular.io/docs/ts/latest/quickstart.html


'Javascript > Angular' 카테고리의 다른 글

5-1. Routing 기초 - 1  (0) 2016.06.19
4. Service 만들기  (0) 2016.06.17
3. 파일 나누기, Component 나누기  (1) 2016.06.15
2. 기본적인 Directive 맛보기  (1) 2016.06.13
1. Data Binding 맛보기  (0) 2016.06.09
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함