DEV Community

Arpit Jain
Arpit Jain

Posted on

CREATE LIBRARY OF REACT COMPONENT

Create React App is a comfortable environment for learning and developing React application. It is the best way to start building a single-page application in React.

By adding few more steps, we can convert our React component into the library. Later, you can publish it to NPM and let the world use that component as reusable and ready-made component into their application.

SO, LET’s BEGIN THE JOURNEY!!!

This journey having 9 milestones. All’re pretty simple and easily achievable.

MILESTONE #1

If you already have create-react-app boilerplate CLI install, you can skip, otherwise have it install using below command.

npm install -g create-react-app

Once you have it successfully installed, you’re ready to create a new project using above installed boilerplate and to do that please run below command.
create-react-app my-first-react-library

  • ’my-first-react-library’ is my project name. You’re free to give any name.

Congratulation! First milestone achieved.

MILESTONE #2

Here, we have to perform two mini steps.

  • Remove all the content available inside folder src and perform below inside src folder.
  • Create a new file, give name as index.js.
  • Create two folder and give name as lib and module.
  • Create one more index.js but this time inside lib folder. It should be like lib/index.js.
  • Create one more index.js but this time inside module folder. It should be like module/index.js.

Your folder hierarchy should like below: -
Alt Text

MILESTONE #3

Now, whatever component’s code you want to package to make it as reusable component, need to put inside src/lib folder.
src/lib folder will be considered as distributed code and entire content from this folder will be published to NPM.

Any external file like CSS or images which are the part of your component, should available inside the "src/lib" only.

MILESTONE #4

In the second milestone, we’ve created src/lib/index.js. Now it’s the time of using that. Here, we need to import our component reference and export it, for the use as an external package.

Finally, your lib/index.js should look like this: -

 import <your-component> from './ <your-component-reference>'
 export default <your-component>

If you want to export single component, you can declare it as export default. Or if you have multiple components to export, in that case your declaration should be like

export {your-component-1, your-component-2}

For better understanding, please refer to below GitHub location: -
https://github.com/arpitjain-in/create-react-component-library

MILESTONE #5

Before publishing it to NPM, it is always good practice to test it a local machine and if necessary, we can debug too at local machine.
Let’s start testing using src/module/index.js. Your code snippet should look like this

import React from 'react';
import <your-component> from '../lib';
const App =()=> <your-component>;
export default App;

Again, for better understanding, please refer above mentioned github link.

Add module/index.js reference to src/index.js,

import React from 'react';
import ReactDOM from 'react-dom';
import App from './module';
ReactDOM.render( <App/>, document.getElementById('root') );

After following till now, You’re ready to run npm start and to see the magic on browser.

MILESTONE #6

To make component publish-able, we need to some changes in package.json as well as need to install babel-cli.
First thing first, install babel-cli using below command: -

npm install babel-cli --save

After successful install, create .babelrc file at the root level of the project and add below content: -

{ “presets” : [[ “react-app”,{ “absoluteRuntime”:false }]]}

In package.json, change the “build” script to the below content.

"build": "rm -rf dist && NODE_ENV=production babel src/lib --out-dir dist --copy-files --ignore __tests__,spec.js,test.js,__snapshots__"

With above script changes, src/lib folder code will transpile to “dist” folder.It will also ignore spec, test and snapshot specific JS files.

MILESTONE #7

Perform below steps: -

  • Delete the line "private": true from package.json.
  • Move react-scripts, react and react-dom from dependencies to devDependencies.
  • Optionally, you can also add react and react-dom to peerDependencies.

Congratulation! All major milestones achieved.

MILESTONE #8

Publishing Preparation

  "main": "dist/index.js",
  "module": "dist/index.js",
  "files": [ "dist", "README.md" ],
  "repository": {
    "type": "git",
    "url": "URL_OF_YOUR_REPOSITORY"
    } 
  “author”: <your-name>
  “keyword”: [<mention all your keywords comma separated>]

MILESTONE #9

And Finally, “Do Publish”

For public NPM push
npm run publish –-access public

For private push
npm run publish

Created by Arpit Jain.

Discussion (10)

Collapse
ferittuncer profile image
Ferit Tunçer

Nice tutorial!

A problem though: yarn build gets an error from Babel:

ReferenceError: [BABEL] src/lib/footer.js: Unknown option: /home/u/repos/react-component/node_modules/babel-preset-react-app/index.js.overrides. Check out babeljs.io/docs/usage/options/ for more information about options.

Collapse
sergioavazquez profile image
Sergio Vazquez • Edited

There's something missing here, that's why some are getting the babel error:

npm install --save-dev @babel/cli @babel/core @babel/preset-react

Also babel-cli is not needed if you install @babel/cli with the command above.

Hope it helps!

Collapse
mmnoo profile image
Melissa Nunes

I get the same error as others with yarn build. It doesnt look like it knows about JSX. (I am new to React, so forgive me that I dont have a solution!)

yarn run v1.21.1
$ rm -rf dist && NODE_ENV=production babel src/lib --out-dir dist --copy-files --ignore __tests__,spec.js,test.js,__snapshots__
SyntaxError: src/lib/components/FormField/FormField.js: Unexpected token (15:9)
  13 |   value,
  14 | }) => {
> 15 |   return <div>fsdkhfsdkfjksdfjkls</div>
     |          ^
  16 | }

Even after installing @babel/cli @babel/core @babel/preset-react

Collapse
mmnoo profile image
Melissa Nunes

OK, it looks like for this error, my when I copy pasted the above config into .babelrc I didnt notice, nor did my IDE, that the double quotes were not kosher. Once I fixed the double quotes it complained :

Options {"absoluteRuntime":false} passed to <path>/node_modules/babel-preset-react-app/index.js which does not accept options.

So I removed those options and it seems to work without errors (at least so far...)

Collapse
crisleo94 profile image
Cristhian Reinoso

For those trying to execute the npm run build, yarn build or others commands like this, please be aware that in this tutorial there's nothing more needed, just run the npm publish and you'll see what I'm talking about. (create an npm account as well), everything will be working and you will see your package. (if Windows users are having troubles with any of this, remember we always have WSL to our disposure)

Collapse
inversemetric profile image
Stephen Bussard

If you use jsconfig.json and have compilerOptions.baseUrl set so that you can use src-relative imports, then using babel will break the consumer of the component. It is necessary to build (webpack bundle) the components in that case.

Collapse
luckcfm profile image
Lucas Cesar F. de Medeiros

Hi nice tuto!
But where should I write the milestone 8?
Thanks.

Collapse
askadar profile image
Антон Обрядин

Hi there,
it's an excerpt from package.json related to npm publishing entries.

You can read more about npm publish process at npm-publish doc and general package.json fields description

Collapse
tdubs profile image
Thom W

what are the advantages of this method vs create-react-library?

Collapse
s530669 profile image
S530669

Awesome tutorial!