How to Publish Your First npm Package: Creating Rainbow Highlight with Utilities

Kunal Singh

Sep 22, 2024

Publishing your first npm package can be an exciting and rewarding experience. In this blog post, we'll walk through the process of creating and publishing a simple yet fun package called "Rainbow Highlight" that adds colorful effects to text, along with some additional utilities.

Example of Usage

What We'll Build

Our "Rainbow Highlight" package will include several functions:

  1. A rainbow highlight effect for text
  2. A random color highlight effect
  3. A utility to strip highlights from text

We'll also demonstrate how to work with nested dependencies by incorporating lodash into our package.

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js (version 12 or later)
  • npm (usually comes with Node.js)
  • A text editor of your choice

Step 1: Set Up Your Project

  1. Create a new directory for your project:

    mkdir rainbow-highlight
    cd rainbow-highlight
  2. Initialize a new npm package:

    npm init -y
  3. Open the package.json file and modify it as needed. For example:

    {
    "name": "@yourusername/rainbow-highlight",
    "version": "1.0.0",
    "description": "A package to add colorful highlights to text, with additional utilities",
    "main": "index.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": ["rainbow", "highlight", "text", "color"],
    "author": "Your Name",
    "license": "MIT",
    "dependencies": {
    "lodash": "^4.17.21"
    }
    }

Step 2: Create Your Package

  1. First, let's install lodash as a dependency:

    npm install lodash
  2. Create an index.js file in your project root:

    const _ = require('lodash');

    function rainbowHighlight(text) {
    const rainbow = [
    'red',
    'orange',
    'yellow',
    'green',
    'blue',
    'indigo',
    'violet',
    ];
    let result = '';
    for (let i = 0; i < text.length; i++) {
    const color = rainbow[i % rainbow.length];
    result += `<span style="color: ${color};">${text[i]}</span>`;
    }
    return result;
    }

    function randomHighlight(text) {
    return _.map(text, (char) => {
    const randomColor = _.sample([
    'red',
    'orange',
    'yellow',
    'green',
    'blue',
    'indigo',
    'violet',
    ]);
    return `<span style="color: ${randomColor};">${char}</span>`;
    }).join('');
    }

    function stripHighlight(highlightedText) {
    return highlightedText.replace(/<span[^>]*>(.*?)<\/span>/g, '$1');
    }

    module.exports = {
    rainbowHighlight,
    randomHighlight,
    stripHighlight,
    };
  3. Create a README.md file to describe your package:

    # Rainbow Highlight

    A package to add colorful highlights to text, with additional utilities.

    ## Installation

    `npm install @yourusername/rainbow-highlight`

    ## Usage

    ````javascript
    const { rainbowHighlight, randomHighlight, stripHighlight } = require('@yourusername/rainbow-highlight');

    // Rainbow highlight
    const rainbowText = rainbowHighlight('Hello, World!');
    console.log(rainbowText);

    // Random highlight
    const randomText = randomHighlight('Random colors!');
    console.log(randomText);

    // Strip highlight
    const strippedText = stripHighlight(rainbowText);
    console.log(strippedText);```

    This package provides three main functions:

    - `rainbowHighlight`: Adds a rainbow color effect to the text.
    - `randomHighlight`: Adds random color highlights to each character.
    - `stripHighlight`: Removes highlight spans from the text.
    ````
    
    

Step 3: Test Your Package Locally

  1. Create a test.js file in your project:

    const {
    rainbowHighlight,
    randomHighlight,
    stripHighlight,
    } = require('./index');

    console.log('Rainbow Highlight:');
    console.log(rainbowHighlight('Hello, World!'));

    console.log('\nRandom Highlight:');
    console.log(randomHighlight('Random colors!'));

    const highlighted = rainbowHighlight('Strip me!');
    console.log('\nStrip Highlight:');
    console.log('Before:', highlighted);
    console.log('After:', stripHighlight(highlighted));
  2. Run the test file:

    node test.js

    You should see the output with different highlight effects and the stripped text.

Step 4: Publish Your Package

  1. Create an npm account if you haven't already: https://www.npmjs.com/signup

  2. Log in to your npm account in the terminal:

    npm login
  3. Publish your package:

    npm publish --access=public

    Note: If this is your first time publishing a scoped package, you'll need to use the --access=public flag.

Step 5: Use Your Published Package

Now that your package is published, you can install and use it in any project:

  1. Install the package:

    npm install @yourusername/rainbow-highlight
  2. Use it in your code:

    const {
    rainbowHighlight,
    randomHighlight,
    stripHighlight,
    } = require('@yourusername/rainbow-highlight');

    const rainbowText = rainbowHighlight('Hello, npm world!');
    console.log(rainbowText);

    const randomText = randomHighlight('Random npm colors!');
    console.log(randomText);

    const strippedText = stripHighlight(rainbowText);
    console.log(strippedText);

Conclusion

Congratulations! You've just created and published your first npm package with multiple utilities and a nested dependency. The "Rainbow Highlight" package demonstrates how to structure a more complex package, work with external libraries, and provide various functionalities to your users. As you continue to develop npm packages, you'll encounter more advanced topics like:

You can find the Package I had published here : https://www.npmjs.com/package/@singhkunal2050/rainbow-highlight with the source code at https://github.com/singhkunal2050/rainbowHighlight

  • Writing comprehensive tests
  • Setting up continuous integration
  • Implementing semantic versioning
  • Managing package updates and deprecations

Remember to maintain your package by addressing issues, adding new features, and updating dependencies as needed. Happy coding, and enjoy your journey in the world of npm package development!

Recommendations

Google Dorking: Unlocking Hidden Search Capabilities & Insights

#seach

,

#seo

,

#research

Explore 16 advanced Google Dorking techniques to uncover valuable data, security...

Aug 8, 2024

This One HTML Attribute Could Save Your Web App from a Security Nightmare

#web-security

,

#cdn

,

#web

Web security is a critical concern for developers, yet some of the most...

Jun 29, 2024

Are You Still Using Basic CSS? Here Are 7 Tricks to Get Ahead of the Curve

#css

Bored of the same old CSS? Unleash 7 hidden gems to take your designs to the...

Dec 27, 2023

Easiest way to store your logs in a file WITHOUT chaging the source file(node)

#productivity

Often, developers face challenges when dealing with a flood of logs in the...

Dec 21, 2023

Build Your Own Pinterest-Style Masonry Grid: A Step-by-Step Guide

#css

,

#web

,

#layout

Create a masonary grid layout with left to right content flow, supporting...

Dec 10, 2023

Using git diff and git apply to Share Local Changes with Peers

#git

,

#productivity

,

#software_engeneering

,

#dev

git diff and git apply are two powerful Git commands that can be used to share...

Nov 12, 2023

React Portals: Render Components Outside the current DOM Hierarchy

#react

,

#web

The createPortal API in React allows you to render child elements into a...

Jul 27, 2023

Cloning Made Easy: Try degit and Clone Directories within Repos.

#git

,

#productivit

Have you ever faced the dilemma of wanting just a small portion of a repository,...

Jul 19, 2023

Debugging Web Apps with Browser Dev Tools: 6 Amazing Tricks

#browser

,

#debugging

,

#web

Debugging web applications can be a challenging task, with errors like...

Jul 13, 2023

Controlled Versus Uncontrolled Components in React

#react

,

#forms

Understanding State Management Within Forms Comparing controlled and...

Nov 5, 2022

Format Numbers, Dates and Currencies with the Intl Object in Javascript

#javascript

,

#html

,

#web

Intl object can be used to format data into commonly used formats of dates,...

Sep 13, 2022

Image Masking on Hover Using CSS Clip Path and Javascript

#javscript

,

#css

,

#html

Image Masking can be used to add fancy hover highlight effects to images for...

Jul 23, 2022

Recreating CSS Tricks Fancy Grid Hover Effect

#html

,

#css

,

#UI

,

#recreation

CSS Trick had a simple yet cool grid layout which I found dope. So lets try to...

May 21, 2022

File Explorer Recursive React Component

#react

,

#javascript

,

#web

How to create a recursive folder Component using react.

Apr 16, 2022

Add Google Fonts to Your React & NextJS + TailwindCSS Project (Next 14)

#css

,

#tailwindcss

,

#react

,

#nextjs

,

#tailwind

,

#design

Use Google Fonts in Your TailwindCSS Projects

Apr 6, 2022

Event Delegation in Javascript

#javscript

,

#css

,

#html

,

#web

,

#performance

Handling multiple Events in Javascript with minimal CPU Usage

Mar 6, 2022

A Simple Web Accessibility Trick that you most probably missed!

#html

,

#css

,

#web-accessibility

,

#user-experience

Imagine that you cannot use the mouse and have to Navigate a Website with the...

Dec 23, 2021

Top Terminal Commands I Use For Productivity

#linux

,

#cli

,

#terminal

The whole point of development is solving problems. But very often we Developers...

Nov 3, 2021

CSS Logical Properties

#css

,

#html

CSS logical properties are properties which are used to design element on the...

Oct 5, 2021

Fluid Typography in CSS 💧

#css

,

#html

,

#typography

CSS Best Practices in Fluid Typography

Aug 15, 2021

CSS Units in a Nutshell 🐚

#css

,

#html

Are you still writing your css units in pixels and percentages? if you are then...

Aug 8, 2021

Master Markdown in 5minutes ⌚

#markdown

,

#documentation

Markdown is a lightweight markup language for creating formatted text using a...

Aug 1, 2021

What is JAMStack ✨

#jamstack

Jamstack stands for Javascript APIS and Markup and it is based on this idea of...

Jul 31, 2021

+

Check my latest Blog Post

How to Publish Your First npm Package: Creating Rainbow Highlight with Utilities

Read Now
Oh My Gawwdd!!!!!!!

Wow you have been viewing my site since 20 seconds!

+
+