かなり時間使ってしまってワロタ(涙)
環境変数使いたいだけなのになんでこんなに時間をかけてしまったのか。。。とりあえず僕の時間が消えたぶんだけきれいにまとめた手順が下記
~/src/functions/hello/handler.ts
// 省略 const hello: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (event) => { console.log(process.env.HOGE); // 省略
デフォで用意されるファイルに環境変数読み取れるか用意。
.envファイルも用意する。
HOGE="HOGEHOGE"
実行してみる。
sls invoke local -f hello --path src/functions/hello/mock.json Running "serverless" from node_modules Error: Serverless plugin "serverless-dotenv-plugin" not found. Make sure it's installed and listed in the "plugins" section of your serverless config file. Run "serverless plugin install -n serverless-dotenv-plugin" to install it.
はいエラーがでました。どうやら追加でモジュールが必要なようです。
$ npm install -D serverless-dotenv-plugin
もっかい実行してみる。
$ sls invoke local -f hello --path src/functions/hello/mock.json Running "serverless" from node_modules DOTENV: Loading environment variables from .env: - HOGE HOGEHOGE { "statusCode": 200, "body": "{\"message\":\"Hello Frederic, welcome to the exciting Serverless world!\",\"event\":{\"headers\":{\"Content-Type\":\"application/json\"},\"body\":{\"name\":\"Frederic\"},\"rawBody\":\"{\\\"name\\\": \\\"Frederic\\\"}\"}}" }
えくせれんと!!!!
ちなみに僕は何にハマっていたのかというと
$ sls invoke local -f hello --path src/functions/hello/mock.json | jq .
この jq
で死んでました。 parse error: Invalid numeric literal at line 2, column 0
です。そりゃそうだよね。jsonじゃないんだから。。。( ˘ω˘)スヤァ