What is npm?
npm is the world's largest software registry. Open source developers from every continent use npm to share and borrow packages. you can create your own npm package for personal use, at the same time other developers can use it!
SO... HOW?
- Create the code that you want to publish in npm, it could be a javascript function or a react component. anything that you think can be useful for you and to others.
example:
this function is going to generate random number with letters in it that can be use as ID
const generateID = () => {
const alphabetArray =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXWZ".split("");
const numberArray = "1234567890".split("");
let ID = [];
for (let i in alphabetArray) {
const random = Math.floor(Math.random() * i + 1);
if (ID.length <= 5 && numberArray[i]) {
ID.push(numberArray[random] + alphabetArray[random]);
}
}
return `0x-${ID.join("-")}`;
};
export default generateID;
make sure the name of the file is
index.js
or it could be anything just edit yourpackage.json
file.as you can see the code is exported using module.exports, this step is really important for you to use your package in other place.
Create a github repo for your npm package. the reason why we are creating a github repo is for the package.json file to have all of the github information linked inside of it.
make sure to change the "repo-link" with your own repo.
echo "# repo-link" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add repo-link
git push -u origin main
Now, initialize the npm, your terminal will ask you about the information of your package, but we are able to initialize it earlier. Just enter the name of your package on the first question and the rest is optional.
npm init
test your package.
example:
make sure to import your package like so.
const generateID = require('generateID');
//ES2015
import generateID from 'generateID';
`shell
npm login
`
make sure to verify your account first or else later on there will be an error while publishing.
Now you can publish your first npm package like so.
`shell
npm publish
`
Possible errors while publishing
- The name of the package already exist
fix:
in your
package.json
file you can edit the name of your package to @name_of_your_account/package_name like so.
`json
"name": "@name_of_your_npm_account/package_name"
`
and also on publishing it you have to define that it's a public package because automatically npm will tag it as a private package which will cause an error publishing it because you have to be a premium user to use this feature.
publish it like so.
`shell
npm publish --access=public
`
- mostly possible problem can be your account is not yet verified
Top comments (0)