DEV Community

Cover image for A step-by-step guide on how to create and publish an npm package
Goodness Chukwudi
Goodness Chukwudi

Posted on • Edited on

A step-by-step guide on how to create and publish an npm package

If you are reading this, you are most likely either trying to publish a package to npm or just learning how to publish npm packages. No matter which one you fall into, I’m here to guide you through the steps to achieving that.

Introduction

NPM (Node Package Manager) is the world’s largest software registry. Open source developers from every continent use npm to share and borrow packages, and many organisations use npm to manage private development as well.

If you are a javascript developer, chances are that you are familiar with npm.
The scope of this article is publishing a package to npm and I will try to stick to that as much as possible. To seamlessly follow the steps outlined in this article and have a good understanding of the concepts used, you need to be familiar with javascript, node, git and npm. If you don’t have node installed, head over to the official website to download and install Node.js.

Step 1: Choose a name for your package.

To begin, you will need to choose a name for your package.
Note: Your package name must be unique. Using the exact or similar name of an existing package will return an error when publishing the package to npm. To ensure the uniquenesses of your package name, head over to npmjs.com and search for any existing packages with a similar name.
If there’s an exact match or a similar name, consider changing the name you will use for your package or publish your package as a scoped package. see “about scopes” for details.

The npm package we will be building for this article will be called boolean-converter, and aims to simplify the process of converting values to boolean in Node.js applications.
As developers working with Node.js, we often encounter scenarios where we need to interpret user input, API responses, or configuration values as boolean values. However, JavaScript's loose typing system can sometimes lead to unexpected results when dealing with truthy and falsy values.

Step 2: Create a project folder and make it a git repository.

Initialise git in your project folder. I will be using git and github (you can use a service of your choice) for version control. After creating a repository on github, in your computer’s terminal, navigate to the location you want to keep your project and clone the repository you just created using the command git clone <url of repository>.

git clone https://github.com/Goodness-Chukwudi/boolean-converter.git
Enter fullscreen mode Exit fullscreen mode

Step 3: Initialise NPM in your project.

From your terminal, navigate to the root of your project folder and initialise npm using the command below 👇

npm init
Enter fullscreen mode Exit fullscreen mode

You can initialise a scoped package by passing the scope flag to the command.

For an organisation-scoped package, replace my-org in the command below with the name of your organisation:

npm init --scope=@my-org
Enter fullscreen mode Exit fullscreen mode

For a user-scoped package, replace my-username in the command below with your username:

npm init --scope=@my-username
Enter fullscreen mode Exit fullscreen mode

You will get prompts requesting for

  • package name
  • version
  • description
  • entry point
  • test command
  • git repository
  • keywords
  • author
  • license

This will be used to create a package.json for your project. Provide the requested information or press enter to use the default for each prompt. See the image below👇

Terminal prompt for initialising npm

If successful, your project should have a package.json file with contents reflecting the information you provided. See the image below👇

package.json created

Step 4: Write the code for your package

Create the additional files: converter.js, index.js in your project.

Image description

Copy and paste the cold below inside converter.js


    /**
     * Converts a value to boolean
     * - "1", true, "true", "on", "yes", 1 converts to true while every other value converts to false
     * - value is not case sensitive
     * @param value the value (of type string|boolean|number) to be converted
     * @returns  a boolean
    */
    const convertToBoolean = (value) => {
        try {

            if(value == undefined) throw new Error("No value provided");

            if (typeof value === "string") value = value.toLowerCase();
            const allowedTruthValues = ["1", "true", "on", "yes", 1, true];

            if (allowedTruthValues.includes(value)) return true;
            return false;

        } catch (error) {
            throw error;
        }
    }

module.exports = {convertToBoolean};
Enter fullscreen mode Exit fullscreen mode

Copy and paste the code below inside index.js

const {convertToBoolean} = require("./converter")

module.exports = convertToBoolean
Enter fullscreen mode Exit fullscreen mode

Step 5: Test your package

If you followed the previous steps correctly, your package should be ready now. To test it before publishing, create a new project; we will call it test-project. Initialise npm like we did in step 3. You can use default values all through as this is just for test purposes. Install your package in the test project using the npm install command: npm install <full path to your project>.

npm install /users/username/folder-path/more-folder-path/boolean-converter
Enter fullscreen mode Exit fullscreen mode

This will create a node_modules folder with your package in it. Import the exported function from your package like every other npm package you have used and test to make sure everything works fine.

Testing our new package in another project

Step 6: Publishing your package to npm

Now that everything works as expected, we are going to publish the package to npm.

  1. Login to npm on your terminal. Head to npmjs.com and create an account if you don’t have any yet.
  2. From the root of your project on your terminal, run the command below
npm login
Enter fullscreen mode Exit fullscreen mode

You will get a prompt to login via your browser, press enter and complete the sign in process.

  1. Back to your terminal, use the command to publish your package to the public on npm registry.
npm publish
Enter fullscreen mode Exit fullscreen mode

If everything goes well, your package will be published to npm and your terminal should have a response similar to the screenshot below. You can go the npm website and search for the package with its name.

Publishing your package to npm

Publishing Scoped Packages

By default, scoped packages are published with private visibility. To publish a scoped package with public visibility, pass the access flag when publishing the package.--access public.

npm publish --access public
Enter fullscreen mode Exit fullscreen mode

Conclusion

If you followed along and everything worked fine, congratulations 🥂 , you have just published your first package to npm! 🥳

Providing tools that make common tasks easier for other developers is always valuable and a great way to contribute to the community. The magic becomes very obvious when you shared a more efficient way of getting things done.

Thank you for coming this far. The npm community await the amazing packages you will be publishing 🤝

Top comments (0)