zip-it-and-ship-it
zip-it-and-ship-it copied to clipboard
netlify dev supports import() but building on Netlify doesn't
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:
- Write a Netlify function with a dynamic import
- Run
netlify dev
- See that the function runs properly
- Deploy to Netlify
- 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.
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.
I've found a workaround:
- Add
node_bundler = "esbuild"
to the[functions]
section ofnetlify.toml
. - Convert functions from CommonJS to the ES Module syntax.
- 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?
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!
Hi @eduardoboucas , sounds great, I'll send that over now. Thanks!
Possibly related #1036