在使用无服务器的 AWS Lambda 中使用
nodejs18.x
运行时我遇到了 ES6 和 Common JS 的问题。
当不在
type: module
中设置 package.json
时,Lambda 会抱怨在 import
之外使用
module.export
语句
SyntaxError: Cannot use import statement outside a module
但是当我将
type
中的 module
设置为 package.json
时,它抱怨我正在使用 required
。我没有这样做,但是由 Serverless 创建的 s_tag_file.js
文件确实包含 required
{
"errorType": "ReferenceError",
"errorMessage": "require is not defined in ES module scope, you can use import instead\nThis file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
"stack": [
"ReferenceError: require is not defined in ES module scope, you can use import instead",
"This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
" at file:///var/task/s_tag_file.js:2:21",
" at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"
]
}
我做错了什么?或者我可以做些什么不同的事情?
这是我的完整代码:
package.json
:
{
"dependencies": {
"@aws-sdk/client-s3": "^3.391.0",
"aws-sdk": "^2.1437.0"
},
"type": "module"
}
serverless.yaml
:
org: OUR_ORG
app: OUR_APP
service: OUR_SERVICE
frameworkVersion: '3'
provider:
name: aws
runtime: nodejs18.x
lambdaHashingVersion: 20201221
region: us-east-1 # Required for using CloudFront, region does not matter though (it runs at the CF edge location anyways)
iamRoleStatements:
cloudFront:
cachePolicies:
cdnCachePolicy:
MinTTL: 0
MaxTTL: 5184001
DefaultTTL: 5184000
ParametersInCacheKeyAndForwardedToOrigin:
CookiesConfig:
CookieBehavior:
none
EnableAcceptEncodingBrotli: true
EnableAcceptEncodingGzip: true
HeadersConfig:
HeaderBehavior: none
QueryStringsConfig:
QueryStringBehavior: none
custom:
origin: 'ORIGIN_URL'
path: 'build'
functions:
tag-file:
handler: index.tagFile
events:
- cloudFront:
eventType: viewer-response
origin:
DomainName: ${self:custom.origin}
OriginPath: /${self:custom.path}
CustomOriginConfig:
OriginProtocolPolicy: match-viewer
cachePolicy:
name: cdnCachePolicy
index.js
:
import { S3Client, PutObjectTaggingCommand } from "@aws-sdk/client-s3";
export async function tagFile(event, context, callback) {
const response = event.Records[0].cf.response;
const client = new S3Client({ region: "eu-west-1"});
const input = {
Bucket: "BUCKET_NAME",
Key: event.Records[0].cf.request.uri,
Tagging: {
TagSet: [
{
Key: "requestTime",
Value: Date.now().toString(),
},
],
},
};
const command = new PutObjectTaggingCommand(input);
const S3response = await client.send(command);
console.log(S3response);
callback(null, response);
};
由于您在
org
文件中使用 serverless.yml
键(第 1 行),因此您正在使用无服务器仪表板插件。
此插件不支持 ES6(这是拥有
import
语句所必需的)。请参阅 https://github.com/serverless/dashboard-plugin/issues/564 了解更多详细信息。
根据网站说明,无服务器仪表板正在被贬值,取而代之的是支持 ES6 的无服务器控制台。
因此,如果您需要支持 ESM: