DEV Community

Rich Field
Rich Field

Posted on • Updated on

How to modify config of Create React App - without Ejecting!

I'm using Create React App (CRA) for a couple of client projects.
To keep things easier to maintain once the project is handed over I've not ejected.

However today I ran into the common "Hooks + multiple instances of React" issue as I was attempting to consume a component library I had created.

Both this library and the main app were including their own copy of React.

To solve this and prevent the error I needed to do two things:

  • Update the library to list React as a peer dependency and then update the bundler (rollup) to not include React in the bundle.

  • Add an alias for React to the Webpack config of the main app

The first step was easy, but as you might know, it's not possible to modify the Webpack config of CRA without ejecting it.

Or so I thought...

Turns out you can by using CRACO - which stands for Create React App Configuration Override.

After installing and a quick modification of the package.json scripts, I can now use a craco.config.js file to override the default CRA Webpack config.

const path = require('path')

module.exports = {
  webpack: {
    alias: {
      react: path.resolve(__dirname, './node_modules/react'),
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

For more info on the issue itself and solutions see:
https://github.com/facebook/react/issues/13991

Top comments (5)

Collapse
 
brad19 profile image
Brad19

Thanks for sharing. I'm new to this eco system of config. My create-react-app is typescript, but i do have some shared code from react-native mainly for services which has both .js & .ts files. So I have .eslint.rc to configure the .js files and for .ts files I have .tsconfig.json to do so. I'm having the same issue trying to access the alias path from App.tsx where it throws "Module not found.." I've raised an issue here . github.com/facebook/create-react-a.... Can you please check and Kindly advise as i'm in a dire need to solve this at the earliest.

Collapse
 
ogheneovo12 profile image
ogheneovo12

can you please share a link to the project, having issues with combining rollup and craco

Collapse
 
rdewolff profile image
Rom

Thanks for the tip!

Collapse
 
anandharshan profile image
Anand Harshan

Could you please elaborate on how to do

Update the library to list React as a peer dependency and then update the bundler (rollup) to not include React in the bundle.

Collapse
 
kildareflare profile image
Rich Field

In the library I updated the package.json, moving React from dependencies to peerDependencies
E.g.

  "peerDependencies": {
    "react": "^16.12.0"
  }
Enter fullscreen mode Exit fullscreen mode