与CDK一起部署时,Lambda无法从外部文件夹中找到模块 [英] Lambda can't find modules from outer folders when deployed with CDK

查看:50
本文介绍了与CDK一起部署时,Lambda无法从外部文件夹中找到模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用cdk将一些api部署到API网关.我的问题是包含lambda(index.ts)的文件无法导入该文件夹(名为 get-users 的文件夹)之外的任何文件或npm模块.

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).

我尝试将node_modules文件夹和其他文件(在 get-users 文件夹之外)复制到文件夹 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.

导入lodash时的示例错误如下,

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'",

我正在按如下方式导入 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

推荐答案

经过一些研究,我找到了答案.问题是CDK没有部署node_modules文件夹以及包含lambda源文件的文件夹之外的其他文件夹.

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.

创建lambda文件时,必须将根路径添加到"code"属性中,以便它将所有其中的文件夹/文件都部署到lambda中.

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
    });

这篇关于与CDK一起部署时,Lambda无法从外部文件夹中找到模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆