To publish a package to npm, we should follow the following steps.
STEP 1 : Make sure your project have package.json file something like this.
{
"name": "your-package-name",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}
STEP 2 : update your entry file with required functionality. Here entry file is index.js as we defined in package.json as “main”: “index.js”. Following is some example code.
// index.js
module.exports = function greeting(name) {
return `Hello, ${name}!`;
};
STEP 3: signup to npm using https://www.npmjs.com/signup
STEP 4: Now login to npm using the following command in the terminal
npm login
STEP 5: publish the package using the following command. (Make sure package name is unique)
npm publish
Finally you are able use that package anywhere by just installing with the following command
npm i your-package-name