How To Make Your Own NPM Package

mohammedtaysser

Mohammed Taysser

Posted on February 21, 2023

How To Make Your Own NPM Package

Before we start coding, there are things need to set up first:

Once sure every thing is good, we can get started building and publishing our NPM package.

Pick up a Name For Our Package

The hardest steps for us. As there are so many packages exist with the name we want one we think we have the best name possible, it could already be taken.

In order not to get too attached to a name, we can check if it is available on the NPM website or not, also trying https://remarkablemark.org/npm-package-name-checker/ and will tell us if it's available.

It is important that the package name is unique, especially if we plan to make it public.

Create a GitHub Repository

Next, create a repository for the package on GitHub. For this example, the name would be count.

It is important to choose an appropriate license for GitHub repository. Especially if you are going to make it public for other developers. Read more about GitHub docs on licensing a repository.

Login To NPM Account

To log in into NPM, use the command npm login. Then put the credentials you used to create the NPM account.

Initialize the Project

  • package name
  • version
  • description
  • git repository
  • keywords
  • license

Here an example

{
  "name": "count",
  "version": "1.0.0",
  "description": "An npm package for counting string char length",
  "main": "index.js",
  "keywords": [
    "js",
    "package",
    "count"
  ],
  "author": "Mohammed Taysser <mohamedtayser@gmail.com>",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Mohammed-Taysser/js-girlfriend.git"
  },
  "license": "MIT"
}
Enter fullscreen mode Exit fullscreen mode

Insure Updating the Version Correctly

By default, the initial package should be 1.0.0

The more our package downloaded the more bugs are updated will be needed, so update package is important. Let know how to update package version.

NPM uses a versioning system called Semantic Versioning (SemVer) and by default starting version is 1.0.0. For future updates, there are three types of version changes you can make, following Semantic Versioning standards. The three types of version changes are Major, Minor and Patch:

NPM version

  • Major version is when you make big changes to your package. An example is incompatible API changes.
  • Minor version is when you add functionality in a backwards compatible manner.
  • Patch version is when you make backwards compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

Creating the Module

The next steps are implementing our package core. In this example, I am implementing the count package.

In index.js or whichever file you want to set as your entry point, you would add the code that applies to your package.

The following code I placed in app.js:

function count(str = '') {
 return str.length;
}

module.exports = count;
Enter fullscreen mode Exit fullscreen mode

I used a simple function called count. It accepts only single parameter str is the string we want to know its length.

The most important part of the code above is exporting the created function using module.exports.

Initializing Git

Next, we have to initialize git for your package using the command:

git init
Enter fullscreen mode Exit fullscreen mode

Then stage the files that you changed using the command:

git add index.js
Enter fullscreen mode Exit fullscreen mode

Next, commit the changes to the code to your local repository:

git commit -m 'create `index.js`'
Enter fullscreen mode Exit fullscreen mode

Keeping files out of your Package

Use a .npmignore file to keep stuff out of your package. If there's no .npmignore file, but there is a .gitignore file, then NPM will ignore the stuff matched by the .gitignore file. If you want to include something that is excluded by your .gitignore file, you can create an empty .npmignore file to override it. Like git, NPM looks for .npmignore and .gitignore files in all subdirectories of your package, not only the root directory.

.npmignore files follow the same pattern rules as .gitignore files:

  • Blank lines or lines starting with # are ignored.
  • Standard glob patterns work.
  • You can end patterns with a forward slash / to specify a directory.
  • You can negate a pattern by starting it with an exclamation point !.
*
!lib/**/*
!bin/**/*
!README.md

.*.swp
._*
.DS_Store
.git
.hg
.npmrc
.lock-wscript
.svn
.wafpickle-*
config.gypi
CVS
npm-debug.log
Enter fullscreen mode Exit fullscreen mode

Write a README for the Package

This may seem like an arbitrary or unnecessary step, but it is actually really important. How many times have you installed a NPM package and then had to research online or look at examples of code to figure out how it works?

Writing a documented README for our package can be a large contributor to its success and wide usage.

For getting a better idea of what README looks like, you should check out popular NPM packages and their GitHub repositories.

In general, your README should include:

  • A description of your package and what it does.
  • How other users can install the package to use it in their project.
  • How to use the package in a project. Give examples of code explaining the usage. This is important!
  • How others can contribute to your package. If you expect other developers to contribute to this project, definitely include this in your README.
  • The license used by the package.

Publish to NPM

This will be the simplest step. All you have to do is run the follow code in your command line:

npm publish
Enter fullscreen mode Exit fullscreen mode

Updating an existing package

On the command line, in the package root directory, run the following commands:

note: The README file will only be updated on the package page when you publish a new version of your package. To update your README file:

npm version patch
npm publish
Enter fullscreen mode Exit fullscreen mode

then if every thing good, the package URL will https://npmjs.com/package/count

Make an CLI package

This is a small tutorial for creating your own CLI with node!

Getting Setup

Make sure that you have node and npm installed.

  • Create an empty directory.
  • Navigate to it in your terminal.
  • Run npm init which will ask you a couple of questions about the module that you are building such as name, versions, repository and author. You can use the default values for all of these by add -y flag the code will npm init -y, or enter some real data if you want.

Modifying package.json

We need to make a couple of changes to package.json to get started.

Prefer Global

It's a handy little property that tell NPM this module is intended to be used from the terminal. If a user tries to install the module locally, NPM will warn them that the package is intended for global installation.

{
  // ...
  "preferGlobal": "true",
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Directories Property

The directories' property is the one that makes this all work. By setting directories bin, we are telling NPM which file or directory contains the files to be added to the system PATH.

For this demo, we want users to be able to run hello from the terminal, so I need to create a new directory bin and create a file called hello in it. Then add the directories' property to package.json. Now, when our module is installed, the user will be able to access ./utils/hello from the terminal.

{
  ...
  "preferGlobal": "true",
  "bin": {
    "hello": "./utils/hello.js"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

Our "Main" File

Create a directory called utils in your module folder, and create hello.js inside of it. This file is going to contain all of our functionality. For now, it will display "Hello World!".

./utils/hello.js

#!/usr/bin/env node

console.log('Hello World!');
Enter fullscreen mode Exit fullscreen mode

Line one is a shebang. Line two is a require statement that requires our main file, which will be executed. We now have all the pieces in place to test our CLI.

Installing Our Module

Navigate to your project root directory, and execute:

npm install -g ./
Enter fullscreen mode Exit fullscreen mode

you will find a file with the name of command create at /usr/local/bin director on Linux

This is telling NPM to install the module location in the current directory as a global module, which is exactly what we want. -g is a flag that specifies that the module should be installed globally.

Now you can test the module by running

> hello
Hello World!
Enter fullscreen mode Exit fullscreen mode

If you need to uninstall it, just write the following command at terminal:

sudo npm uninstall -g hello
Enter fullscreen mode Exit fullscreen mode

Conclusion

Publishing a NPM package is actually simple, for this tutorial I used a simple example with more complex topics, you can make them as complex as you see fit. Don't forget to add test for the package

At end now you know how to create your own NPM package and publish it!
Good luck, have fun, and please feel free to share the NPM packages you create with me.

💖 💪 🙅 🚩
mohammedtaysser
Mohammed Taysser

Posted on February 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How To Make Your Own NPM Package
npm How To Make Your Own NPM Package

February 21, 2023