Setup
We'll use create-react-library CLI tool to generate our library project.
For this, let's first install create-react-library
globally:
npm install -g create-react-library
Now run below command to generate our library project:
create-react-library
You will be prompted with couple of questions as below:
After the above command finishes. Notice the output's last few lines as shown below.
Actually if you cd
into the folder and notice the content. There is one extra project inside folder named example
, which is create-react-app application that you can use to test the component that you will build in the library.
To start developing,
- run
npm start
in the root folder of your project to compile your source code intodist
folder every time you do changes in your library code. - run
npm start
from inside ofexample
folder to start serving the example project at localhost.
Code
Now we have the servers running. Next thing is to understand src/index.js
and example/src/App.js
.
If you notice src/index.js
it is right now exporting one component ExampleComponent
and the same is being used in example/src/App.js
.
If your library is supposed to export only one component. Then you are done here. Go on and start implementing your component in src/index.js
.
Multiple components
In my case, I wanted to expose multiple components out of my library.
For this:
- I created a new file for each component under
src/
folder.
E.g.src/BasicCounter.js
andLikeCounter.js
. - Then updated
src/index.js
file as below:
import {BasicCounter} from './BasicCounter'
import { LikeCounter } from "./LikeCounter";
export { BasicCounter, LikeCounter }
-
Make the changes in
example/src/App.js
accordingly to test these components:import { BasicCounter, LikeCounter} from 'events-counter-react'
const App = () => { return (
Thats it for this note!
Helpful?
If you think this is helpful 🎈
Don't keep it to yourself 🙊
Share it with your lovely followers at twitter 🗽