无服务器 - Lambda 层 "找不到模块'request'"

10

当我使用以下方式部署我的无服务器 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 脚本的样子。
4个回答

5
我在使用显式的layers键来定义lambda层时遇到了与您类似的错误。
我的错误是(为了进行网络搜索): Runtime.ImportModuleError: Error: Cannot find module <package name> 我觉得这只是暂时的解决方案,因为我想要像您一样明确地定义我的层,但是它没有起作用,所以似乎是个错误。
我在Serverless中创建了一个错误报告来针对此问题。如果其他人也遇到了同样的问题,他们可以在那里跟踪它。
解决方法:
我根据AWS的这些文档在Serverless论坛上关注了this帖子。
我将位于文件夹nodejs下的node_modules压缩,解压后看起来像这样:nodejs/node_modules/<各种包>
然后,我使用了packageartifact键,而不是显式定义层,如下所示:
layers:
  test:
    package:
      artifact: test.zip

在函数层中,它被称为这样:
functions:
  function1:
    handler: index.handler
    layers:
      - { Ref: TestLambdaLayer }

"TestLambdaLayer是一个约定,其名称应为<您的层名称>LambdaLayer,如此处所述。"

没有起作用。仍然出现错误:错误:找不到模块'./json.js' - Binh Ho

2
如果有人遇到类似的问题Runtime.ImportModuleError,可以说这个问题的另一个原因可能是serverless.yml文件中的包排除语句。
请注意,如果您有这个语句:
package:
  exclude:
    - './**'
    - '!node_modules/**'
    - '!dist/**'
    - '.git/**'

一旦您使用无服务器框架部署Lambda函数,就会在运行时产生完全相同的错误。请确保删除可能在依赖项之间创建冲突的内容。


2

在部署之前,请确保在您的层内运行npm install,例如:

cd ~/repos/repo-name/layers/utilityLayer/nodejs && npm install

否则,您的层将在没有node_modules文件夹的情况下部署。您可以从Lambda UI下载您的层的.zip文件以确认该层的内容。

0

我正在使用 serverless-plugin-typescript 进行 TypeScript 编程,也遇到了同样的错误。

当我从

const myModule = require('./src/myModule');

import myModule from './src/myModule';

错误已经消失了。看起来在我使用require时,serverless没有将文件包含在zip文件中。

附注:删除serverless-plugin-typescript并切换回javascript也解决了这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接