0

I am currently working on an express app (API) which I now want to convert to use the serverless framework so I can deploy on AWS Lambda. I have done this before and did not have too many issues.

I have made the few code changes that need to be made and I can build and run the server using sls offline no problem, but as soon as I make a call to the API it crashes with a dependency error like the following:

Error: Dynamic require of "fs" is not supported

This error pointed to the dotenv package which sure enough had a "require('fs')" line in it. I commented out my import of the dotenv package just to see what would happen and called the API again. I got another error, but this time it was about the "path" package.

Error: Dynamic require of "path" is not supported

So this is obviously not an issue with just one package, it seems to be a compatibility issue between the serverless framework and my express app. The only real difference between this express app and the other one I made which works fine with serverless is that this new one is using typescript. Anyone with experience in express and serverless have any idea what could be causing the issue? Thanks in advance.

1 Answer 1

0

Maybe a clue in github.com/evanw/esbuild/issues/3324

From the Issue thread:

In summary, this runtime error is caused by bundling CJS libraries into ESM context (i.e. bundle express in format: 'esm'). esbuild uses closures to wrap these CJS liraries, and Node.js forbids dynamic (i.e. not at the top level) require on builtin modules.

I would still suggest you to exclude these dependencies from your bundle with --packages=external or --external:express since your runtime supports loading them from the file system, and it also bundles less code.

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe setting project to type="commonJS", instead of "module" in package.json. Even though this can be a nigthmare to adjust everything, depending on how your dependencies work.
So that's sort of what I did. I ended up just removing "type: module" from my package.json file. From my understanding this just no longer holds me to ESM standards? Kind of annoying because my project does comply with ESM standards but the packages I use dont, which seemingly wasn't a problem until I wanted to use serverless framework?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.