You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在现有NX v20.4.2 monorepo中创建AWS CDK应用及Lambda函数求助

解决NX v20.4.2 Monorepo中创建AWS CDK及Lambda应用的方案

一、创建AWS CDK基础设施应用

由于官方无维护中的NX CDK插件,直接手动在monorepo中集成CDK应用即可:

  • 在monorepo根目录下创建apps/cdk-infra文件夹,进入该目录执行:
    cdk init app --language typescript
    
  • 修改nx.json,将CDK应用加入项目配置,添加自定义执行目标:
    "cdk-infra": {
      "root": "apps/cdk-infra",
      "targets": {
        "synth": {
          "executor": "nx:run-commands",
          "options": {
            "command": "cdk synth",
            "cwd": "apps/cdk-infra"
          }
        },
        "deploy": {
          "executor": "nx:run-commands",
          "options": {
            "command": "cdk deploy",
            "cwd": "apps/cdk-infra"
          }
        },
        "destroy": {
          "executor": "nx:run-commands",
          "options": {
            "command": "cdk destroy",
            "cwd": "apps/cdk-infra"
          }
        }
      }
    }
    
  • 后续可通过NX命令执行CDK操作,比如nx run cdk-infra:synth、nx run cdk-infra:deploy。

可选:创建共享CDK库

如果需要复用基础设施代码,可在libs目录下创建CDK公共库:

  • 创建libs/cdk-common文件夹,执行npm init -y并安装CDK相关依赖。
  • 编写可复用的Constructs(比如通用VPC、S3桶定义),在CDK应用的package.json中添加本地依赖:
    "@your-monorepo/cdk-common": "file:../../libs/cdk-common"
    

二、创建Lambda函数应用及库

采用NX库模式管理Lambda函数,每个函数作为独立库维护:

1. 单个Lambda函数库初始化

  • 在libs/lambda-functions下创建子文件夹(比如get-users),进入该目录执行npm init -y,安装依赖:
    npm install typescript @types/aws-lambda aws-sdk --save-dev
    
  • 添加tsconfig.json配置编译规则:
    {
      "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "outDir": "../../../dist/libs/lambda-functions/get-users",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules"]
    }
    
  • 在src/index.ts中编写Lambda handler:
    import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
    
    export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
      return {
        statusCode: 200,
        body: JSON.stringify({ message: 'Successfully fetched users' })
      };
    };
    
  • 在nx.json中添加该库的build目标:
    "lambda-functions-get-users": {
      "root": "libs/lambda-functions/get-users",
      "targets": {
        "build": {
          "executor": "nx:run-commands",
          "options": {
            "command": "tsc",
            "cwd": "libs/lambda-functions/get-users"
          }
        }
      }
    }
    
  • 执行nx run lambda-functions-get-users:build编译代码,产物输出到dist目录。

2. 在CDK中关联Lambda函数

在CDK应用的栈定义中,引用编译后的Lambda代码并关联API Gateway:

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';

export class CdkInfraStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // 加载编译后的Lambda代码
    const getUsersLambda = new lambda.Function(this, 'GetUsersLambda', {
      runtime: lambda.Runtime.NODEJS_20_X,
      code: lambda.Code.fromAsset('../../dist/libs/lambda-functions/get-users'),
      handler: 'index.handler'
    });

    // 创建API Gateway并绑定Lambda
    const userApi = new apigateway.RestApi(this, 'UserManagementApi', {
      restApiName: 'User Management Service'
    });

    const usersResource = userApi.root.addResource('users');
    usersResource.addMethod('GET', new apigateway.LambdaIntegration(getUsersLambda));
  }
}

三、优化NX工作流(可选)

  • 在根目录package.json中添加快捷脚本:
    "scripts": {
      "cdk:synth": "nx run cdk-infra:synth",
      "cdk:deploy": "nx run cdk-infra:deploy",
      "lambda:build:all": "nx run-many --target=build --projects=lambda-functions-*"
    }
    
  • 配置NX缓存,在nx.json中为Lambda的build目标开启缓存,减少重复编译时间。

内容的提问来源于stack exchange,提问作者InternalVoice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:53:20