Creating and Publishing a Node.js Package to npm
This guide will help you create a Node.js package and publish it to npm.
Step 1: Set Up Your Development Environment
First, ensure you have Node.js and npm installed. You can verify the installations by running:
node -v
npm -vIf you don't have Node.js and npm installed, follow the Installing Node.js and Package Managers on Ubuntu Server 22.04 guide.
Step 2: Create a New Node.js Project
Create a new directory for your project and navigate into it:
mkdir my-node-package
cd my-node-packageInitialize a new Node.js project:
npm initFollow the prompts to set up your package.json file. You can accept the defaults or customize the fields as needed.
Step 3: Write Your Package Code
Create a new file named index.js and add your package code. For example, let's create a simple function that adds two numbers:
// filepath: /home/kelly/ws/guide/node/my-node-package/index.js
function add(a, b) {
return a + b;
}
module.exports = add;Step 4: Add Tests
It's a good practice to add tests for your package. Create a new directory named test and add a test file:
mkdir test
touch test/test.jsIn test/test.js, write a simple test for your add function:
// filepath: /home/kelly/ws/guide/node/my-node-package/test/test.js
const add = require('../index');
const assert = require('assert');
assert.strictEqual(add(2, 3), 5);
console.log('All tests passed!');Run the test to ensure everything is working:
node test/test.jsStep 5: Prepare for Publishing
Before publishing, you need to create an npm account if you don't have one. You can sign up at npmjs.com.
Log in to your npm account from the command line:
npm loginFollow the prompts to enter your username, password, and email.
Step 6: Publish Your Package
To publish your package, run:
npm publishIf the package name is already taken, you will need to choose a different name. You can update the name field in your package.json file and try publishing again.
Step 7: Use Your Published Package
You can now install and use your published package in any Node.js project. For example:
npm install my-node-packageThen, require and use it in your code:
const add = require('my-node-package');
console.log(add(2, 3)); // Outputs: 5Conclusion
You have successfully created and published a Node.js package to npm. You can now share your package with the world and use it in your projects.