Error [ERR_REQUIRE_ASYNC_MODULE]: require() cannot be used on an ESM graph with top-level await.
Use import() instead. To see where the top-level await comes from, use --experimental-print-required-tla.
This error is due to a Node.js updating the name of the error with a special "backport" of the require(esm)
feature.
- In Node <= 20.18.0 the error is
ERR_REQUIRE_ESM
. - In Node >= 20.19.0 the error is
ERR_REQUIRE_ASYNC_MODULE
.
I noticed this error when trying to run Serverless 3.40.0 after upgrading Node from 20.18.0 to 20.19.3. Serverless has a method to handl require
/import
differenced based on catching ERR_REQUIRE_ESM
error.
The handling is in the file serverless/lib/utils/require-with-import-fallback.js
https://github.com/serverless/serverless/blob/v3.40.0/lib/utils/require-with-import-fallback.js#L9
The workaround is to either downgrade to 20.18.0 or use Node arguments or environment variables.
Example:
node --no-experimental-require-module foo.js
Or environment vars
NODE_OPTIONS="--no-experimental-require-module" sls deloy foo