Imoprting ESM-only dependencies/Running as ESM Module

Hi everybody.
I’m using an esm-only library and I cannot for the life of me figure out how to properly load it in my project or how to turn it into an ESM module itself. When I just try to import it in my function, it says:

SyntaxError: Cannot use import statement outside a module",

I can’t rename my function to function.mjs, because then it’ll complain that:

“Error: Cannot find module ‘./index.js’”,

If I try to set the “type” to “package” in package.json it says:

ReferenceError: require is not defined in ES module scope, you can use import instead

probably because generated “s_function.js” works with require.

I tried to use plugins like serverless-esbuild with “platform: neutral”, but whatever I try I run into one of the above errors.

Could somebody please point me into the right direction? AWS Lambda does support it, if I just call my function function.mjs and zip it, I can run it in Lambda, so it must be something about the serverless framework.

Thanks.

This seems to do the trick:

async function loadStuff () {
    const node_module = await import('$node_module');
    const cljsFile = await node_module.$some_function('$args)
}
exports.handler=loadStuff;

I solved this issue by making a separate handler module that imports the index.mjs file and calls the handler in it, like lambda would. This handler must be a CJS module (i.e: not .mjs or “type”:“module” in package), but you can still use imports in it to import your ESM module.
Use a named import, since all handlers are named.
This works perfectly fine for me and can be copied over between all functions without editing, assuming all functions have the same naming for the handlers and modules

exports.handler = async (event, context) => {
    const { lambdaHandler } = await import('./index.mjs');
    return lambdaHandler(event, context);
}