dherault / serverless-offline

Emulate AWS λ and API Gateway locally when developing your Serverless project
MIT License
5.16k stars 794 forks source link

Add preLoadModules option to import modules on main thread #1777

Open astron8t-voyagerx opened 2 months ago

astron8t-voyagerx commented 2 months ago

Description

This commit adds 'preLoadModules' option that allows the main thread to load specified modules.

Motivation and Context

Some Node.js modules, such as 'sharp', are not safe to use with worker threads. Importing them in a worker thread can lead to crashes. There are several reported issues regarding this, for example, see: https://github.com/dherault/serverless-offline/issues/1603

And 'sharp' recommends importing the module on the main thread to prevent such problems. https://github.com/lovell/sharp/issues/2263#issuecomment-645523303

While the 'useInProcess' option allows us to avoid using threading, it also disables hot reloading, which significantly reduces convenience. This commit implements the 'preLoadModules' option (e.g., preLoadModules: "sharp, canvas") to import these modules before creating worker threads.

How Has This Been Tested?

I've tested in my own project using serverless offline, and also conducted tests with Mocha in this repository.