14
14

More than 3 years have passed since last update.

lambdaにTypeScriptをデプロイする手順(zip)

Posted at

はじめに

TypeScriptをlambdaにデプロイする方はServerless FreamworkやSAMなどがあります。
しかし、installや設定などの事前準備が必要で、手軽ではありません。
そこで今回は簡単にデプロイして動作確認するために、zip化してデプロイする手順を記載していきます。

事前準備

typescriptのインストール

npm install -g typescript

AWS CLI

AWS CLI のインストール

lambda関数の作成

あらかじめ、AWSコンソールやcliでlambda関数を作成しておきます。

スクリーンショット 2019-11-06 23.51.11.png

プロジェクトの作成

下記の構成でファイルを作成していきます。

├─ src          
│   └─ index.ts  # TypeScriptソース
├─ package.json   # パッケージ設定ファイル
├─ tsconfig.json  # TypeScript設定ファイル
├─ deploy.sh      # lambdaにデプロイするためのスクリプト

src/index.ts

TypeScriptソースです。
今回はnode_modulesを含めているため、動作確認としてmomentを読み込んでいます。

src/index.ts

import moment from 'moment';

export async function handler(event: any): Promise<any> {
  return {
    statusCode: 200,
    body: {
      message: 'typescript test',
      timestamp: moment().format()
    }
  }
}

package.json

パッケージ設定ファイル

package.json

{
  "name": "typescript-lambda",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@types/moment": "^2.13.0",
    "moment": "^2.24.0"
  }
}

tsconfig.json

TypeScript設定ファイル

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  },
  "include": [
    "./src/**/*"
  ]
}

deploy.sh

ビルド、zip化、アップロードをするスクリプトです。

deploy.sh

#!/bin/sh
# distフォルダ
rm -rf ./dist
# TypeScriptビルド
tsc -p tsconfig.json
# package.jsonをdistにコピー
cp -f ./package.json ./yarn.lock ./dist
cd dist
# packageのインストール
yarn install --production
# uploadするためにzip化
zip -r ./lambda.zip ./

# zipデータをlambdaにアップロード
aws lambda update-function-code \
    --function-name typescript-lambda \
    --zip-file fileb://lambda.zip

実行


$ yarn install
$ ./deploy.sh

確認

AWSコンソールでテスト実行して、想定通りのレスポンスが返ってくることを確認

スクリーンショット 2019-11-09 10.56.46.png

参考URL

2019/6 AWS LambdaのTypeScript化

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14