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
We’re hosting our react component library on Bitbucket
The library we’re wanting to create is react-ft-components
The project where we’d want to use these components would be react-ft-rockon
We’re also assuming that will primarily be using yarn package manager
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:
Create application using CLI
create-react-app react-ft-components
Install dependencies
yarn add @babel/cli @babel/core --dev
yarn add @babel/preset-env @babel/preset-react --dev
Create a .babelrc file
touch .babelrc
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>
)
}
}
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",
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.
Rename devDependencies to dependencies
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
Once this is done you can also generate tarball using
yarn pack
Installing created library¶
Create a new react app using
create-react-app react-ft-rockon
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
Use the component in App.js, firstly import it
import DummyComponent from 'react-ft-components';
and then use it in the application
<DummyComponent />
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?