Lambda函数导入GraphQL模块失败,如何正确导入queries和mutations?
解决Lambda中ES模块导入找不到文件的问题
错误信息
Cannot find module '/var/task/graphql/queries' imported from /var/task/index.js Did you mean to import ../graphql/queries.js?
在Lambda函数的index.js中导入JS模块时出现上述错误,需要修正queries和mutations文件的导入方式,以下是相关文件代码:
现有文件代码
./index.js
import { default as fetch, Request } from "node-fetch"; import * as queries from "./graphql/queries"; import * as mutations from "./graphql/mutations"; async function myFunction(event) { // My function body } const resolvers = { Mutation: { adminProvision: (event) => { return myFunction(event); }, }, }; export const handler = async (event) => { //console.log(`EVENT: ${JSON.stringify(event)}`); const typeHandler = resolvers[event.typeName]; if (typeHandler) { const resolver = typeHandler[event.fieldName]; if (resolver) { var result = await resolver(event); console.log(result); return result; } } throw new Error("Resolver not found!"); };
./graphql/queries.js
export const ListSmartLocks = /* GraphQL */ ` query ListSmartLocks( $filter: ModelSmartLockFilterInput $limit: Int $nextToken: String ) { listSmartLocks(filter: $filter, limit: $limit, nextToken: $nextToken) { items { bikeparkID } nextToken } } `;
./graphql/mutation.js
export const createSmartLock = /* GraphQL */ ` mutation CreateSmartLock( $input: CreateSmartLockInput! $condition: ModelSmartLockConditionInput ) { createSmartLock(input: $input, condition: $condition) { id deviceId status bikeparkID vehicleType createdAt updatedAt } } `;
package.json
{ "name": "fnadminprovision", "type": "module", "version": "2.0.0", "description": "Lambda function generated by Amplify", "main": "index.js", "license": "Apache-2.0", "devDependencies": { "@types/aws-lambda": "^8.10.92" }, "dependencies": { "node-fetch": "^3.2.10" } }
修正方案
错误源于两个问题,对应修复如下:
文件名拼写不匹配:实际mutation文件名为
mutation.js,但导入时写的是mutations,需二选一修正:- 将
./graphql/mutation.js重命名为mutations.js; - 或直接修改导入语句中的文件名。
- 将
ES模块需明确文件后缀:Node.js的ES模块(
"type": "module"模式)要求导入本地文件必须添加.js后缀,Lambda环境严格执行此规则。
最终修正后的index.js导入语句示例(选其中一种即可):
方案1:保留原文件名,修正导入语句
import { default as fetch, Request } from "node-fetch"; import * as queries from "./graphql/queries.js"; import * as mutations from "./graphql/mutation.js";
方案2:重命名mutation文件后修正导入语句
先把./graphql/mutation.js改名为mutations.js,再修改导入:
import { default as fetch, Request } from "node-fetch"; import * as queries from "./graphql/queries.js"; import * as mutations from "./graphql/mutations.js";
另外需确认Lambda部署包中包含graphql目录及对应文件,避免打包时遗漏。
内容的提问来源于stack exchange,提问作者Dhanuka Perera
相关产品推荐
相关产品推荐

