Custom create-react-app webpack configuration

av paul

Last Updated on Mon, Oct 07, 2019

02 mins read

Hands down, Create-React-App is the best! But at one point in your development process, you need to add some custom configurations!

CRA provides an easy and trusted way to bootstrap any React app project. At one point you need to change something in the configuration, like adding Babel plugins or other Webpack configurations.

The CRA documentation mentions two options, Ejecting or forking react-scripts. Ejecting gives power over the configurations and scripts but if you have many projects you will have to do the same process. The second option is to fork react-scripts, this gives you your own CRA library that you can use and share with others. The downside of both options is that you will no longer benefit from CRA updates.

There is an easy way to customize CRA Webpack configs! Meet react-app-rewired and customize-cra. React-app-rewired overrides the configurations while customize-cra gives you a set of utilities to customize the configurations.

Challenge😤

const Home = ({ user }) => {
  return <div>Welcome { user?.name }!</div>;
};

I want to use Optional chaining. If you don't know about optional chaining check this article. I get an error! I need to add the optional chaining plugin in babel configuration and I don't have access to the configs.

Solution😁

Start by installing dependencies

yarn add react-app-rewired customize-cra -D

Then create a config-overrides.js file

const { override, useBabelRc } = require('customize-cra');

module.exports = override(useBabelRc());

As mentioned, customize-cra has many utilities that you can use to override default configs. useBabelrc overrides babel configs. We need to create a .babelrc file

{
    "plugins": ["@babel/plugin-proposal-optional-chaining"]
}

If you start the project, you still get the same error🤔 This is because we are still using react-scripts to start or build the project. We need to use react-app-rewired for our customizations to work. Let's update the package.json file.

...
"scripts": {
    - "start": "react-scripts start",
    + "start": "react-app-rewired start",
    - "build": "react-scripts build",
    + "build": "react-app-rewired build",
}
...

Start the project and now the error is gone. We've customized CRA👏

If you can't find any customize-cra utility to help you add your configurations, you can define your own utilities or customizers.

In your config-overrides.js

const { override } = require('customize-cra');

const myCustomizer = () => (config) => {
    // your customizer receives webpack configs object as a parameter
   // do whatever
   return config;
}

module.exports = override(myCustomizer());

Thanks for reading🙏 If you enjoyed this and would like to learn together with me follow me on twiter to stay tuned🤙

If you have a comment, leave it here!

  back home