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:
Table of Contents
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}!`;
}
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).
Pack the Package into a Tarball
Simply run:
npm pack
This generates a file like my-local-package-1.0.0.tgz.
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
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.jsorindex.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!
Example can be found http://github.com/pavelHudau/de-bouncer/.
