Must use import to load ES Module error on production, but not local

Hi. On local, I am importing d3 via import * as d3 from ‘d3’ and all works well on local.

However, when I deploy (to https://coruscating-ganache-5df72b.netlify.app/), I get the following error message:

Must use import to load ES Module: /var/task/node_modules/d3/src/index.js
require() of ES modules is not supported.
require() of /var/task/node_modules/d3/src/index.js from /var/task/.netlify/server/entries/pages/index.svelte.js is an ES module file as it is a .js file whose nearest parent package.json contains “type”: “module” which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove “type”: “module” from /var/task/node_modules/d3/package.json.
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/task/node_modules/d3/src/index.js
require() of ES modules is not supported.
require() of /var/task/node_modules/d3/src/index.js from /var/task/.netlify/server/entries/pages/index.svelte.js is an ES module file as it is a .js file whose nearest parent package.json contains “type”: “module” which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove “type”: “module” from /var/task/node_modules/d3/package.json.

I believe the suggestion is to either modify d3 files in the node_module directory (which feels like the wrong solution as they are third-party files from a popular library and shouldn’t even be under version control) or make sure I am using ESM import syntax, rather than CJS require syntax (but I am already using ESM import syntax: i.e., import * as d3 from ‘d3’ ).

I’ll continue researching. When I search this general error, I mostly see references to using the node-fetch library on netlify. But, again, the solution is to either use ESM import instead of CJS require or downgrade to an older version of node-fetch that supports CSJ require.

Any ideas why this might work on my local but fails on Netlify remote? Thank you so much for any advice or insight if you’ve experienced this before.

Hey @dslanger

If you wish to use import in function, you need to have the following in the netlify.toml of the project

[functions]
  node_bundler = "esbuild"

Otherwise it will use zizi See documentation here and here

2 Likes

@coelmay , thank you, that resolved the issue!

2 Likes