How to Build Your Own React Package and NPM Install in Another Project
If you ever want to publish your own library, you will need to upload a new project onto Github.
In this tutorial, I will teach all of you how to create your own react project, upload it to GitHub, create another react project, and uploading the initially created project as a package.
To begin, you need to install node on your machine with the following command:
- curl “https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE ‘s|.*>node-(.*)\.pkg</a>.*|\1|p’)}.pkg” > “$HOME/Downloads/node-latest.pkg” && sudo installer -store -pkg “$HOME/Downloads/node-latest.pkg” -target “/”
Now create a folder and create index.js. Index.js is where you will be exporting your functions from the package.
Afterward, create a package.json within the same folder and include the following:
This will be a repository consists of util functions that we will export.
Afterward, create index.js and include the following:
Next, we need to log in to github.com. If you haven’t created any account please do so.
Afterward, go to https://github.com/new and create a public repository. You can name it anything and you want and don’t initialize the readme. Click “Create Repository”.
Now go to terminal and ls to the directory/folder that contains index.js(I name it as utilsExport.js but it is really index.js) and package.json. Your project structure should look something similar to this:
If you go to the webpage you were on after creating a repository in GitHub, locate “…or create a new repository on the command line” and run the instructions, line by line.
Go to your GitHub and locate your utils directory. Click on code and you should get a URL under “clone with https”. Keep that URL on hold as you will be including this URL in your new project package.json.
Now create a new react project.
Step 1: run curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -q0- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg</a>.*|\1|p')}.pkg”> "$HOME/Downloads/node-latest.pkg” && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg” -target "/”
Step 2: run the following command to create a new react project: npx create-react-app sample-project
Step 3: After the project is successfully, go to package.json and add the following line under “dependencies”: “utils”: “git+https://github.com/<username>/Utils.git”
Step 4: run npm install
Step 5: in app.js, you can import { add, sub } from “utils” and utilize within the application.
That’s how it is to creating your external dependencies and incorporating them into another application.
Now you can create your own open-source libraries if you want to!