zip-it-and-ship-it icon indicating copy to clipboard operation
zip-it-and-ship-it copied to clipboard

netlify dev supports import() but building on Netlify doesn't

Open mjswensen opened this issue 2 years ago • 5 comments

Describe the bug

In development, the following code works as expected:

exports.handler = async function (event) {
  const myValue = await import('my-package');
  // ...
};

But when deploying to production, my-package doesn't get bundled, resulting in 500 errors when the function tries to run (Cannot find package 'my-package' imported from /var/task/my-function.js)

To Reproduce

Steps to reproduce the behavior:

  1. Write a Netlify function with a dynamic import
  2. Run netlify dev
  3. See that the function runs properly
  4. Deploy to Netlify
  5. See that the deployed function doesn't run

Expected behavior

Either Netlify's production function bundling should support this case, or netlify dev should not. The behavior should match between the two.

mjswensen avatar Feb 15 '22 14:02 mjswensen

Confusingly, in development, when trying to require() an ES module, you get the following message:

Error: require() of ES Module <path to module> from <function path> not supported.
Instead change the require of index.js in <function path> to a dynamic import() which is available in all CommonJS modules.

Which leads users into this situation.

mjswensen avatar Feb 15 '22 14:02 mjswensen

I've found a workaround:

  1. Add node_bundler = "esbuild" to the [functions] section of netlify.toml.
  2. Convert functions from CommonJS to the ES Module syntax.
  3. Add the .netlify directory to .gitignore to exclude the build artifacts from source control.

Depending on which dependencies are getting bundled, CommonJS may no longer be an option for some users (like in my case). Perhaps esbuild should be the default for new projects?

mjswensen avatar Feb 16 '22 13:02 mjswensen

Hi @mjswensen! We're in the processing of rolling out a change that will address this issue, without you having to do any of the workarounds you described.

The change is going to be gradually rolled out over the next few days, but if you want I can enrol you in that group right now. You'd just need to send me your Netlify site ID (Go to Site settings > General > Site details > Site information, and copy the value for API ID). You can send it to [email protected] if you don't want to share it in public.

Thanks!

eduardoboucas avatar Feb 16 '22 13:02 eduardoboucas

Hi @eduardoboucas , sounds great, I'll send that over now. Thanks!

mjswensen avatar Feb 16 '22 13:02 mjswensen

Possibly related #1036

PH4NTOMiki avatar Feb 24 '22 11:02 PH4NTOMiki