I am deploying some apis to API Gateway using cdk. My problem is the file that contains the lambda(index.ts) can't import any files or npm modules outside that folder(folder named get-users
).
I tried copying node_modules folder and other files (which were outside the folder get-users
) to the folder get-users
and it worked perfectly.
Example error when importing lodash is as follows,
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'lodash'",
"stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'lodash'",
I am importing lodash
as follows,
import * as _ from "lodash";
I am importing shared files as follows,
import { validator } from "./shared/validators" // This one works
import { validator } from "../../shared/validators" // This one doesn't work
I found the answer after some research. Problem was CDK not deploying the node_modules folder and other folders which are outside the folder which contains the lambda source file.
When creating the lambda file root path has to be added to the 'code' attribute so that it will take all the folders/files inside it and deploy to the lambda.
const pathToRoot = //absolute path to the root folder
const pathToHandler = //path to handler from root folder
const lambdaFunction: Function = new Function(construct, name, {
functionName: name,
code: Code.asset(pathToRoot),
handler: `${pathToHandler}/index.handler`,
runtime: Runtime.NODEJS_10_X
});
UPDATE
And after some more research found out the best way to handle this is with Lambda Layers. I have added my node modules folder as a layer.