How to Build an NPM package and Test it before publishing

When developing an NPM package, you may want to test it locally before publishing it to the NPM registry. This guide will walk you through:

  1. Creating and building an NPM package.
  2. Publishing it to a local tarball file.
  3. Installing it from the file.
  4. Using it in a React application for testing.

Step 1: Create an NPM Package

  1. Create a new directory for your package
 mkdir my-local-package && cd my-local-package

2. Initialize the package. This generates a package.json file.

npm init -y

3. Create an index.js file as the entry point.

touch index.js

4. Write your package logic inside index.js. Example:

function greet(name) {
    return `Hello, ${name}!`;
}

module.exports = { greet };

5. Optionally, add TypeScript support.

npm install typescript --save-dev npx tsc --init

If using TypeScript, create index.ts.

export function greet(name: string): string {
    return `Hello, ${name}!`;
}

Step 2: Build the Package

If using TypeScript, compile it.

npx tsc

Ensure the package.json main field points to the correct file (index.js or dist/index.js for compiled TypeScript).

Step 3: Pack the Package into a Tarball

Simply run:

npm pack

This generates a file like my-local-package-1.0.0.tgz.

Step 4: Install the Package in a React Application

  1. Navigate to your React project:cd /path/to/react-app.
  2. Install the package from the tarball.
install /path/to/my-local-package/my-local-package-1.0.0.tgz

Step 5: Use the Package in React

Inside a React component import my-local-package and use it.

import React from "react";
import { greet } from "my-local-package";

const App = () => {
    return <h1>{greet("React Developer")}</h1>;
};

export default App;

Summary

  • Create and build the package (npm initindex.js or index.ts).
  • Pack it locally (npm pack).
  • Install in React (npm install path/to/package.tgz).
  • Import and use in components.

This method lets you efficiently test and debug your package before publishing it publicly!

Posts created 30

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top