This guide has the following sections :
- Structuring your code for npm 📑
- File Structure for the module 📁
- Publishing and using your module 💻
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.😄
1. Structuring your code for npm 📑
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 ! 🎉
2. File Structure for the module 📁
- Create a new project folder with the name which you want to give your module and cd into it :
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
3. Publishing and using your module 💻
- Go to npmjs.com and create an account.
- Run
npm login
and enter your username and password. - Now enter
npm publish
to have your code published to the NPM database. Go tonpmjs.com/your-package-name
to view your package - If you want to update your package, simply change the ‘package-version’ in your package.json and run
npm 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 !! :