How Can I Make My "Fake ESM" Next 12 Project Use Native ESM?

Viewed 320

I had a perfectly working Next.js version 11 site, which used Babel/webpack to get modern "ES Module" syntax: the only require/CommonJS syntax in my whole app was in next.config.js and babel.config.js.

I updated it to Next 12 and it worked great, so I figured I'd try to get rid of those remaining requires, and make my project fully ESM, by adding "type": "module" to my package.json.

That gave me an error about how next.config.js had to use ESM syntax, so I updated it to ESM syntax ... but now I get an error about how Next is (evidently?) using Common JS to import the babel.config.js?

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/me/project/client/babel.config.js require() of ES modules is not supported. require() of /home/me/project/client/babel.config.js from /home/me/project/client/node_modules/next/dist/build/babel/loader/get-config.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 babel.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/me/project/client/package.json.

Since I'm not in control of Next I don't know how to fix this (and shouldn't Next 12 be importing with ESM by default?) Also my syntax in babel.config.js doesn't seem to even matter: whether I use ESM or Common JS, I get that same error.

Any help would be greatly appreciated.

1 Answers
Related