LoginSignup
3
1

CDKでNode.jsのLambda関数を作るときにjs|ts以外のファイルをバンドルする

Last updated at Posted at 2023-08-03

TL;DR

bundling.commandHooks.beforeBundling
を定義して、その中でcpでコピーしてあげればOK!

new NodejsFunction(this, 'lambda', {
  runtime: Runtime.NODEJS_18_X,
  architecture: Architecture.ARM_64,
  functionName: 'my-nodejs-function',
  handler: 'handler',
  entry: 'lambda/index.ts',
  bundling: {
    commandHooks: {
      beforeBundling(inputDir: string, outputDir: string): string[] {
        return [`cp ${inputDir}/lambda/hoge.txt ${outputDir}`];
      },
      afterBundling(): string[] {
        return [];
      },
      beforeInstall(): string[] {
        return [];
      },
    },
  },
});

解説

CDKでNode.jsのLambda関数を作る場合、NodejsFunctionクラスを使うことで、TypeScriptのビルドなど含めて、いい感じに行うことができます。

一方、js|tsに関係ないファイルは無視してバンドルしてくれるので、プログラム内でreadFileSync('hoge.txt')とかやってる場合、そのテキストファイルがLambdaにアップロードされず、ちゃんと動いてくれません。

そういうとき、最初に書いた方法を使えば、任意のファイルをアップロードしてあげることができます。UNIXコマンドを何でも実行できるオプションなので、ファイルコピー以外にもかなり応用が効きそうですね!

ちなみにafterBundlingbeforeInstallは今回は使わないんですが、commandHooksの中には必ず3点セットで関数を定義しないとエラーになるので、[]だけを返す関数を書いておく必要があります。

参考サイト

ではまた!

3
1
2

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
1