首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Google Cloud Functions |提供的模块无法加载-错误[ERR_REQUIRE_ESM]:必须使用import加载ES模块: /workspace/index.js

Google Cloud Functions |提供的模块无法加载-错误[ERR_REQUIRE_ESM]:必须使用import加载ES模块: /workspace/index.js
EN

Stack Overflow用户
提问于 2021-06-22 20:45:39
回答 2查看 378关注 0票数 1

我希望使用Google Cloud Functions与概念API进行交互。我首先从their API doc中提取第一个示例,并将其放入CF中(见下文)。然而,我得到了以下错误日志:

Detailed stack trace: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /workspace/index.js

当我尝试在本地运行概念应用程序接口时,我收到了类似的消息,但通过将import { Client } from "@notionhq/client"更改为import notion from "@notionhq/client"; const Client = notion可以绕过这一问题。由于某些原因,这个修复在云函数中不起作用。

我还读到了其他SO回答,我需要将package.json中的类型更改为模块,但我已经这样做了,问题仍然存在。

index.js

代码语言:javascript
复制
import { Client } from "@notionhq/client"

exports.notionBot = (req, res) => {
  let message = req.query.message || req.body.message || 'Testing the notion API with Cloud Functions!';

  const notion = new Client({ auth: process.env.NOTION_KEY })

  const databaseId = process.env.NOTION_DATABASE_ID

  async function addItem(text) {
    try {
      await notion.request({
        path: "pages",
        method: "POST",
        body: {
          parent: { database_id: databaseId },
          properties: {
            title: { 
              title:[
                {
                  "text": {
                    "content": text
                  }
                }
              ]
            }
          }
        },
      })
      console.log("Success! Entry added.")
    } catch (error) {
      console.error(error.body)
    }
  }

  addItem("Yurts in Big Sur, California")

  res.status(200).send(message);
};

package.json

代码语言:javascript
复制
{
  "name": "notion-example",
  "type": "module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "@notionhq/client": "^0.1.9",
    "esm": "^3.2.25"
  }
}
EN

回答 2

Stack Overflow用户

发布于 2021-06-23 14:10:35

Google Cloud Functions还不支持ES模块。请参阅https://cloud.google.com/functions/docs/migrating/nodejs-runtimes#nodejs-14-changes下的“备注”。

您需要将您的函数重写为CommonJS (即使用require而不是import),或者使用像Babel这样的工具将您的代码转换为CommonJS。

(请注意,对ES模块的支持即将到来:https://github.com/GoogleCloudPlatform/functions-framework-nodejs/issues/233)

票数 2
EN

Stack Overflow用户

发布于 2021-07-15 10:52:13

从Firebase Tools v9.15.0开始,您现在可以在云函数中使用ES模块。

https://github.com/firebase/firebase-tools/releases/tag/v9.15.0

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68083791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档