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

CDK部署TypeScript Lambda报错:无法找到模块'index'

问题:AWS Lambda部署成功但测试时提示找不到模块'index'

测试Lambda时出现以下错误:

{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module 'index'\nRequire stack:\n- /var/runtime/index.mjs",
  "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'index'",
    "Require stack:",
    "- /var/runtime/index.mjs",
    "    at _loadUserApp (file:///var/runtime/index.mjs:996:17)",
    "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1031:21)",
    "    at async start (file:///var/runtime/index.mjs:1194:23)",
    "    at async file:///var/runtime/index.mjs:1200:1"
  ]
}

Lambda在CDK中的定义:

const postImages = new lambda.Function(scope, utils.prefixed('post_images'), {
    runtime: lambda.Runtime.NODEJS_18_X,
    handler: 'index.lambdaHandler',
    code: lambda.Code.fromAsset('./sd_service/post_images')
})

./sd_service/post_images目录包含以下文件:

index.ts

import { Context, APIGatewayEvent, APIGatewayProxyResult } from 'aws-lambda';

export const lambdaHandler = async (event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> => {
    console.log(`Event: ${JSON.stringify(event, null, 2)}`);
    console.log(`Context: ${JSON.stringify(context, null, 2)}`);
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: 'hello world',
        }),
    };
};

tsconfig.json

{
    "$schema": "https://json.schemastore.org/tsconfig",
    "display": "Node 18",
    "compilerOptions": {
        "lib": ["es2022"],
        "module": "commonjs",
        "target": "es2022",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "moduleResolution": "node"
    },
    "exclude": ["node_modules", "**/*.test.ts"]
}

package.json

{
  "name": "post_images",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/aws-lambda": "^8.10.111",
    "@types/node": "^18.14.6",
    "aws-sdk": "^2.1330.0",
    "typescript": "^4.9.5"
  },
  "dependencies": {
    "aws-lambda": "^1.0.7"
  }
}
原因与解决方案

原因

Lambda运行环境(Node.js)只能执行JavaScript文件,你当前直接将TypeScript源码目录作为部署资产,CDK的lambda.Code.fromAsset不会自动编译TypeScript,导致部署到Lambda的是.ts文件而非.js文件,运行时找不到index.js模块。

解决方案

方案1:手动编译TypeScript后部署

  1. 修改tsconfig.json,添加输出目录配置,将编译后的JS文件输出到dist目录:
    {
        "compilerOptions": {
            // 保留原有配置
            "outDir": "./dist"
        }
    }
    
  2. 修改package.json,添加编译脚本:
    {
        "scripts": {
            "build": "tsc",
            "test": "echo \"Error: no test specified\" && exit 1"
        }
    }
    
  3. 执行编译:在./sd_service/post_images目录下运行命令:
    npm run build
    
  4. 修改CDK代码,将资产路径指向编译后的dist目录:
    const postImages = new lambda.Function(scope, utils.prefixed('post_images'), {
        runtime: lambda.Runtime.NODEJS_18_X,
        handler: 'index.lambdaHandler',
        code: lambda.Code.fromAsset('./sd_service/post_images/dist')
    })
    
  5. 重新部署CDK栈即可。

方案2:使用CDK的NodejsFunction自动处理编译

使用AWS CDK提供的lambda.NodejsFunction构造,它会自动完成TypeScript编译、依赖打包等操作,无需手动处理:

  1. 修改CDK代码:
    import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
    
    const postImages = new NodejsFunction(scope, utils.prefixed('post_images'), {
        runtime: lambda.Runtime.NODEJS_18_X,
        handler: 'lambdaHandler',
        entry: './sd_service/post_images/index.ts'
    })
    
  2. 直接重新部署CDK栈即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:32:13