Shared components in two create-react-app setups

(Evan G) #1


I am building a React app (through create-react-app), and I want to share some of its components in a second, separate React app. What are the recommended ways of doing this?


(Eric Masiello) #2

Is the idea that the create react app will just be a library of components and not an actual app?

(Evan G) #3

As it stands, currently, I have 2 separate apps, which I want them to share a few components. So it’s not a library, but 2 apps. Btw… create-react-app expects an application endpoint and an HTML app container. I have no clue how I would create just a library with it.

(Guptaanoop2005) #4

There is a concept of monorepo which uses multi packages concept. you can use Lerna ( to make your reposirory as a multipackage repository. Create packages in your repo and you can share them in other app folders. You can create as many as app in your repo/ folder.
An ideal structure could be like
Common - where you can have your shared components.
App1 - App1 can import components form common
App2 - App2 can import components form common

On thing you need to keep in mind that there should not be any interdependency between App1 and App2 and Common does not have dependency on any apps.

In addition to that , you need to add configuration in your webpack/ roll up/ any bundler for bundling various apps separately.

(Jovica Aleksic) #5

You might get away without lerna by just using yarn workspaces

You simply create a package.json like this:

“private”: true,
“name”: “@client/workspace”,
“workspaces”: [“packages/*”]

And keep your apps inside packages/app-one and packages/app-two. Both apps will be able to use packages/foo and packages/bar, if they have regular package.jsons. It works out of the box if your shared packages don’t need transpiling, e.g. they have their own build scripts and transpile into /lib, and their package.json “main” field points to the file in /lib.
Otherwise, if you want to import the raw source code, it might be more complicated.

Keep in mind that you won’t be able to use create-react-app inside a yarn workspace to create the app. It’s a known issue.
However, it works perfectly if you use create-react-app outside the yarn workspace to create the app and then copy it into your workspace.

Just recently I also created crosslink that might be useful. Keep in mind that it’s not battle-tested at all :slight_smile: It’s just an idea.

(Jeremy) #6

Just copy and paste them into a lib folder with a minimal package.json and add it as a dependency in your main package.json, something like “@loopmode/components”:”./lib/common” , when you npm i or yarn it pretty much just copies it over to node_modules, so u can treat it like you published it