Extract your React components as dependencies in a lerna + CRA project without ejecting

David Brown
2 min readJul 18, 2019

--

The simple way…

1. Set up your shared components in packages/components

2. Use your component in your CRA app

[ProTip] You can’t “yarn add” your sub-project, you have to add it manually to the dependency list.

Then just import and use it somewhere.

You should now see the message:

Failed to compile. SyntaxError: […]: Unexpected token

Which means your JSX code is not valid Javascript: you have to tell webpack to add your component code to the list of folder to be transpiled with babel.

3. Force your component to be transpiled

In order to change the webpack configuration provided by CRA without ejecting, you have several solutions. One of them is to use react-app-rewired:

Steps:

cd packages/cra-app# Install react-app-rewired
yarn add -D react-app-rewired
# Create config file
touch config-overrides.js
# Replace react-scripts by react-app-rewired
sed -i -- 's/react-scripts /react-app-rewired /g' package.json

Note: customize-cra is a helper to edit the right part of the CRA webpack configuration but you can manually edit the babel rule inside “config.module.rules” (ie. add “path.resolve(‘../components’)” to the “include” key).

4. Enjoy

Everything should be working like before, with hot-reloading and all \o/.

--

--

David Brown

Developer & co-founder of https://www.notif.me (transactional notification API for developers)