[NodeJS] Express + Typescript 구성하기
2021. 3. 3. 23:11ㆍWEB.DEV/NodeJS
반응형
이번 포스팅에서는 Typescript를 이용해서 Express를 구성하는 것을 해보겠습니다.
먼저 필요한 라이브러리를 npm을 이용해서 설치를 해주겠습니다.
$ npm i express
$ npm i -D nodemon typescript @types/express @types/node
그리고 명령어를 통해서 typescript 환경 파일을 생성해주도록하겠습니다.
$ npx tsc --init
위 명령어를 실행을 하면 tsconfig.json 파일이 생성이 됩니다.
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
...
}
...
}
안에 있는 세세한 옵션은 나중에 다른 포스팅에서 알아보도록 하겠습니다.
기본적인 옵션만 설정을 해주도록 하겠습니다.
{
"compilerOptions": {
"target": "ESNext",
"module": "commonjs",
"strict": true,
"moduleResolution": "node",
"outDir": "./build",
"sourceMap": false,
"esModuleInterop": true
},
"exclude": [
"node_modules"
],
"include": [
"./src/**/*.ts"
]
}
그리고 src/index.ts를 생성해주겠습니다.
import express from 'express';
class App {
app: express.Application;
constructor() {
this.app = express();
}
}
const app = new App().app;
app.get('/', (req: express.Request, res: express.Response) => {
res.send('Hello');
});
app.listen(8080, () => {
console.log('Started server with 8080');
});
위와 같이 작성을 하고 package.json에 script를 작성해주도록 하겠습니다.
{
...
"scripts": {
"start": "nodemon --exec ./node_modules/.bin/ts-node ./src/index.ts",
...
}
}
그리고 터미널에서 npm start를 입력하고 실행을 해줍니다.
...
> nodemon --exec ./node_modules/.bin/ts-node ./src/index.ts
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `./node_modules/.bin/ts-node ./src/index.ts`
Started server with 8080
위와 같이 실행이 된 후에 브라우저 혹은 Postman에 http://localhost:8080을 입력해서 실행을 하면 화면에 Hello라고 출력되는것을 볼수 있습니다.
많이 부족한 글 읽어 주셔서 감사합니다💛
728x90
반응형
'WEB.DEV > NodeJS' 카테고리의 다른 글
[NodeJS] Sequelize Timezone 설정 (0) | 2021.02.27 |
---|---|
[NodeJS] Node.js 설치 (0) | 2021.01.31 |