0

I am adding a layer to my AWS Lambda function, when I run a test I get this error returned. I am using nodejs 18, and the layer is only installing pg.

The code:

import {
  Pool,
  Client
} from 'pg'
const pool = new Pool({
  user: 'postgres',
  host: 'tom-practice-database-2.csl0vrlucjal.eu-west-2.rds.amazonaws.com',
  database: 'tom-practice-database-2',
  password: 'root4322',
  port: 5432,
})
exports.handler = async(event) => {
  pool.connect()
  await pool.query('SELECT * FROM employees')
    .then((res) => console.log(res))
    .catch(console.log)
  return {
    statusCode: 200,
    body: JSON.stringify('Hello from lambda')
  }
};

Error:

{
  "errorType": "ReferenceError",
  "errorMessage": "require is not defined in ES module scope, you can use import instead",
  "trace": [
    "ReferenceError: require is not defined in ES module scope, you can use import instead",
    "    at file:///var/task/index.mjs:2:28",
    "    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"
  ]
}
Papgooner
  • 13
  • 5
  • Related: [type field in package.json](https://stackoverflow.com/questions/61401475/why-is-type-module-in-package-json-file). Typically you need ["type": "commonjs"](https://nodejs.org/api/packages.html#type) and the source would be named index.js (to use require), not index,mjs (to use import). – jarmod Jun 21 '23 at 13:58

0 Answers0