Error [ERR_REQUIRE_ESM]: require() of ES Module

Receiving the error:

Error [ERR_REQUIRE_ESM]: require() of ES Module when trying to compile a typescript service implementing the netlify api module. Version 11.0.1.

My TS config looks like this:

{
  "compilerOptions": {
    "target": "ES2021",
    "module": "commonjs",
    "lib": [
      "esnext"
    ],
    "moduleResolution": "node",
    "strict": true,
    "rootDir": "src",
    "outDir": "dist",
    "sourceMap": true,
    "esModuleInterop": true,
    "types": ["jest"]
  }
}

The full error is as follows:

/my-app/dist/graphql/resolvers/Mutations/site.js:7
const netlify_1 = __importDefault(require("netlify"));
                                  ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /my-app/node_modules/netlify/src/index.js from /my-app/dist/graphql/resolvers/Mutations/site.js not supported.
Instead change the require of index.js in /my-app/dist/graphql/resolvers/Mutations/site.js to a dynamic import() which is available in all CommonJS modules.

Hey there, @shallow_alchemy :wave:

Apologies for the delay here! Can you please share a link to your site as well as your most recent deploy log?

Additionally, have you seen this thread? It looks like the very last exchange in the post was from a Forums member with a similar error (Error [ERR_REQUIRE_ESM]: require() of ES Module):

I filed an issue on the GitHub repo for netlify js client and they said it’s expected. The client api only exports esm not common js. The proposed solution is to use “module: ‘nodenext’”, but doing that breaks a bunch of other imports and it also isn’t a stable release yet. Alternatively it was suggested to use a dynamic import, but I got the same error when doing that.

So I gave up and wrote my own.

Not sure why the js client wouldn’t be compatible in ts environments, but it appears to not be.

thanks for letting us know - glad you found a solution even if its not ideal. :pray:

Add the below code to your index.js File and in package.json add “main”: “index.js”, “type”: “module”,

import { NetlifyAPI } from “netlify”;

import Downloader from “nodejs-file-downloader”;

const client = new NetlifyAPI("");

(async () => {
const files = await client.listSiteFiles({
site_id: “”,
});

files.forEach(async (file) => {
const downloader = new Downloader({
url: “” + file.path,
directory:
“./Download” + file.path.substring(0, file.path.lastIndexOf("/") + 1),
});

try {
  await downloader.download();
  console.log(file.path + " done");
} catch (error) {
  console.log(file.path + " failed", error);
}

});
})();