DEV Community

Cover image for Create and publish your own npm package with example
Awais Abbas
Awais Abbas

Posted on • Updated on

Create and publish your own npm package with example

Creating the package

Create a new folder for the package. you can do that by typing in the terminal:

mkdir my_first_package

Then go inside the folder with terminal and initialize your package.json file like this:

cd my_first_package
npm init
Enter fullscreen mode Exit fullscreen mode

Fill in the required details about the package

You can skip some questions with Enter Key but try to provide the complete information.

Create a new file index.js in your directory and start writing your code.

In my case, I am creating a package to show console.log output in colors.

module.exports = function colorize(message, color) {
  switch (color) {
    case "red": {
      console.log("\x1b[31m%s\x1b[0m", `${message}`);
    case "green": {
      console.log("\x1b[32m%s\x1b[0m", `${message}`);
    case "blue": {
      console.log("\x1b[34m%s\x1b[0m", `${message}`);
    case "black": {
      console.log("\x1b[30m%\x1b[1m%s\x1b[0m", `${message}`);
    case "cyan": {
      console.log("\x1b[36m%s\x1b[0m", `${message}`);
    default: {
Enter fullscreen mode Exit fullscreen mode

Here is some information about the above code:

  • A function is created named colorize that gets the console message and color of your choice as a parameter.
  • In Node, colors references of text to command are written like \x1b[30m for black color etc.
  • There is a %s present in each console to reset the color back to normal for other log outputs. (\x1b[0m is being used to reset the color).

publishing the package

  • Name your package inside the package.json file.
  • Go to npmjs website and create an account.
  • Now, open up the terminal in your project's directory and write following commands:
npm login
npm publish
Enter fullscreen mode Exit fullscreen mode

If you encounter an error after the publish command, change your package name to something unique as it already exists on NPM.

Now, lets test our package.

Install the package with:  
npm install colorixer

and in index.js file, write:

const colorixer = require("colorixer");

colorixer("My first NPM package", "red");
colorixer("My first NPM package", "green");
Enter fullscreen mode Exit fullscreen mode



And you are done..Thanks for reading :)

Oldest comments (0)