How to Create and Publish Your First NPM Package: A Complete Guide

dipakahirav

Dipak Ahirav

Posted on September 1, 2024

How to Create and Publish Your First NPM Package: A Complete Guide

Creating and publishing your own NPM package is an exciting way to contribute to the developer community, while also boosting your own coding skills. In this guide, I'll walk you through every step, from creating an NPM account to publishing a useful package called env-config-check. This package will help developers ensure that all required environment variables are set before their applications start.

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

Why Publish an NPM Package?

Before we dive into the steps, let’s quickly explore why you might want to publish an NPM package:

  • Share Useful Code: Distribute utilities or components that others can benefit from.
  • Improve Your Skills: The process of creating and maintaining a package can deepen your understanding of JavaScript, Node.js, and software distribution.
  • Contribute to the Community: By sharing your work, you help improve the ecosystem for everyone.

Step 1: Create an NPM Account

What is NPM?

NPM (Node Package Manager) is the default package manager for Node.js. It’s an online repository for open-source Node.js projects, and it’s also a command-line tool for interacting with that repository.

How to Create an NPM Account

To publish packages, you'll need an account on NPM. Here's how to create one:

  1. Visit the NPM website: Go to npmjs.com.
  2. Sign Up: Click the "Sign Up" button in the top right corner of the page.
  3. Enter Your Details: Fill in your username, password, and email address. Make sure your username is unique and reflects your identity or brand.
  4. Verify Your Email: NPM will send you a verification email. Click the link in the email to verify your account.

Now that you have an NPM account, you’re ready to start publishing packages!

Step 2: Setting Up Your Project

Let’s create a package that ensures all required environment variables are set before your Node.js application starts. We’ll call this package env-config-check.

Initialize Your Project

First, create a new directory for your package and initialize it:

mkdir env-config-check
cd env-config-check
npm init -y
Enter fullscreen mode Exit fullscreen mode

This command creates a package.json file with default settings. The package.json file contains metadata about your package, such as its name, version, description, and more.

Customizing package.json

Edit the package.json file to reflect your package details:

{
  "name": "env-config-check",
  "version": "1.0.0",
  "description": "A simple utility to ensure all required environment variables are set.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "environment",
    "variables",
    "config",
    "npm",
    "utility"
  ],
  "author": "Dipak Ahirav",
  "license": "MIT"
}
Enter fullscreen mode Exit fullscreen mode
  • name: The unique name of your package.
  • version: Start with 1.0.0 for your initial release.
  • description: A short explanation of what your package does.
  • main: The entry point for your package (typically index.js).
  • license: MIT is a popular open-source license.

Step 3: Writing the Package Code

Create an index.js file, which will contain the core functionality of our package:

touch index.js
Enter fullscreen mode Exit fullscreen mode

Now, open index.js and add the following code:

function checkEnvVariables(requiredVars) {
    const missingVars = requiredVars.filter((variable) => !process.env[variable]);

    if (missingVars.length > 0) {
        throw new Error(`Missing required environment variables: ${missingVars.join(', ')}`);
    } else {
        console.log('All required environment variables are set.');
    }
}

module.exports = checkEnvVariables;
Enter fullscreen mode Exit fullscreen mode

How It Works

  • Input: The checkEnvVariables function takes an array of required environment variable names.
  • Check: It checks if each variable is set in process.env.
  • Output: If any are missing, it throws an error listing the missing variables. If all are set, it logs a success message.

Step 4: Testing Your Package Locally

Before publishing, it’s important to test your package locally to ensure everything works as expected.

Local Installation Using npm link

You can install your package locally using npm link. In the package directory, run:

npm link
Enter fullscreen mode Exit fullscreen mode

Next, create a new directory to test the package:

mkdir ../test-env-config-check
cd ../test-env-config-check
npm link env-config-check
Enter fullscreen mode Exit fullscreen mode

Now, create a simple test script:

echo "const checkEnvVariables = require('env-config-check'); const requiredEnvVars = ['DB_HOST', 'DB_USER', 'DB_PASS']; checkEnvVariables(requiredEnvVars);" > test.js
Enter fullscreen mode Exit fullscreen mode

Run the script with:

node test.js
Enter fullscreen mode Exit fullscreen mode

If you haven’t set the required environment variables, you should see an error message.

Image description

Set the variables and run the script again to see the success message.

Image description

Step 5: Preparing for Publication

Before publishing your package, make sure to:

  • Ignore Unnecessary Files: Create a .gitignore file to exclude files like node_modules:
  node_modules
  .DS_Store
Enter fullscreen mode Exit fullscreen mode
  • Create a README: Create a README.md file to document how to install and use your package.

Example README.md

# env-config-check

A simple utility to ensure all required environment variables are set.

## Installation


npm install env-config-check
Enter fullscreen mode Exit fullscreen mode

Usage

const checkEnvVariables = require('env-config-check');

const requiredEnvVars = ['DB_HOST', 'DB_USER', 'DB_PASS'];
checkEnvVariables(requiredEnvVars);
Enter fullscreen mode Exit fullscreen mode

This will check if DB_HOST, DB_USER, and DB_PASS are set in your environment. If any are missing, it will throw an error and prevent the application from starting.

Step 6: Publishing Your Package

With everything set up, you’re ready to publish your package to NPM.

Login to NPM

First, log in to your NPM account:

npm login
Enter fullscreen mode Exit fullscreen mode

You’ll be prompted for your username, password, and email associated with your NPM account.

Publish the Package

Once logged in, publish your package with:

npm publish
Enter fullscreen mode Exit fullscreen mode

If everything is configured correctly, your package will be published to the NPM registry, and you can see it live on npmjs.com.

Step 7: Updating Your Package

As you continue to develop your package, you may need to publish new versions. Update the version number in package.json following semantic versioning rules:

  • Patch: For bug fixes (e.g., 1.0.1)
  • Minor: For new features that don’t break backward compatibility (e.g., 1.1.0)
  • Major: For breaking changes (e.g., 2.0.0)

After updating the version number, publish the new version with:

npm publish
Enter fullscreen mode Exit fullscreen mode

Certainly! Here's how you can add your package link to the end of your blog post before the conclusion:


Try It Out

If you're interested in ensuring that all required environment variables are set before your Node.js application starts, check out the package I created: env-config-check.

You can easily install it via NPM:

npm install env-config-check
Enter fullscreen mode Exit fullscreen mode

For more details on how to use it, visit the NPM package page.


Conclusion

Creating and publishing an NPM package is a rewarding experience that allows you to share your work with the developer community. With env-config-check, you can ensure that your Node.js applications are correctly configured with all required environment variables, preventing common errors and improving the robustness of your applications.

Give it a try! Whether it’s your first package or your hundredth, each contribution helps make the NPM ecosystem stronger.

Happy coding!


Start Your JavaScript Journey

If you're new to JavaScript or want a refresher, visit my blog on BuyMeACoffee to get started with the basics.

👉 Introduction to JavaScript: Your First Steps in Coding

Series Index

Part Title Link
1 Server-Side Rendering (SSR) in React with Next.js Read
2 Ditch Passwords: Add Facial Recognition to Your Website with FACEIO Read
3 The Ultimate Git Command Cheatsheet Read
4 Top 12 JavaScript Resources for Learning and Mastery Read
5 Angular vs. React: A Comprehensive Comparison Read
6 Top 10 JavaScript Best Practices for Writing Clean Code Read
7 Top 20 JavaScript Tricks and Tips for Every Developer 🚀 Read
8 8 Exciting New JavaScript Concepts You Need to Know Read
9 Top 7 Tips for Managing State in JavaScript Applications Read
10 🔒 Essential Node.js Security Best Practices Read
11 10 Best Practices for Optimizing Angular Performance Read
12 Top 10 React Performance Optimization Techniques Read
13 Top 15 JavaScript Projects to Boost Your Portfolio Read
14 6 Repositories To Master Node.js Read
15 Best 6 Repositories To Master Next.js Read
16 Top 5 JavaScript Libraries for Building Interactive UI Read
17 Top 3 JavaScript Concepts Every Developer Should Know Read
18 20 Ways to Improve Node.js Performance at Scale Read
19 Boost Your Node.js App Performance with Compression Middleware Read
20 Understanding Dijkstra's Algorithm: A Step-by-Step Guide Read
21 Understanding NPM and NVM: Essential Tools for Node.js Development Read

Follow and Subscribe:

💖 💪 🙅 🚩
dipakahirav
Dipak Ahirav

Posted on September 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related