LoginSignup
3
2

More than 3 years have passed since last update.

ServerlessFramework+TypeScript+serverless-offlineでLambda関数を作る

Last updated at Posted at 2020-06-13

目標

ServerlessFrameworkのローカル開発で重宝するserverless-offline。
非常に便利なのでこれをTypeScriptでも使用したかったのですが、色々躓いてました。
今回どうにか動いたので備忘録的にその流れを記録しておきます。

ServerlessFrameworkにてテンプレートをインストール

npx sls create -t aws-nodejs-typescript -n lambda-typescript
cd lambda-typescript
yarn

eslintをインストールしますが、自分はグローバルインストールしたeslint-cliから実行します。
(そうした方が楽なので)

# まだインストールしていなければ
npm i -g eslint

eslint --init
? How would you like to use ESLint? To check syntax and find problems
? What type of modules does your project use? JavaScript modules (import/export)
? Which framework does your project use? None of these
? Does your project use TypeScript? Yes
? Where does your code run? Browser, Node
? What format do you want your config file to be in? JavaScript
? Would you like to install them now with npm? Yes

Prettierもインストール(お好みで)

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

以下.eslintrc.js

.eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2020: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
    'prettier/@typescript-eslint',
  ],
  globals: {
    Atomics: 'readonly',
    SharedArrayBuffer: 'readonly',
  },
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint'],
  rules: {
    // お好みで
    'prettier/prettier': [
      2,
      {
        singleQuote: true,
        semi: false,
        arrowParens: 'always',
        parser: 'typescript',
      },
    ],

    '@typescript-eslint/explicit-module-boundary-types': 'off',
  },
}

プラグインをインストール

serverless.ymlに以下を追加

serverless.yml
plugins:
  - serverless-webpack
  - serverless-dynamodb-local # DynamoDBを使う場合
  - serverless-offline

コマンドを実行

# serverless-offlineをインストール
yarn add -D serverless-offline

# (オプション)DynamoDBを使う場合は下記も
yarn add -D serverless-dynamodb-local
npx sls dynamodb install
npx sls dynamodb start

※プラグインを読み込む順番には意味があるので、以上のような順番は必須です。

スタート

npx sls offline start

これで動くと思いますが、ただしバグのためホットリロードがうまく機能しない可能性があります。
その場合はServerless Framwork +serverless-offline + Webpackでホットリロードが効かないバグを御覧ください。

一部だけ抜き出すとserverless.ymlを以下を追記します。

serverless.yml
custom:
  serverless-offline:
    useChildProcesses: true

これで後はJavaScriptで作るのと同じ感覚でTypeScriptによるLambda実装が可能になります!

3
2
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
3
2