NPM 으로 빌드 수행하기

build with npm

프론트엔드 개발 결과를 빌드할 때 gulp 와 npm 을 이용해 수행한다.

grunt, gulp 로 빌드할 때 불편한 점

  • grunt, gulp는 wrapper로 실제 툴을 npm과 혼용하는게 좋다
    • gulp-sass는 node-sass 의 wrapper이다.
  • 실제 사용하는 하부 모듈의 버전을 확인해야 한다.
  • 이런 빌드 툴은 새로운 태스크를 추가하려면 많은 의존성을 해결해야 한다.
    • npm으로 && 연결로 해결
  • Grunftfile.js 스크립트 대신 package.json 만 있으면 된다.
  • package.json에 명령을 추가할 수 있다.

npm 기본

–version or -v
–global as -g
–save as -S
–save-dev as -D

Outdated module

현재 package.json 에 설치된 버전과 명시된 버전 그리고 최신 버전과 차이를 알 수 있다.

1
2
3
4
npm outdated
Package Current Wanted Latest Location
body-parser 1.15.2 1.15.2 1.18.2 application-name
debug 0.7.4 0.7.4 3.1.0 application-name

최신 버전으로 설치를 하려면 package.json을 버전코드로 변경하고 업데이트를 진행한다.

모든 패키지를 업데이트할 수 있다.

1
2
3
npm update
+ mongoose@4.13.1
added 1 package, removed 4 packages and updated 2 packages in 32.975s

특정 모듈만 업데이트하려면 패키지를 명시하면 된다.

1
npm update debug

프로젝트 시작

프로젝트를 위해 폴더를 만들고 npm init 으로 초기화 한다. package.json 파일 생성 부터 묻는데, 응답이 귀잖고 즉시 초기화를 할 것이면 –yes 옵션을 사용한다.

1
2
$ mkdir hellonpm && cd hellonpm
$ npm init --yes

현재 폴더에 package.json 의 골격이 생성된다:

1
2
3
4
5
6
7
8
9
10
11
12
{
"name": "hellonpm",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

test 스크립트가 생성되어 있는데 실행해 본다:

1
2
3
4
$ npm test
> hellonpm@1.0.0 test /home/qkboo/Lectures/lecture_node/npm/hellonpm
> echo "Error: no test specified" && exit 1
...

node_modules 가 없다고 나오는데, 빌드를 위해 dev-dependencies 를 먼저 설치한다.

1
$ npm i -D jshint lite-server mocha concurrently node-sass uglify-js
  • -D : Package will appear in your devDependencies

패키지 디렉토리

package.json에 의존성 패키지가 명시되면 패키지 버전이 명시되는데 이 방법을 Semantic Versioning(Semver)라고 한다. started/semantic-versioning 참고한다.

npm install 명령으로 모듈이 설치되면 아래 같은 구조를 갖는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
├── photo-gallery/
└───── node_modules/
└───── modaal/
├───── demo/
│ ├───── css/
│ ├───── img/
│ └───── js/
├───── dist/
│ ├───── css/
│ └───── js/
└───── source/
├───── css/
└───── js/
└───── lib/

스크립트

package.json 의 scripts 에 태스크를 추가한다. 필요한 테스트 모듈은 …

lite-server

Node 서버 개발시 실시간 리로딩과 browser-sync (lite-server의 하부 모델)를 이용해 HTML, CSS, JS 를 테스트한다.

https://www.npmjs.com/package/lite-server

1
2
3
$ npm install lite-server --save-dev
# or yarn
$ yarn add lite-server --dev

package.json에 lite-server 스크립트를 추가하자

1
2
3
4
"scripts": {
...
"dev": "lite-server"
}

그리고 npm run dev 로 테스트를 시작한다.

browser-sync는 cross-browser checking도 지원한다. 자세한 것은 https://www.npmjs.com/package/light-server 참조

json-server

json-server는 Fake REST API로 여기를 참조: https://scotch.io/tutorials/json-server-as-a-fake-rest-api-in-frontend-development

설치

1
$ npm install -D json-server

스크립트는,

1
2
3
4
"scripts": {
...
"db": "json-server --watch db.json --port 3005"
}

테스트 실행은

1
2
$ npm run db

concurrently

여러 명령을 쉽게 실행하게 해준다.

https://www.npmjs.com/package/concurrently

테스트 스크립트에 다른 테스크를 동시에 실행하도록 해준다.

1
2
3
4
"scripts": {
...
"start": "concurrently -k \"npm run dev\" \"npm run db\""
}

concurrently 를 쓰기 싫다면 && 로 묶어서 실행해도 된다.

uglify

javascript 파일을 minify 해서 저장하도록 해준다.

1
2
3
4
"scripts": {
...
"uglify": "mkdir -p dist/js && uglifyjs src/js/*.js -m -o dist/js/app.js"
}

lint

1
2
3
4
"scripts": {
...
"lint": "jshint src/**.js"
}

sass

1
2
3
4
"scripts": {
...
"sass": "node-sass --include-path scss scss/main.scss assets/main.css"
}

mocha

mocha는 javascript 테스트 프레임워크로 npm test shorthand for npm run test.

1
2
3
4
"scripts": {
...
"test": "mocha test"
}

bash

쉘 스크립트로 만든 명령을 실행해 준다.

1
2
3
4
"scripts": {
...
"bash": "Location of the Bash/Shell script file"
}

rimraf

여러 계층의 파일/디렉토리를 지울 수 있는 모듈.

https://www.npmjs.com/package/rimraf

Boilerplate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"scripts": {

"start": "concurrently -k \"npm run dev\" \"npm run watch-css\"",

"dev": "lite-server",
"db": "json-server --watch db.json --port 3005",

"build-js": "mkdir -p dist/js && uglifyjs src/js/\*.js -m -o dist/js/app.js",

"lint": "lint jshint src/**/**.js",

"build-css": "node-sass --include-path scss scss/main.scss assets/main.css",
"watch-css": "nodemon -e scss -x \"npm run build-css\"",

"test": "mocha test",
"pretest": "npm run lint",
"posttest": "echo the test has been run!",

"bash": "Location of the bash/shell script file"

"clean": "rimraf ./dist/\*"
}

참조

Angular4 Tutorial for Beginner -- (1)

Angular 이용에 대한 튜토리얼은 Angular Tutorial for beginners to Professionals 를 요약하고 있다.

Angular App

여기서는 angular cli를 사용해서 angular project를 생성하고 다루는데, 링크 Angular Cli Usages 에서 새 프로젝트 실행에 대해 살펴볼 수 있다.

Anguar 의 개발 환경은 Create Angular2 를 참조한다.

자세히 보기

Angular 개발환경

Angular4 CLI

2017년 3월에 기존 2.x 버전에 호환하는 Angular 4.0.0이 출시되었다. [^1]


### CLI Quick Start

Angular CLI는 명령행 인터페이스로 프로젝트를 생성, 파일 추가 그리고 개발 태스크 - 테스트, 번들, 개발에 대한 기능을 제공하고 있다.
여기서 Angular CLI로 TypeScript 에서 앱을 개발하는 과정을 Style Guide가 권장하는데 맞게 진행해 보자

예제 다운로드

자세히 보기

Angular 개발환경

Angular

모바일, 데스크탑 웹 앱 구축을 지원하는 UI Framework 이다.

Version History

  • Angular 2: Initial Release 14.09.2016
  • Angular 4: Release on 23.03.2017
    • 2017년 3월에 기존 2.x 버전에 호환하는 Angular 4.0.0이 출시되었다. [^1]
  • Angular 5: Currently in beta 4 release 16.08.2017

Angular Changelog 에서 최신 정보를 얻을 수 있다.

자세히 보기

NodeJS: 콤포넌트 만들기

모듈 방식의 express 콤포넌트 만들기

코드 기반 모듈화 하기

Modular nodejs express 를 정리했다.

모듈식 구조는 콤포넌트 사이를 완전히 분리되지 않는 것으로 이해할 수 있다. 모듈화 구조는:

    1. 작은 콤포넌트로 나뉜다
    1. 콤포넌트 자체의 의존성 (테스트)를 갖고 타 콤포넌트에 영향을 최소화해 갱신할 수 있다.
    1. 프로젝트 전반 의존성은 개별 콤포넌트낄 공유 (혹은 덮어씀)할 수 있다
    1. 콤퍼넌트 우선-클래스(first-class)를 만들어야 한다. 즉 상대적인 경로롤 require를 구문을 사용 않는다.
    1. 다시 구성할 필요 없이앱 확장 (혹은 축소)에 전념한다

최소 모듈식 구조

아래 같은 최소 구조를 기반으로 하자:

1
2
3
4
bin/
lib/
package.json
index.js
  • bin: npm 스크립에 내장하지 않는 모든것 (ex. hooks, ci 등등 )
  • lib: 앱 콤포넌트

콤포넌트를 추가

콤포넌트는 단독으로 사용할 수 있는 프로젝트의 모든 측면이다. 예를 들어, 한 구성 요소는 cron 작업 스케줄링, 전자 메일 보내기, 내보내기 도구에 다른 구성 작업을 할 수 있다. 데이터 측면에서 모든 모델에 전용 인 하나의 구성 요소 또는 각 모델에 대해 별도의 구성 요소를 가질 수 있다

lib 디렉토리에 콤포넌트를 추가한다:

1
2
3
4
5
6
7
8
9
10
bin/
lib/
|- app/
| |- index.js
| └─ package.json
|- logger/
|- config/
└─ models/
package.json
index.js

콤포넌트의 진입점은 index.js 이고 package.json에 관련 의존성을 담는다.

package.json은 npm init -y 으로 초기화한다.

먼저 express 모듈을 설치한다. ( 여기선 npm version 5 이상 사용)

1
npm i express

logger 디렉토리에 로깅 모듈을 설치하고, config 디렉토리에 콤포넌트를 위한 구성 파일을 둔다.

콤포넌트 우선 클래스 만들기

콤포넌트는 앱에서 우선 클래스 이라서 프로젝트 어느 곳에서든 바로 접근할 수 있어야 해서, 아래 같이 상대적 경로를 사용하지 말아야 한다.

1
var logger = require('../../../logger')

콤포넌트에서 모든 모듈은 /lib 폴더를 참조하게 하므로 아래 같이 트릭을 사용해 node_modules 밑에 _ 로 링크를 만들어 주면
In UNIX, this is:

1
2
cd {project_root}/node_modules
ln -s ../lib _

In Windows, it is:

1
2
cd {project_root}/node_modules
mklink /D _ ..\lib

require('_/looger) 같이 참조할 수 있다.

1
var log = require('_/logger')

의존성 공유

이제 프로젝트 루트에서 콤포넌트를 설치하면 의존성을 사용할 수 있다.

설정

콤포넌트의 분리는 휼륭하다

preinstall

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var fs = require("fs");
var resolve = require("path").resolve;
var join = require("path").join;
var cp = require("child_process");

// get library path
var lib = resolve(__dirname, "../lib/");

fs.readdirSync(lib).forEach(function (mod) {
var modPath = join(lib, mod);

// ensure path has package.json
if (!fs.existsSync(join(modPath, "package.json"))) return;

// install folder
cp.spawn("npm", ["i"], { env: process.env, cwd: modPath, stdio: "inherit" });
});

참조

Nodejs middleware: Express

Express

Express는 NodeJS Webapplication framework이다.

Install express

Express는 크게 express 모듈과 CLI 모듈로 구성되어 있다.

  • express-generator: Express 프로젝트 및 템플릿 생성
  • exporess module: Node.js module

expres 명령을 이용해서 프로젝트를 생성하는 모듈로서 글로벌로 설치합니다.

1
2
$ mkdir myapp
$ cd myapp

npm의 package.json 를 초기화하자.

1
$ npm init

entry point: 에 app.js 혹은 index.js 시작점을 선언한다.

그리고 현재 프로젝트에 express 모듈을 설치하고 package.json에 의존성을 추가해 준다.

npm 5.0+ 이상은 npm install 시 모듈을 의존성 목록에 자동으로 추가한다.

1
$ npm install express

이전 버전은 아래같인 --save 를 명시해야 한다.

1
$ npm install express --save

Express Generator

express-generator 모듈은 손쉽게 프로젝트를 구성할 수 있게 해준다. CLI 명령으로 글로벌로 설치해 준다.

1
$ npm i -g express-generator

pug 뷰 엔진을 가진 myapp 이란 프로젝트를 생성하려면

1
$ express --view=pug myapp

프로젝트로 이동해 모듈을 설치하고 시작한다.

1
$ cd myapp && npm install

MacOS or Linux 에서 디버그 모드로 시작한다.

1
$ DEBUG=myapp:* npm start

Windows 에서

1
> set DEBUG=myapp:* & npm start

debug module

https://developer.ibm.com/node/2016/10/12/the-node-js-debug-module-advanced-usage/

https://expressjs.com/en/guide/writing-middleware.html

ExpressJS Middlewares

  • morgan:
    logger

  • body-parser:
    parse the body so you can access parameters in requests in req.body. e.g. req.body.name.

  • cookie-parser:
    parse the cookies so you can access parameters in cookies req.cookies. e.g. req.cookies.name.

  • serve-favicon:
    exactly that, serve favicon from route /favicon.ico. Should be call on the top before any other routing/middleware takes place to avoids unnecessary parsing.

주요 미들웨어

The following middlewares are not added by default, but it’s nice to know they exist at least:

  • compression:
    compress all request. e.g. app.use(compression())

  • session:
    create sessions. e.g. app.use(session({secret: 'Secr3t'}))

  • method-override:
    app.use(methodOverride('_method')) Override methods to the one specified on the _method param. e.g. GET /resource/1?_method=DELETE will become DELETE /resource/1.

  • response-time: app.use(responseTime()) adds X-Response-Time header to responses.

  • errorhandler:
    Aid development, by sending full error stack traces to the client when an error occurs. app.use(errorhandler()). It is good practice to surround it with an if statement to check process.env.NODE_ENV === ‘development’.

  • vhost:
    Allows you to use different stack of middlewares depending on the request hostname. e.g. app.use(vhost(‘.user.local’, userapp)) and app.use(vhost(‘assets-.example.com’, staticapp)) where userapp and staticapp are different express instances with different middlewares.

  • csurf:
    Adds a Cross-site request forgery (CSRF) protection by adding a token to responds either via session or cookie-parser middleware. app.use(csrf());

  • timeout:
    halt execution if it takes more that a given time. e.g. app.use(timeout(‘5s’));. However you need to check by yourself under every request with a middleware that checks if (!req.timedout) next();.

R 시작하기

R 소개

R은 벨 연구소 Becker 등에 의해 개발됐던 S language를 기반으로 통계 계산, 시각화를 위한 프로그래밍 언어를 포함한 개발환경이다. S language를 이용한 Insightful사의 S+는 S 언어를 이용한 상업용 소프트웨어이고, R은 공개소프트웨어 기반의 소프트웨어 이다.

  • 예) Excel, SPSS, SAS, HLM, MPlus 등 통계 프로그램

소개

http://revolution-computing.typepad.com/.a/6a010534b1db25970b01676908ecaf970b-pi

설치

R 의 GUI 도구로 R Studio를 사용할 수 있다.

  1. http://r-project.org 의 CRAN mirror에서 R을 다운받아 설치한다.
  2. RStudio 설치

R 시작하기

R 은 console을 통해 프로그래밍을 하거나 외부 에디터에서 작성한 소스를 컴파일해서 실행 할 수 있다.

macOS에서 R 시작시 다음 같은 경고를 보이면 macOS FAQ를 참고해 설정을 해주어야 한다.

[그림. ]

prompt

R을 실행하면 명령 입력 프롬프트 ‘>’을 볼 수 있다. 프롬프트에서 한 줄에 하나 혹은 한문장의 명령이 입력되고 실행된다.

1
2
3
4
5
6
7
print(“Hello World”)
Factorial(10) # 계산 기능
Rep(x=”hello”, times=5)
Rep(times=5) : Error…
Plot(10,10)
Plot(c(5,7), c(20, 30))
Plot(runif(100), runif(100)) # runif()는 랜덤 넘버 생성 함수

에서 명령을 입력하고 엔터로 실행이 되지만 괄호((),{},[])가 닫히지 않으면 ‘+’ 프로프트에서 계속 입력할 수 있다.

help() 사용

R에서 도움말을 통해 함수, 형식, 등의 정보를 얻을 수 있다.

1
> help(“함수명”)

패키지를 로드하지 않은 함수의 도움말 보기

1
> help.search(“함수명”)

내가 얻은 패키지는 어떤 것인가?

1
> help(package=”알고싶은 패키지명”)

주요 도움말 명령 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
> help()                      # 도움말 창
> help(ls) # 함수 ls()에 대한 도움말
> ?ls # 도움말 단축키 ?로 help(ls) 호출
> help(">") # R의 예약어, 연산자 등은 ""로
> help("for") # 묶는다.
> #특정 패키지에 대한 도움말 요청
> help(package="datasets")
> # 일반 검색어를 이용해 도움말 검색
> help.search("Latex")
> ??"Latex"
>
> # 사용 예제 검색
> example(mean)
mean> x <- c(0:10, 50)

mean> xm <- mean(x)

mean> c(xm, mean(x, trim = 0.10))
[1] 8.75 5.50
>

object

다음 같이 hello 변수와 값을 대입하고 hello 변수를 살펴본다.

1
2
3
4
5
6
7
8
9
10
11
12
> hello <- “안녕하세요"            #유니코드 문자열
> hello
[1] “안녕하세요"
> hello2 <- “R"
[] “R"
> Object1 <- 1 # 숫자
> Obect2 <- 2
> Object1 + Object2
[] 3

> Object1 <- TRUE # 논리형
> Object2 <- FALSE

Workspace

R에서 작업공간(workspace)에 사용자가 R을 이용하여 수행하는 자료와 분석 프로시져 등을 포함하게 된다.

  • setwd( … ): 명령으로 워크스페이스 변경
  • getwd(): 현재 워크스페이스 경로
  • list.files(PATH): 경로의 파일 목록을 반환

R의 종료를 위해서는 명령문 프롬프트에서 **q()**를 실행하던가 메뉴로부터 “종료”를 선택한다.
종료시 워크스페이스에 작업된 자료를 저장할 수 있다.

R 객체 이용하기

R의 최소 단위는 벡터

정수(1), 실수(5.8271), 문자(‘A’) 문자열(“hello”)는 스칼라이다.
벡터는 {1,2,3,4,5,6}과 같이 스칼라가 여러 개 모인 것이이다.

한 개의 스칼라 값을 가진 벡터를 선언한다.

1
> a <- 5

객체에 다른 객체 넣기

1
2
3
4
5
6
7
> object1 <- 1
> object2 <- 2
> object1
[1] 1
> object1 <- object2
> object1
[1] 2

객체에 다른 객체 넣기

1
2
3
4
5
6
> object1 <- 1
> object1 <- 2
> object1 <- object2
> object2 <- 100
> object1
[1] 2

함수 계산 결과를 객체에 넣기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> Excel1 <- read.csv(“example_student.csv”)

> Object1 <- sum(1,8,4,5,9)
Object1 : 27

> A <- c(1,3,5,6,9) # 벡터에 대해
A : 1,3,5,6,9

> A <- 1
Is.vector(a): True

A <- c(1,2,5)
Is.vector(a): True

> A <- c(“첫번째”, “두번째”, “세번째”)
A : ???

Package 관리

외부에서 제공하는 모듈을 Install, Update, Library 명령으로 관리할 수 있다. 패키지 설치는 Install 그리고 사용할 때는 Library 명령을 사용하고 패키지 갱신에 Update 명령을 사용한다.

패키지 관리

패키지 설치과 업데이트

1
2
3
4
> install.packages("패키지명")      # 패키지 설치
> library("패키지명") # 패키지 불러들이기 (사용)
> require("패키지명") #
> update.packges('패키지명') # 패키지 갱신

설치된 패키지 목록 보기

1
2
3
> Library()
> installed.packages()
> Install.packages()[, c(“Packages”, “version”, “License”)]

필수 패키지

1
2
3
4
5
6
7
8
9
10
11
Install.packages(“rgl”) # 3D 그래프 보여주는 패키지
Install.packages(“ggplot2”)
Install.packages(“ggthemes”)
Install.packages(“data.table”)
Install.packages(“devtools”)
Install.packages(“KoNLP”)
Install.packages(“dplyr”)
Install.packages(“plyr”)
Install.packages(“reshape2”)
Install.packages(“scales”)
Install.packages(“stringr”)

Github로 패키지 설치하기

개발자가 베타 버전을 github에 공개하는 경우
Knitr 패키지는 R에서 html, pdf, MS-Word 문서를 만들 수 있음고 https://github.com/yihui/knitr 에서 배포한다.

1
2
3
4
> Install.packages(“devtools”)
Library(“devtools”)

> install_github(“yihui/knitr”)

RStudio UTF8 지원


참조