目標
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
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に以下を追加
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を以下を追記します。
custom:
  serverless-offline:
    useChildProcesses: true
これで後はJavaScriptで作るのと同じ感覚でTypeScriptによるLambda実装が可能になります!
