Following Scenario
CustomButton.jsx
CustomButton.jsx
Current Solution
Copy paste CustomButton.jsx
into both Project 1 & 2.
Desired Solution
CustomButton.jsx
D://dev/react/my-component-library
)package.json
to keep consistency accross git clones.CustomButton.jsx
with import statement in Project 1 & 2: import { CustomButton } from "my-component-library"
Questions
create-react-app
or which other tool can be used?The components are fairly simple and don't contain complex logic.
EDIT
This shouldn't cost me anything (private npm does) or use 3rd party hosting, since I already have a privately shared environment/server/directory and I can host/store the packages there.
I solved this problem in vue. But the steps should be pretty similar in react.
1. Create a project with your components (create-react-app
should be fine. You will export your components only anyway, that's why the project setup is irrelevant. It is just useful for development and to test your components.)
2. Use rollup.js to bundle your react components (there are many tutorials online, just google "rollup react component library")
3. Add a new script to your package.json
to bundle your app using rollup -c
.
Then use npm pack
to create the package.
"build:lib": "rollup -c && npm pack"
This will create a zipped package with only the files you need with following pattern:
[package-name]-[package-version].tgz
e.g. my-react-components-0.1.0.tgz
You can influence the resulting package of npm pack
by modifying attributes in your package.json
, e.g. "version"
, "name"
, "main"
, "files"
will influence the output.
4. Now you can install your packages locally from another project:
npm i ../path/to/library/my-react-components-0.1.0.tgz
This will add a new dependency to your package.json
:
"my-react-components": "file: ../path/to/library/my-react-components-0.1.0.tgz"
5. Based on your rollup setup you can then use your library like any other library:
import { MyComponent } from "my-react-components";
You might also have to import the styles:
import "my-react-components/index.css"
If you need a more detailed explanation on a step, just comment below and I will add further information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With