Search code examples
node.jscreate-react-appcommonjs

create-react-app importing modules as ES6 Modules when project is using CommonJS Modules


I am trying to use CommonJS module format, with create-react-app (CRA). The documentation for CRA says:

..Create React App can consume both CommonJS and ES modules. For Node.js compatibility, it is recommended that the main entry point is CommonJS...

I am finding that when I import a module that offers ES6 module format (via is "module" property in "package.json"), then CRA uses this as the entry point for the module.

Thus - even when my project is using CJS entirely, it then tries to import ES6 modules - and fails.

So - Is this a bug? Or, am I misunderstanding the intended behaviour of create-react-app?

Reproducing

I have reproduced this here: https://github.com/mjashanks/cra-test. This project is a basic CRA skeleton, modified to used CJS.

Additionally, I have added a "test-module", whose a package.json includes a "main" (CJS) and "module" (ES6) entry point.

If we run npm start, the project fails to build, as the file "test-module/index.esm.js" is being used. (We can edit this file to use CJS format to make the project build and make this more clear).

"test-module/index.cjs.js" is never used.

Thanks :)


Solution

  • I found that this actually turned out to be an issue (actually expected behaviour) with Webpack: https://github.com/webpack/webpack/issues/5756