Search code examples
node.jsazureazure-functions

'Cannot use import statement outside a module' in Azure function


I have an azure function running locally in dev mode. I am trying to import 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,
  };
};

I get the following error:

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

What I've tried:

  1. I added type: 'module' to package.json.
  2. I named the file index.cjs

But it still throws same error.

For reference, here is my package.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": {}
}

And here is the file structure:

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

Solution

  • I found the solution

    1. renamed the file to index.mjs
    2. removed module.exports and used export default instead:
    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,
      };
    }