This guide has the following sections :
Note : This guide assumes that you have node and npm installed. I will be using module and package interchangeably to refer to your npm module.😄
npm modules are pieces of code which can be included into your Node.js program by using require(). As far as you the author are concerned, they are seperate Node.js programs on your file system, which export some function for other programs to use.
Consider your boilerplate JS :
const dependency = require(‘dependency-name’);//list all requires required by your npm module
function yourFunction(args) {// operationsreturn result;}
You convert this code to an npm module by simply placing your function into a module.exports variable. In the following example, I will be placing the function in const to export it as a variable :
const dependency = require('dependency-name');//list all requires required by your npm module
const yourFunction = (args) => {//operationsreturn result;}
module.exports = yourFunction;
That’s it for the coding part ! 🎉
mkdir module-namecd module-name
Place your newly created js file in this folder and rename it to your module name as module-name.js
2. Use npm init
and give answers to the questionnaire like package-name,version,etc. This creates a package.json file with your provided information.
Finally, populate your package.json with the following fields to make your module SEO-friendly.
Note : Here the 'main' field is important as it is the entry point of your module
npm login
and enter your username and password.npm publish
to have your code published to the NPM database. Go to npmjs.com/your-package-name
to view your packagenpm publish
again.To use your published module in any of your Node.js programs, simply install it using
npm i your-package-name --save
And finally, use your module by including it in your code via require() and then use your function directly. 😄
const dependency = require('your-package-name')
const desired_result = dependency(args)
Get in touch !! :