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

时间:2018-09-19 08:26:09

标签: javascript reactjs npm

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.

2 个答案:

答案 0 :(得分:1)

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 = git@github.com/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

答案 1 :(得分:0)

您可以将其作为NPM依赖项并从其导入,即使它位于嵌套的directory中也是如此。实际上,如果您使用resolve使用webpack(或任何模块捆绑程序),则您的应用程序可以完全忽略软件包的实际位置。

结论:无需将此组件作为package.json的main。它在node_modules中的存在使其可用。您的模块捆绑器可以轻松地通过配置导入。可以使用具有git url的NPM / yarn支持的git来控制版本,以安装软件包。