typescript로 nodeJS 시작하기
typescript를 이용하여 NodeJS를 실행시키는 방법입니다.
global npm
$ npm install -g typescript
$ npm install -g nodemon
nodemon은 있으면 편합니다.
npm
$ npm init -y
$ npm install -D express ts-node @types/node @types/express
/* Express용 Typescript 정의입니다. */
$ npm install @types/express-serve-static-core
tsconfig.json 작성하기
$ npx tsc --init
위 명령어를 실행하면 아래 json 파일이 생성됩니다.
tsconfig.json
{
"compilerOptions": {
"target": "ES6", // 컴파일 할 버전
"jsx": "react", // 생성할 JSX 코드 지정
"module": "commonjs", // 어떤 모듈 방식으로 컴파일할지 설정
"rootDir": ".", // 루트 디렉토리
"moduleResolution": "node", // 모듈 해석 방법
"outDir": "./dist", // 컴파일 후 JS파일이 생성되는 디렉토리
"esModuleInterop": true, // 가져오기를 용이하게 하기 위해 추가 Javascript를 내보냅니다.
"forceConsistentCasingInFileNames": true, // 케이스가 올바른지 확인합니다.
"strict": true, // strict Option 활성화
"skipLibCheck": true // 모든 .d.ts파일들 건너뛰기
}
}
tsconfig.json 파일을 열어보면 주석처리된 내용들이 나옵니다. 그 중에서 위 내용들을 풀어줍니다.
package.json 내용 추가하기
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node dist/app.js",
"build": "tsc -p .",
"dev": "nodemon --watch \"src/**/*.ts\" --exec \"ts-node\" src/app.ts"
},
- start: node dist/app.js로 컴파일된 JS파일로 시작합니다.
- build: "tsc -p ." 타입스크립트를 자바스크립트로 빌드를 시작합니다.
app.ts 작성하기
app.ts
import express, { Request, Response, NextFunction } from "express";
const app = express();
app.get("/", (req: Request, res: Response, next: NextFunction) => {
res.send("성공 !");
});
const PORT = 4000;
app.listen(PORT, () => {
const message = `
[ TEST PROJECT ]
Running PORT: localhost:${PORT}
`;
console.log(message);
});
기본 틀입니다.
Server 실행하기
$ npm run dev
// yarn을 사용했을 경우
$ yarn dev
'NodeJS > NodeJS 시작하기' 카테고리의 다른 글
[ NodeJS ] window yarn 설치하기 (0) | 2022.08.02 |
---|---|
[ NodeJS ] window nvm 관리하기 (0) | 2022.08.02 |
[ NodeJS ] nvm 기본 노드 버전 변경하기 (0) | 2022.07.20 |
[ NodeJS ] app.js 시작하기 (0) | 2022.01.23 |