commonJS 스펙의 require, export 대신 es6의 import, export 를 사용하도록 설정해보자.
첫번째 방법은 commonJS 스펙을 es6로 변환해주는 babel을 사용하는 방법이고 두번째 방법은 typescript 모듈을 사용하는 방법이다. 첫번째 방법이 좀 더 쉬울수 있겠지만 최근 흐름이 nodejs 뿐만 아니라 angular, react, vue 모두가 typescript를 사용하는게 트렌드이므로 두번째 방법을 사용해보도록 한다.
먼저 express 모듈의 타입스크립트 모듈을 설치하고 실행해보자.
1 |
C:\web\node\hero-server>npm install -D @types/express |
index.js에 es5 문법을 문법으로 모두 수정한다. import, const, arrow 펑션을 사용하여 모두 수정한다.
1 2 3 4 5 6 7 8 9 10 11 |
import express from 'express'; const app = express(); app.get('/api/hello', (req, res) => { res.send('hello world'); }); app.listen(8000, () => { console.log('server is listening 8000'); }); |
그렇지만 실행하면 아직 import 구문 다음을 인식하지 못한다.
이제 타입 스크립트 설정을 추가한다.
첫번째로 먼저 index.js => index.ts 로 확장명을 수정한다.
두번째로 typescrpit 컴파일러를 설치한다. 설치하면 tsc 명령어를 사용할 수가 있고 확장자가 .ts 인 화일을 컴파일해서 .js es5 화일을 생성할 수 있다. 설치후 버전을 확인해보자. tsc -v
1 |
C:\web\node\hero-server>npm install -D typescript |
세번째로 typescript 환경화일을 설정한다.
1 |
C:\web\node\hero-server>tsc --init |
위의 명령을 실행하면 tsconfig.json 화일이 생겼을 것이다. 일단 아래의 내용대로 세팅한다.
1 2 3 4 5 6 7 8 9 10 11 |
{ "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "target": "es6", "moduleResolution": "node", "sourceMap": true, "outDir": "dist" }, "lib": ["es2015"] } |
이제 실행을 해보자. 화일 확장자가 .ts 이므로 먼저 typescript를 컴파일해서 .js 를 생성한 다음에 실행해야 한다.
1 |
C:\web\node\hero-server>tsc && node dist/index |
실행이 되면 다시 브라우저로 테스트해보자.