Difficulties understanding nodejs modules in AWS Lambda [duplicate]
I'm trying to create an AWS Lambda function running on nodejs. It simply calls a REST API and should return whatever the API call returns. I'm trying to make use of the node-fetch module. At first I used this:
const fetch = require('node-fetch');
Which resulted in the following error: Must use import to load ES Module
So I changed it to use import like this:
import fetch from 'node-fetch';
Which in turn resulted in the following error: SyntaxError: Cannot use import statement outside a module
So next I added "type": "module" to the package.json in the main filetree.
(Main filetree)
{
"dependencies": {
"node-fetch": "^3.1.0"
},
"name": "aws_lambda",
"version": "1.0.0",
"type": "module",
"main": "index.js"
}
So now I get an error like this: "errorMessage": "exports is not defined in ES module scope\nThis file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
Changing the file extension to .cjs brings me back to 'Cannot use import statement outside a module'
How is this so freakin difficult? What am I supposed to do? Thanks
If you want to use require you need to use node-fetch v2 by running npm like this:
npm install node-fetch@2