Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share react component across multiple projects?

I have few react components in a project that I would like to use in another few react projects. What would be the best way to share the components across the projects ? I know that we could use something like bitly to do it but is there any other open source way like git submodules to share the components across multiple projects.

like image 715
user1162910 Avatar asked Mar 14 '26 23:03

user1162910


1 Answers

One way that worked for me is to define a component in a React app (using create-react-app), bring that whole React app to Github, and npm install it as a dependency. I highly encourage you to check out this resource which explains in detail how to prepare a React component for this process. Follow the steps in the linked tutorial up to #3, then bring everything (including the /dist folder) to Github. Then, do npm install org_name/repo_nameand install it as a dependency in your second React app. Then, to import a specific component, you can do something like import { Button } from 'repo_name/dist/index' or reference whatever file you used to export your components.

In case the link doesn't work, here are the steps in the article:

  1. Create a folder called lib that stores all the components you want to bring to the other react app. Also define a file called index.js in this folder that exports these components.
  2. Create a repo for the components on Github
  3. Install Babel and build the dist folder.(npm install --save-dev @babel/core @babel/cli @babel/preset-env and npm install -save @babel/polyfill)
  4. Add the following config file to the top-level folder of your project:
{
 "presets": [
  [
   "@babel/env",
    {
     "targets": {
     "edge": "17",
     "firefox": "60",
     "chrome": "67",
     "safari": "11.1"
      },
   "useBuiltIns": "usage",
   "corejs": "3.6.5"
    }
],
   "@babel/preset-react"
]
}
  1. In package.json, replace the build script with the following: "build": "rm -rf dist && NODE_ENV=production babel src/lib --out-dir dist --copy-files";
  2. Run the command npm run build
like image 63
zip27 Avatar answered Mar 16 '26 11:03

zip27



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!