Skip to content
Advertisement

Cannot build an app when there is CommonJS instead of ES6 module exports/imports

I generated a simple app through create-react-app (v3.3.0 for what that is worth) without messing with it’s default settings.

For the most part, I use I do exports using the ES6 syntax:

export default myStuff

// Or

export const myStuff = ()=>{}

However, I wanted one of my scripts to also run in node’s CLI. Because of this, some select files use the commonJS syntax:

module.exports = myStuff

That is all fine and well, until I decided to build and deploy the app, which then complains that myStuff is not being imported if I use the commonJS syntax, the error I get is precisely:

Creating an optimized production build… Failed to compile. Attempted import error: ‘myStuff’ is not exported from ‘./myStuff’.

I should point out that the build and dev scripts were left with whatever was generated by create-react-app. Precisely:

...
  "dev": "react-scripts start",
  "build": "react-scripts build",
...

Keep in mind that when running locally both on the Browser and using the Node CLI everything works perfectly. Did I miss something? How could I build with the existing CommonJS files?

Edit: To clarify the question asked by @JustRaman, my usage of these exports within the client app starts with an index.js file which lives in the same folder. Think of it as the following:

├── ...
├── lib
│   ├── myCommonJSStuff.js
│   ├── myOtherCommonJSStuff.js
│   ├── myEs6Stuff.js
│   └──  index.js

From myCommonJSStuff.js I do the export as follows:

function myCommonJSStuff () { /* Do Stuff*/ }
module.exports = {
  myCommonJSStuff,
  someOtherIrrelevantFunction
}

From myOtherCommonJSStuff.js it would just be the a single default export equivalent:

module.exports = function myOtherCommonJSStuff() { /*Do more stuff*/ }

For myEs6Stuff.js as its name suggest, I use ES6 syntax:

export default function myEs6Stuff () { /*More stuff*/ }

Finally, index.js I re-export everything so that I can just import it from my lib/ folder:

import { myCommonJSStuff } from './myCommonJSStuff'
import myOtherCommonJSStuff from './myOtherCommonJSStuff'
import myEs6Stuff from './myEs6Stuff'

export {
  myCommonJSStuff,
  myOtherCommonJSStuff,
  myEs6Stuff
}

Advertisement

Answer

I found a similar issue https://github.com/facebook/create-react-app/issues/6163 seems like there is no easy solution except ejecting.

  1. you can use https://www.npmjs.com/package/react-app-rewired if you don’t want to eject CRA.

  2. Another solution can be a module loader to load ESM files in Node https://www.npmjs.com/package/esm this package can help.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement