Error using pure ESM library from common-js (nextjs) project: "Must use import to load ES module"

I get an error like “Must use import to load ES module” when trying to use mdast-util-to-string or other libraries that are in esm format from my nextjs rescript site (regardless of whether I use webpack 4 or 5) with the bsconfig set to output es6. If I understand correctly, as part of the nextjs build, the outputs are finally converted to common-js, but I am getting an error because the nextjs build is not converting the mdast-util-to-string to common-js. I’m not completely clear on what is happening.

My current best guess is to do the following:

  • hack my bindings to the esm based library to use await import in the generated code

I’ll keep digging further, but if someone has an obvious reaction/answer to this, I’m happy to read it.

This works in hacked js output:

const MdastUtilToStringInternal = (await import('mdast-util-to-string')).toString

if i add the following to webpack config:

    config.experiments = {
      topLevelAwait: true,

as well as using next-transpile-modules on mdast-util-to-string.

1 Like