Dynamic imports in Node causing errors when using ES modules.

4 replies
Last updated: Nov 8, 2021
Dynamic imports are supposed to work in Node right?
prebuild.js:

(async function () {
  const createClient = require("next-sanity");
  const { config } = await import("../config.js");
})();
throws an error:

Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

...

export const config = {
^^^^^^

SyntaxError: Unexpected token 'export'
The Node docs clearly state that "Dynamic import() is supported in both CommonJS and ES modules. In CommonJS modules it can be used to load ES modules." -
https://nodejs.org/api/esm.html#import-expressions
Nov 7, 2021, 4:28 AM
I think because dynamic import(…) can be used for both CJS & ES module, Node needs a hint on which module type to use. That’s why it suggested changing the file extention from js -> mjs. Node treats all
.js
as CJS &
.mjs
as ES module.
If you add a
type: "module"
to package.json, it’ll do the reverse where all
js
files are treated as ES Module & you’d have to mark CJS files as
.cjs
Nov 7, 2021, 10:44 PM
Hey User, I had tried changing the prebuild.js script and all its dependencies to ES modules, both by adding a package.json with the
"type": "module"
line to the parent dir as well as by changing the extensions to
.mjs
. This caused a heap of webpack errors when Next tried to build or HMR the site, since it also uses these files, and I guess it didn't like that. For now I just copied and pasted the Sanity config object into the prebuild script. It works and now I'm able to fetch global site data, store it in a JSON file, and use it in the Layout component.
Nov 8, 2021, 12:49 AM
Ah things get complicated when bundlers are involved… I think a possible solution is to create a directory for shared files in esm format (but keep the
.js
ext), then add a empty package.json with
type: module
in it. Hopefully both Node & webpack can understand that.
I’m glad that typescript sorted these stuff out for me so I don’t have to deal with them, as long as all my files are
.ts
Nov 8, 2021, 10:14 AM
Yep, that’s what I did. Node was ok with it but webpack wasn’t. I should get more into typescript. 😀
Nov 8, 2021, 1:16 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?