I have a simple lambda function written in typescript. It works locally using sls invoke local -f main
however when deployed and i run it in aws console via a test function i get the following error:
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'handler'\nRequire stack:\n- /var/runtime/index.mjs",
"trace": [
"Runtime.ImportModuleError: Error: Cannot find module 'handler'",
"Require stack:",
"- /var/runtime/index.mjs",
" at _loadUserApp (file:///var/runtime/index.mjs:951:17)",
" at async Object.UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:976:21)",
" at async start (file:///var/runtime/index.mjs:1137:23)",
" at async file:///var/runtime/index.mjs:1143:1"
]
}
serverless.ts
import type { AWS } from "@serverless/typescript";
const serverlessConfiguration: AWS = {
service: "email-service",
frameworkVersion: "3",
plugins: [],
useDotenv: true,
provider: {
name: "aws",
region: "us-east-2",
runtime: "nodejs16.x",
apiGateway: {
minimumCompressionSize: 1024,
shouldStartNameWithService: true,
},
environment: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1",
NODE_OPTIONS: "--enable-source-maps --stack-trace-limit=1000",
FROM_EMAIL: process.env.FROM_EMAIL,
SENDGRID_API_KEY: process.env.SENDGRID_API_KEY,
},
},
// import the function via paths
functions: {
main: {
handler: "handler.main",
timeout: 60,
},
},
package: { individually: true },
};
module.exports = serverlessConfiguration;
The file handler.ts
exists and there is an exported function called main
.
hanlder.ts
import SendEmail from "./src/sendemail";
import { ValidateInput } from "./src/validator";
export const main = async (event, _context) => {
try {
const errors = await ValidateInput(event);
if (errors.length > 0) {
return { statusCode: 400, body: { errors: errors } };
}
const result = await SendEmail(event);
return { statusCode: 200, body: { data: result } };
} catch (err) {
return { statusCode: 500, body: { errors: [err.stack] } };
}
};
Is it possible for aws lambda to run .ts files OR must they be converted to js using something like serverless-esbuild?
CodePudding user response:
Node.js doesn't run TypeScript code natively doc. You have to transpile it to JS code.