当我使用以下方法部署无服务器api时:
serverless deploy
创建了lambda层,但是当我运行该函数时,会出现以下错误:
"Cannot find module 'request'"
但是,如果我通过控制台手动上载.zip文件(与我部署时上载的文件完全相同),它就可以正常工作。
有人知道为什么会这样吗?
environment:
SLS_DEBUG: "*"
provider:
name: aws
runtime: nodejs8.10
stage: ${opt:api-type, 'uat'}-${opt:api, 'payment'}
region: ca-central-1
timeout: 30
memorySize: 128
role: ${file(config/prod.env.json):ROLE}
vpc:
securityGroupIds:
- ${file(config/prod.env.json):SECURITY_GROUP}
subnetIds:
- ${file(config/prod.env.json):SUBNET}
apiGateway:
apiKeySourceType: HEADER
apiKeys:
- ${file(config/${opt:api-type, 'uat'}.env.json):${opt:api, "payment"}-APIKEY}
functions:
- '${file(src/handlers/${opt:api, "payment"}.serverless.yml)}'
package:
# individually: true
exclude:
- node_modules/**
- nodejs/**
plugins:
- serverless-offline
- serverless-plugin-warmup
- serverless-content-encoding
custom:
contentEncoding:
minimumCompressionSize: 0 # Minimum body size required for compression in bytes
layers:
nodejs:
package:
artifact: nodejs.zip
compatibleRuntimes:
- nodejs8.10
allowedAccounts:
- "*"
这就是我的无服务器yaml脚本的样子。
答案 0 :(得分:2)
确保在部署之前在层中运行npm install
,即:
cd ~/repos/repo-name/layers/utilityLayer/nodejs && npm install
否则,将在没有node_modules
文件夹的情况下部署您的层。您可以从Lambda UI下载图层的.zip来确认该图层的内容。
答案 1 :(得分:2)
如果有人遇到类似问题Runtime.ImportModuleError
,可以公平地说,此问题的另一个原因可能是serverless.yml
文件中的package exclude语句。
请注意,如果您有以下声明:
package:
exclude:
- './**'
- '!node_modules/**'
- '!dist/**'
- '.git/**'
一旦部署了lambda函数(使用无服务器框架),它将在运行时导致完全相同的错误。只是,请确保删除那些可能在您的依赖项之间造成冲突的因素
答案 2 :(得分:0)
您需要手动将其安装在serverless.yml文件夹中
.clear()
答案 3 :(得分:0)
在使用用于定义Lambda层的显式layers
键时,我遇到了与您类似的错误。
(为了进行网络搜索)我的错误是:
Runtime.ImportModuleError: Error: Cannot find module <package name>
我觉得这是一个临时解决方案b / c,我想像您在做的那样明确定义我的图层,但是它没有用,所以好像是个错误。
我为此问题在Serverless中创建了bug report。如果其他人遇到同样的问题,他们可以在那里追踪。
解决方案
我在基于AWS的this的无服务器论坛中关注了these docs这个帖子。
我将node_modules
压缩到文件夹nodejs
下,因此在解压缩nodejs/node_modules/<various packages>
时看起来像这样。
然后,我使用package
和artifact
键,而不是使用层的显式定义,如下所示:
layers:
test:
package:
artifact: test.zip
在功能层中这样称呼:
functions:
function1:
handler: index.handler
layers:
- { Ref: TestLambdaLayer }
TestLambdaLayer
是here所记录的<your name of layer>LambdaLayer
的约定
答案 4 :(得分:0)
我在serverless-plugin-typescript
上使用打字稿,并且也遇到了相同的错误。
当我从
切换时const myModule = require('./src/myModule');
到
import myModule from './src/myModule';
错误消失了。当我使用serverless
时,require
似乎没有将文件包含在zip文件中。
PS:删除serverless-plugin-typescript
并切换回javascript
也解决了这个问题。