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:
- Creating and building an NPM package.
- Publishing it to a local tarball file.
- Installing it from the file.
- Using it in a React application for testing.
Step 1: Create an NPM Package
- 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
- Navigate to your React project:
cd /path/to/react-app
. - 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 init
,index.js
orindex.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!