Skip to main content

Publish Own Public Npm Package

· 3 min read
Sivabharathy

Publishing your own public npm package involves several steps, from setting up your package to publishing it to the npm registry.

Here's a step-by-step guide to help you publish your own npm package:

1. Set Up Your Package

  1. Create a New Directory for Your Package:

    mkdir my-awesome-package
    cd my-awesome-package
  2. Initialize a New npm Package: Run the following command and answer the prompts to create a package.json file:

    npm init

    Alternatively, you can use npm init -y to automatically generate a package.json file with default values.

2. Develop Your Package

  1. Create Your Package Files: For example, create an index.js file:

    // index.js
    function helloWorld() {
    console.log('Hello, world!');
    }

    module.exports = helloWorld;
  2. Add any necessary dependencies: If your package depends on other npm packages, install them and save them to your package.json file:

    npm install some-package --save
  3. Write Documentation: Create a README.md file to document your package:

    # My Awesome Package

    This is my awesome package that says hello to the world.

    ## Installation

    ```bash
    npm install my-awesome-package

    Usage

    const helloWorld = require('my-awesome-package');
    helloWorld();

3. Test Your Package Locally

  1. Link Your Package Locally: Use npm link to link your package locally and test it in another project:

    npm link
  2. Test Your Package: Create another directory and link your package to test it:

    mkdir test-my-package
    cd test-my-package
    npm link my-awesome-package

    Then create a test file, e.g., test.js, and require your package:

    // test.js
    const helloWorld = require('my-awesome-package');
    helloWorld();

    Run your test file:

    node test.js

4. Publish Your Package

  1. Login to npm: If you don't have an npm account, create one at npmjs.com. Then, log in from the command line:

    npm login
  2. Publish Your Package: Ensure your package name is unique and not already taken on the npm registry. Then, publish your package:

    npm publish --access public

    If your package name is scoped (e.g., @username/my-awesome-package), you must include the --access public flag.

5. Update Your Package

  1. Make Changes: Make any necessary updates or changes to your package files.

  2. Update the Version: Update the version number in your package.json file according to semver (semantic versioning) guidelines:

    npm version patch  # or minor, or major
  3. Publish the Updated Package: Publish the updated version of your package:

    npm publish

Summary

By following these steps, you'll be able to create, test, and publish your own npm package. Make sure to follow best practices, such as writing good documentation and using semantic versioning, to make your package useful and maintainable for others.