Create a ReactJS package

In this guide we will cover how to create and use a ReactJS components library using a Private Repository.

Assumptions

This guide assumes

  1. We’re hosting our react component library on Bitbucket
  2. The library we’re wanting to create is react-ft-components
  3. The project where we’d want to use these components would be react-ft-rockon
  4. We’re also assuming that will primarily be using yarn package manager
  5. We’re assuming you already have create-react-app CLI installed

Create library

This section of guide includes how to create a react-ft-components library. Steps are as follows:

  1. Create application using CLI
create-react-app react-ft-components
  1. Install dependencies
yarn add @babel/cli @babel/core --dev
yarn add @babel/preset-env @babel/preset-react --dev
  1. Create a .babelrc file
touch .babelrc
  1. Get rid of all files in src folder
cd src && rm *

and create components/index.js file with following contents

import React, { Component } from 'react';

export default class DummyComponent extends Component {
    render () {
        return (
            <div>I am a dummy react npm module</div>
        )
    }
}
  1. Do a sanity check and see if you’re able to build index.js
./node_modules/.bin/babel src/components --out-file index.js

6. Update build and postinstall script in package.json by adding following line {within script block}

"build": "./node_modules/.bin/babel src --out-file index.js",
"postinstall": "./node_modules/.bin/babel src --out-file index.js",
  1. Check with yarn build and see if everything is working fine

8. In package.json rename dependencies to peerDependencies. This assumes that react-ft-components will be used in a project where packages mentioned in peerDependencies are already installed.

  1. Rename devDependencies to dependencies
  2. Commit the code to Bitbucket
git init
wget "https://raw.githubusercontent.com/github/gitignore/master/Node.gitignore" -O .gitignore
git add .
git commit -m "first commit"
git remote add origin git@bitbucket.org:<username>/<repo-name>.git
git push -u origin master
  1. Once this is done you can also generate tarball using
yarn pack

Installing created library

  1. Create a new react app using
create-react-app react-ft-rockon
  1. Install tarball using
cd react-ft-rockon/
yarn add ../react-ft-components/react-ft-components-v0.1.0.tgz

Alternatively you can install directly from repo as follows

cd react-ft-rockon/
yarn add ssh://git@bitbucket.org:<username>/<repo-name>.git
  1. Use the component in App.js, firstly import it
import DummyComponent from 'react-ft-components';

and then use it in the application

<DummyComponent />
  1. Build and start the application
yarn start

Reference:

1. Building a React component as an NPM module 1. Create Node.js module 1. How to create and publish NPM Packages?