亚马逊Lambda节点图书馆
AWS CDK v1在2023-06-01上达到了支持结束. 此软件包不再更新,用户应该迁移到 AWS CDK v2.
关于如何移徙的更多信息,请参见: 移动到 AWS CDK v2 指南。 。 。 .
这个库为Node.js Lambda函数提供构造.
节点.js 函数
这个 NodejsFunction 构造创建自动转接和捆绑的 Lambda 函数
类型脚本或 Javascript 代码。 因此,Lambda小包只包含:
操作该函数需要代码和依赖.
用这个 兴建 在引擎盖下.
参考项目架构
这个 NodejsFunction 允许您在单个中定义您的 CDK 和运行时的依赖性
package.json 和将您的运行时间代码与您的基础设施代码拼接:
.
├── lib
│ ├── my-construct.api.ts # Lambda handler for API
│ ├── my-construct.auth.ts # Lambda handler for Auth
│ └── my-construct.ts # CDK construct with two Lambda functions
├── package-lock.json # single lock file
├── package.json # CDK and runtime dependencies defined in a single package.json
└── tsconfig.json
默认情况下,构造将使用定义文件的名称和构造的
查找条目文件的ID 。 单位 my-construct.ts 上面有:
// automatic entry look up
const apiHandler = new lambda.NodejsFunction(this, 'api');
const authHandler = new lambda.NodejsFunction(this, 'auth');
或者,可以指定条目文件和处理器:
new lambda.NodejsFunction(this, 'MyFunction', {
entry: '/path/to/my/file.ts', // accepts .js, .jsx, .ts, .tsx and .mjs files
handler: 'myExportedFunc', // defaults to 'handler'
});
对于单体,参考架构变为:
.
├── packages
│ ├── cool-package
│ │ ├── lib
│ │ │ ├── cool-construct.api.ts
│ │ │ ├── cool-construct.auth.ts
│ │ │ └── cool-construct.ts
│ │ ├── package.json # CDK and runtime dependencies for cool-package
│ │ └── tsconfig.json
│ └── super-package
│ ├── lib
│ │ ├── super-construct.handler.ts
│ │ └── super-construct.ts
│ ├── package.json # CDK and runtime dependencies for super-package
│ └── tsconfig.json
├── package-lock.json # single lock file
├── package.json # root dependencies
└── tsconfig.json
自定义基本的 Lambda 函数
所有属性 lambda.Function 可用于自定义基础 lambda.Function。 。 。 .
另见 AWS Lambda 构建库。 。 。 .
这个 NodejsFunction 自动构造 重复使用现有连接
当与 JavaScript 的 AWS SDK 合作时. 设定 awsSdkConnectionReuse 向 false 来禁用它.
锁定文件
这个 NodejsFunction 需要依赖性锁定文件( q)yarn.lock, (中文(简体) ), pnpm-lock.yaml 或者说
package-lock.json) (中文(简体) ). 当捆绑在一个 Docker 容器中时,包含此锁文件的路径是
用作源(/asset-input用于装入容器的体积.
默认情况下, 构造将尝试自动确定您的工程锁定文件 .
或者,您可以指定 depsLockFilePath 手动道具。 在这
您需要确保此路径包含 entry 和任何模块/相互依存关系
用于您的函数。 否则,捆绑将失败.
本地捆绑
若为 esbuild 它将用来将您的代码捆绑在您的环境中 。 否则,
捆绑将发生在一个 Lambda 兼容多克容器
与多克平台基于Lambda函数的目标架构.
对于macOS,建议的方法是安装 esbuild 因为Docker的体积表现很差.
esbuild 可用下列方式安装:
$ npm install --save-dev esbuild@0
或
$ yarn add --dev esbuild@0
如果你使用单重排布局 esbuild 依赖需要安装在“ 根” 中 package.json 文档,
不是在工作空间。 从描述的参考架构 上文,则 esbuild
dev 依赖性需要在 ./package.json没有 packages/cool-package/package.json 或者说
packages/super-package/package.json。 。 。 .
强迫捆绑在一个多克容器中,即使 esbuild 在你的环境中,
设定 bundling.forceDockerBundling 改为 true。如果函数依赖于节点,则此功能是有用的
应安装的模块nodeModules 道具,见 下级在兰巴达
兼容环境。 使用本土依赖的模块通常属于这种情况.
使用模块
外部人员
默认情况下,除了 aws-sdk。可以通过指定
bundling.externalModules数字 :
new lambda.NodejsFunction(this, 'my-handler', {
bundling: {
externalModules: [
'aws-sdk', // Use the 'aws-sdk' available in the Lambda runtime
'cool-module', // 'cool-module' is already available in a Layer
],
},
});
安装模块
默认情况下,您 Lambda 代码中引用的所有节点模块将被捆绑 esbuild。 。 。 .
使用 nodeModules 道具下方 bundling 指定一个不应是
已捆绑,但已纳入 node_modules lambda 软件包的文件夹。 这个有用
与本地依赖者合作或何时 esbuild 无法捆绑模块 .
new lambda.NodejsFunction(this, 'my-handler', {
bundling: {
nodeModules: ['native-module', 'other-module'],
},
});
所列模块 nodeModules 必须在 package.json其依赖性或
已安装。 同一版本将用于安装。 锁定文件( R)yarn.lock, (中文(简体) ),
pnpm-lock.yaml 或者说 package-lock.json)将与右安装器一起使用(yarn, (中文(简体) ),
pnpm 或者说 npm) (中文(简体) ).
合作时 nodeModules 使用本地依赖,您可能想要强制捆绑在一个
即使挂载容器 esbuild 可以在您的环境中使用。 可以通过设置
bundling.forceDockerBundling 改为 true。 。 。 .
配置 esbuild
这个 NodejsFunction 构造曝光 新建选项
通过属性 bundling数字 :
new lambda.NodejsFunction(this, 'my-handler', {
bundling: {
minify: true, // minify code, defaults to false
sourceMap: true, // include source map, defaults to false
sourceMapMode: lambda.SourceMapMode.INLINE, // defaults to SourceMapMode.DEFAULT
sourcesContent: false, // do not include original source into source map, defaults to true
target: 'es2020', // target environment for the generated JavaScript code
loader: { // Use the 'dataurl' loader for '.png' files
'.png': 'dataurl',
},
define: { // Replace strings during build time
'process.env.API_KEY': JSON.stringify('xxx-xxxx-xxx'),
'process.env.PRODUCTION': JSON.stringify(true),
'process.env.NUMBER': JSON.stringify(123),
},
logLevel: lambda.LogLevel.SILENT, // defaults to LogLevel.WARNING
keepNames: true, // defaults to false
tsconfig: 'custom-tsconfig.json', // use custom-tsconfig.json instead of default,
metafile: true, // include meta file, defaults to false
banner: '/* comments */', // requires esbuild >= 0.9.0, defaults to none
footer: '/* comments */', // requires esbuild >= 0.9.0, defaults to none
charset: lambda.Charset.UTF8, // do not escape non-ASCII characters, defaults to Charset.ASCII
format: lambda.OutputFormat.ESM, // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js 14.x)
mainFields: ['module', 'main'], // prefer ECMAScript versions of dependencies
inject: ['./my-shim.js', './other-shim.js'], // allows to automatically replace a global variable with an import from another file
esbuildArgs: { // Pass additional arguments to esbuild
"--log-limit": "0",
"--splitting": true,
},
},
});
命令钩子
通过指定 commandHooks 道具 :
// This example only available in TypeScript
// Run additional props via `commandHooks`
new lambda.NodejsFunction(this, 'my-handler-with-commands', {
bundling: {
commandHooks: {
beforeBundling(inputDir: string, outputDir: string): string[] {
return [
`echo hello > ${inputDir}/a.txt`,
`cp ${inputDir}/a.txt ${outputDir}`,
];
},
afterBundling(inputDir: string, outputDir: string): string[] {
return [`cp ${inputDir}/b.txt ${outputDir}/txt`];
},
beforeInstall() {
return [];
},
// ...
},
// ...
},
});
现提供以下钩子:
beforeBundling: 在所有捆绑命令之前运行beforeInstall: 在节点模块安装前运行afterBundling: 在所有捆绑命令后运行
他们都收到包含锁文件的目录(inputDir)和
捆绑资产将输出的目录( e)outputDir) (中文(简体) ). 他们必须回来
要运行的一系列命令。 命令与 &&。 。 。 .
命令将在捆绑发生的环境中运行: 用于多克捆绑的容器或用于本地捆绑的主机OS上.
附带海训方案的预汇编
在某些情况下, esbuild 可能尚不支持打字语言的一些较新的特性,例如,
emitDecoratorMetadata。 。 。 .
在这种情况下,可以使用 tsc 通过设置 preCompilation 旗帜.
new lambda.NodejsFunction(this, 'my-handler', {
bundling: {
preCompilation: true,
},
});
注:A tsconfig.json 文件 需要时间
自定义多克捆绑
使用 bundling.environment 以定义环境变量,当 esbuild 运行 :
new lambda.NodejsFunction(this, 'my-handler', {
bundling: {
environment: {
NODE_ENV: 'production',
},
},
});
使用 bundling.buildArgs 在构建 Docker 捆绑图像时通过构建参数 :
new lambda.NodejsFunction(this, 'my-handler', {
bundling: {
buildArgs: {
HTTPS_PROXY: 'https://127.0.0.1:3001',
},
}
});
使用 bundling.dockerImage 要使用自定义的多克捆绑图像 :
new lambda.NodejsFunction(this, 'my-handler', {
bundling: {
dockerImage: DockerImage.fromBuild('/path/to/Dockerfile'),
},
});
这个图像应该有 esbuild 已安装 全球。如果计划使用 nodeModules 这个
也应该有 npm, (中文(简体) ), yarn 或者说 pnpm 取决于您使用的锁文件.
使用 默认图像提供方式 @aws-cdk/aws-lambda-nodejs
作为灵感的来源.
资产散列h
默认情况下,资产散列将根据捆绑的产出计算(AssetHashType.OUTPUT) (中文(简体) ).
使用 assetHash 通过自定义散列的道具 :
new lambda.NodejsFunction(this, 'my-handler', {
bundling: {
assetHash: 'my-custom-hash',
},
});
如果您选择自定义散列, 您需要确保每次资产更新它 否则,一些部署不会被取消.