David Gomes
David Gomes

Reputation: 5815

Sharing React components between projects while keeping the source code in one of them

I am looking for a way to share React components (as well as their Flow types and their SCSS) between 2 projects while keeping the source code for the components in one of the projects. The second project would then have a read-only usage of the components from the other project.

However, because the main project is deep inside a directory in a Git repository, I can't add a NPM dependency to the second project of the first project (the package.json in the first project is not at the root git directory).

For now, the only option which I have found is to have a script that manually copies all the code from the directory of the first project to the other. However, I was wondering if there is a more "standard" way of doing this.

Upvotes: 2

Views: 1986

Answers (2)

adz5A
adz5A

Reputation: 2032

You can have it as a NPM dependency and import from it even if its in a nested directory. Actually your application can be totally oblivious as to where the package actually resides if you are using webpack (or any module bundler) using resolve.

In conclusion : no need to have this component as the main of a package.json. Its presence in the node_modules makes it available. Your module bundler can make it easy to import through configuration. Version can be controlled using git with the NPM/yarn support of git urls for installing packages.

Upvotes: 0

sdabrutas
sdabrutas

Reputation: 1517

Try using git submodule. Here's its documentation.

Let's say you have Project1 and you want to use it in Project2. To make it simple, add .gitmodules file in the root directory of the Project2. Inside that file is this:

[submodule "src/project-1"]   //you can change the path to wherever you want to put the Project1 inside Project2
   path = src/project-1   //same as above mentioned path
   url = [email protected]/your-project-1-repo.git
   branch = master //branch of Project1 that you want to use, usually in the master

Then, run this commands within Project2

git submodule init

And whenever you have changes in Project1, just run

git submodule update --remote

in your Project2 to update the Project1 that you are using in Project2

Upvotes: 2

Related Questions