Simplest Way to Install Babel Plugins in Create React App
Anson Heung
Posted on December 27, 2021
The traditional way of installing Babel plugins in a Create React App project requires you to eject the app via running npm run eject
. However, ejecting may be a bad idea because it’s a one-way operation that exposes complex configurations files.
In this article, I’ll show you how to install Babel plugins WITHOUT ejecting your Create React App.
Steps
-
Install react-app-rewired and customize-cra:
npm install react-app-rewired customize-cra --save-dev # or yarn add react-app-rewired customize-cra --dev
Purpose of these two packages
-
react-app-rewired
: Overrides Create React App webpack configs without ejecting. -
customize-cra
: Provides a set of utilities to customize Create React App config, such as reading from.babelrc
. Requiresreact-app-rewired
as a dependency.
-
-
Install your Babel plugin(s). Suppose our Babel plugin is called
babel-plugin-myPlugin
:
npm install babel-plugin-myPlugin --save-dev # or yarn add babel-plugin-myPlugin --dev
-
Open
package.json
located in the project root and edit the"scripts"
field:
"scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test", + "start": "react-app-rewired start", + "build": "react-app-rewired build", + "test": "react-app-rewired test", "eject": "react-scripts eject" },
-
Create
.babelrc
at the root of the project (wherepackage.json
is located) and add the following code. Replacebabel-plugin-myPlugin
with the actual name of your plugin.
{ "plugins": ["babel-plugin-myPlugin"] }
-
Create
config-overrides.js
at the root of the project and add the following code:
// Overrides create-react-app webpack configs without ejecting // https://github.com/timarney/react-app-rewired const { useBabelRc, override } = require("customize-cra"); module.exports = override(useBabelRc());
Run
npm start
oryarn start
to start the development server and see if everything works properly.
Without Using .babelrc
In the above, Step 4 requires you to create a new .babelrc
file to register Babel plugins. Alternatively, you can skip Step 4 (i.e., no need to create .babelrc
) by directly registering Babel plugins inside config-overrides.js
:
// Overrides create-react-app webpack configs without ejecting
// https://github.com/timarney/react-app-rewired
const { addBabelPlugins, override } = require("customize-cra");
module.exports = override(
...addBabelPlugins(
"babel-plugin-myPlugin"
/* Add plug-in names here (separate each value by a comma) */
)
);
Thanks for reading! If you find it useful, don’t forget to like and share this post 🙌
- Follow me on Twitter: @AnsonH_
- Personal website
- GitHub profile: AnsonH
Posted on December 27, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.