Sharing components between two react apps

Viewed 4603

I have two react Apps that I want to keep separate. However, many of the components are very similar between the two apps.

What is the best approach for sharing components?

Here are some approaches I can think of:

  1. Duplicate the components as they may vary slightly
  2. Import the files from a folder outside the project scope

thanks

2 Answers

If the components "may vary slightly" then maybe you should duplicate them. But if you can find a way to keep them the same (and keep variations in props passed in), here how I've done it:

I setup a separate project that has all common components. There are two ways I've accessed those components from the server build system:

  1. Publish either a public or private npm module, and add to package.json like any other npm module (read more about private modules here)
  2. If private npm modules are too complicated but you still want to keep the project private, you can add a private repo to your package.json. You'll need to have the ssh key saved on your build system so it can login to github or bitbucket (or whatever) to checkout your code.

If you go with option 2, you can include repos in your package.json like this. Then when npm install is run, it will ask for a credentials to your private repo (or it can use an ssh key).

...
"dependencies": {
  ...
  "your-common-module": "git+ssh://git@bitbucket.org/path/to-repo.git#0.1.5"
}

Unless your components are A. Private or B. Already produced by someone else, why not contribute them to the npm repository for others to use?

You can do this by

  1. Creating a user
  2. Publishing the package
  3. Updating the package

You can view specific documentation @ https://docs.npmjs.com/getting-started/publishing-npm-packages

Related