Why does module.exports not work in react?

But export default does?

bump - please could someone help me?

The short answer is that it is possible. The long answer can go down the rabbit hole and take you to a whole lot of other topics, such as the build process, tooling, versions of different packages, etc.

For example, if you go to Codesandbox.io and create a sandbox for a React project using their template (It’s based on create-react-app), then copy/paste the following to the specified files, it will work fine:

App.js

const React = require('react');

function App() {
  return <h1>Hello</h1>;
}

module.exports = App;

index.js

const React = require('react');
const ReactDOM = require('react-dom');

const App = require('./App');

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

They are using a template based on a slightly older version of create-react-app, so it’s using react-scripts version 3.4.3. It works just fine there.

Newer apps created with create-react-app use react-scripts version 4.0.1. The packages that create-react-app uses matters because behind the scenes it’s taking care of a lot of configuration as far as webpack, babel, and a lot of other tools. Somewhere between those versions, the default configurations of some of those tools that take care of transpiling stopped using a configuration that allowed the code above automatically. You don’t get to access those configurations unless you eject (npm run eject), but you’d want to do more research about that topic too. There may even be newer options that we do have access to that would allow it without having to eject.

A lot of this was about create-react-app specifically since I’m thinking that is what you’re using, but there are plenty of build processes out there that can be used. Once you have access to the configurations and choosing your own tools, then you can do whatever you want.

I won’t go any deeper about it here because this is already longer than I intended, but let me arm you with some search terms that will help you pinpoint information if you do want to dive deeper. CommonJS (CJS) is the module formatting system that uses module.exports and require()

1 Like

Just saw this. Thank you so much for the detailed response, really appreciate it1