NodeJS Azure函数中的“无法在模块外部使用import语句”

6tr1vspr  于 2023-01-25  发布在  Node.js
关注(0)|答案(1)|浏览(122)

我有一个azure函数在本地以开发模式运行。我正在尝试导入node-fetch

import { fetch } from "node-fetch";

module.exports = async function (context, req) {
  context.log("JavaScript HTTP trigger function processed a request.");

  const res = await fetch("https://www.swyx.io/api/rss.xml");

  const responseMessage = "res:" + res.ok;

  context.res = {
    // status: 200, /* Defaults to 200 */
    body: responseMessage,
  };
};

出现以下错误:

Worker was unable to load function HttpTrigger1: 'Cannot use import statement outside a module'

我尝试过的:
1.我在package.json中添加了type: 'module'
1.我将文件命名为index.cjs
但它仍然抛出相同的错误。
作为参考,这里是我的包. json:

{
  "name": "cors-test",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "scripts": {
    "start": "func start",
    "test": "echo \"No tests yet...\""
  },
  "dependencies": {
    "node-fetch": "^3.3.0"
  },
  "devDependencies": {}
}

下面是文件结构:

.
├── host.json
├── HttpTrigger1
│   ├── function.json
│   ├── index.cjs
│   └── sample.dat
├── local.settings.json
├── package.json
├── package-lock.json
└── yarn.lock
szqfcxe2

szqfcxe21#

我找到解决办法了
1.将文件重命名为index.mjs
1.删除了module.exports并使用export default

import fetch from "node-fetch";

export default async function (context, req) {
  context.log("JavaScript HTTP trigger function processed a request.");

  const res = await fetch("https://www.swyx.io/api/rss.xml");

  const responseMessage = "res:" + res.ok;

  context.res = {
    // status: 200, /* Defaults to 200 */
    body: responseMessage,
  };
}

相关问题