Create and Publish npm module
Creating and publishing an npm module is a great way to share your code with the community. Here’s a step-by-step guide to help you through the process.
Step 1: Set Up Your Project
First, create a new directory for your module and navigate into it:
1 2 |
mkdir my-npm-module-example cd my-npm-module-example |
Next, initialize your project with npm:
1 |
npm init |
This command will prompt you to enter various details, such as the module name, version, and description. Fill these out to create your package.json
file.
Step 2: Write Your Module
Now, create a JavaScript file where your module logic will reside. Let’s create a simple utility function that adds two numbers. Create an index.js file and add the following code:
1 2 3 4 5 |
function add(a, b) { return a + b; } module.exports = add; |
This code defines a function add
and exports it so that other modules can use it.
Step 3: Create a README File
Now, create a README.md file describe what your module does and how to use it. Here’s a simple example:
1 2 3 4 5 6 7 8 |
# My NPM Module This module provides a function to add two numbers. ## Installation ```bash npm install my-npm-module-example |
Usage:
1 2 |
const add = require('my-npm-module'); console.log(add(2, 3)); // Outputs: 5 |
Step 4: Publish
Create a npm account to publish the package. Once done please ensure you are logged in to your npm account: npm login
Then, publish your module with: npm publish
Step 5: Update Your Module
If you make changes, update the version in your package.json
, then run npm publish
again.
Conclusion:
Congratulations! You’ve successfully created and published an npm module. Share it with the world and encourage others to contribute!