Serverles에 TypeScript 적용하기!

오병진·2021년 8월 28일
0
post-thumbnail

✨ 저의 Serverless 시리즈는 Typescript, yarn, AWS 기준으로 작성되므로 읽기 전 참고 바랍니다 ✨

저번에는 serverless aws 연동 설정까지 하였는데요
이번에는 Typescript를 적용해볼 예정입니다.

아 적용할 파일이 없다고요? 잠깐만요 😅

Template 생성

serverless 명령어는 sls로 줄일 수 있습니다.

D:\velog> sls create -help

이렇게 한다면 생성할 여러 템플릿들을 확인할 수 있습니다.

aws-nodejs-typescript

D:\velog>sls create -t aws-nodejs-typescript

이렇게 한다면 Typescript 기반 템플릿이 생성됩니다.

물론 이런다면 제목에 있는 Typescript 적용이 아닌, Typescript 템플릿 생성이니
node.js 기반으로 템플릿을 생성하겠습니다.
물론 제 취향이 아니기도 합니다

aws-nodejs

D:\velog> sls create -t aws-nodejs

이렇게 깔끔한거를 가져왔습니다.

성공적으로 생성하였으니, 한번 배포를 해서 봐야하는데
그 전 파일을 약간 수정해보도록 하겠습니다.

org: sunrabbit123
app: helloworld
service: velog
frameworkVersion: "2"

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221

functions:
  hello:
    handler: handler.hello

주석만 지웠는데 많이 줄어들었네요
여기서 이제 nodejs12.x를 LTS 버전인 nodejs14.x로 교체해주도록 합시다.
그리고 불러온 함수를 http를 이용하여 웹통신을 가능하도록 합시다.

org: sunrabbit123
app: helloworld
service: velog
frameworkVersion: "2"

provider:
  name: aws
  runtime: nodejs14.x
  lambdaHashingVersion: 20201221

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get

아 이제 깔끔하네요. 다음 명령어를 입력해줍시다

배포하기

sls deploy

이렇게 명령어를 입력하면 ...!

짜자잔

Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Installing dependencies for custom CloudFormation resources...
Serverless: Uploading CloudFormation file to S3...

.
.
.

............................
Serverless: Stack update finished...
Service Information
service: velog
stage: dev
region: us-east-1
stack: velog-dev
resources: 11
api keys:
  None
endpoints:
  GET - https://ojitgj9s10.execute-api.us-east-1.amazonaws.com/dev/hello
functions:
  hello: velog-dev-hello
layers:
  None

이렇게 배포가 완성되었네요!
물론 사람마다 나오는 endpoints는 다릅니다.

Typescript는 언제 적용해요?

지금 합니다.

우선 Typescript와 함께 플러그인도 같이 설치해줍니다.

D:\velog> yarn add -D typescript serverless-plugin-typescript

설치가 완성되었다면, handler.jshandler.ts로 확장자를 변경해주시고

handler.ts에서 module.exports.hello = ... 파트를
exports.hello = ...으로 변경해주시길 바랍니다 😋

tsconfig.json도 추가해야합니다!

{
 "compilerOptions": {
   "module": "commonjs", 
   "target": "es2017", 
   "outDir": "dist", 

   "noImplicitAny": true, 
   "strictPropertyInitialization": true, 
   "moduleResolution": "node", 
   "sourceMap": true,  
   "experimentalDecorators": true, 
   "emitDecoratorMetadata": true, 
   "strictNullChecks": true,
   "resolveJsonModule": true,
   "strict": true,
   "allowSyntheticDefaultImports": true,
   "typeRoots": ["@types", "node_modules/@types"]
 },
 "include": ["./src/**/*", "DTO/*", "util/*"],
 "exclude": ["src/**/*.spec.ts", "src/**/*.test.ts", "node_modules"]
}

저는 평소 이렇게 사용하네요 😉

그리고 serverless.yml 파일에 plugin 파트도 추가해주어야 합니다.

serverless.yml

plugin: 
	- serverless-plugin-typescript

마지막으로 배포!

sls deploy

이 명령어를 마지막으로 실행하게 된다면
Typescript가 컴파일되면서 배포가 되는 것을 볼 수 있습니다!

profile
지나가는 사람입니다. 마저 지나갈게요 :D

0개의 댓글