この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
AWS CDK の NodejsFunction では、デフォルトではバンドルに esbuild が使用されます。
しかし、esbuild はデコレータに対応していないなど互換性の問題により、Webpack を使用したいケースもあると思います。
実は AWS CDK では Lambda 関数のバンドル処理を自由に定義できるようになっています。
準備
Webpack をインストールしておきます
npm install -D webpack-cli ts-loader
構成ファイルも作っておきます。
webpack.config.js
const { webpack } = require("webpack");
const path = require("path");
module.exports = {
mode: "development",
target: "node",
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
libraryTarget: "commonjs2",
},
module: {
rules: [
{
test: /\.ts$/,
use: "ts-loader",
},
],
},
resolve: {
extensions: [".ts", ".js"],
},
entry: "./src/index.ts",
};
bundling オプションを設定する
Code.fromAsset
の bundling
オプション でバンドル処理を定義することができます。
const exampleFunction = new Function(this, "example-function", {
code: Code.fromAsset(process.cwd(), {
assetHashType: AssetHashType.OUTPUT,
bundling: {
image: Runtime.NODEJS_14_X.bundlingImage,
command: [
"bash",
"-c",
`npx webpack -o ${AssetStaging.BUNDLING_OUTPUT_DIR}`,
],
},
}),
handler: "index.handler",
runtime: Runtime.NODEJS_14_X
});
image
にはバンドルに使用されるコンテナイメージを指定します。関数ランタイムの bundlingImage
を指定するのが簡単です。
command
にはコンテナ内で実行されるコマンドを定義します。今回は Webpack ですので、webpack の起動コマンドを指定しています。
webpack
の -o
オプションに AssetStaging.BUNDLING_OUTPUT_DIR
を渡すことで、出力先ディレクトリを CDK の出力先に変更しています。