Published on Monday, February 3, 2025
How to Create and Publish an NPM Package
Posted by

Video Tutorial
Introduction
In this article, we will create a simple NPM package called colorzila, which allows developers to log messages in different colors for better visibility in the console. This package will enhance readability by providing easy-to-use methods for printing messages in various colors. Once built, we will publish it to the NPM registry so it can be used by others.
Prerequisites
To follow along, ensure you have the following:
- Node.js installed on your machine.
- Basic Typescript knoledge.
Step 1: Set Up Your Project
1. Initialize the NPM Package
First, create a new directory and initialize an NPM package:
mkdir colorzilla && cd colorzilla
npm init -y
This generates a package.json file with default values.
2. Install Dependencies
Since we are using TypeScript and chalk, install them as dependencies:
npm install chalk
npm install --save-dev typescript @types/node
3. Configure TypeScript
Create a tsconfig.json file:
{
"compilerOptions": {
"strict": true,
"module": "ESNext",
"target": "ESNext",
"esModuleInterop": true,
"moduleResolution": "Bundler",
"declaration": true,
"outDir": "dist",
"declarationDir": "dist/types",
"baseUrl": "./",
},
"exclude": ["node_modules", "dist"],
"include": ["src"]
}
Step 2: Write Package Code
Create a src/index.ts file and add the following code:
import chalk from "chalk";
export default class ColorZilla {
info(message: string, end: string = "\n") {
process.stdout.write(chalk.blue(message) + end);
}
warn(message: string, end: string = "\n") {
process.stdout.write(chalk.yellow(message) + end);
}
error(message: string, end: string = "\n") {
process.stdout.write(chalk.red(message) + end);
}
success(message: string, end: string = "\n") {
process.stdout.write(chalk.green(message) + end);
}
secondary(message: string, end: string = "\n") {
process.stdout.write(chalk.gray(message) + end);
}
}
export const zilla = new ColorZilla();
Step 3: Build the Package
Run the TypeScript compiler:
npm run build
Make sure your package.json includes the correct build script and configurations:
"main": "./dist/index.js",
"types": "./dist/types/index.d.ts",
"scripts": {
"build": "tsc",
"prepare": "npm run build"
}
Step 4: Publish to NPM
1. Login to NPM
If you haven't already, log in to your NPM account:
npm login
2. Publish the Package
Run the following command to publish:
npm publish --access=public
Step 5: Use Your Package
To use the package in another project, install it with:
npm install colorzilla
And import it:
import { zilla } from "colorzilla";
color.success("Package published successfully!");
Useful Links
- 🖥️ Source Code: GitHub Repository
- 📦 NPM Package: View on NPM Registry
Conclusion
Creating and publishing an NPM package is a straightforward process. By following these steps, you can share your work with the developer community and contribute to open-source projects. Happy coding!