DEV Community

nestedifsdotcom
nestedifsdotcom

Posted on

A comprehensive guide to publishing and maintaining javascript libraries part 1

As developers, we always have our favorite utilities that we carry around from project to project, usually a utils folder that contains snippets and scripts that we created or shamelessly stolen from StackOverflow.

We decided with my friend Youcef to create an npm package that includes those utilities, and after helping him watching him do that, I wanted to share and document the process in a series of articles.


Let's start with the definitions

what's a package ?:

A package is a file or directory that is described by a package.json file. A package must contain a package.json file in order to be published to the npm registry
-- source npm.com

What's npm?

npm stands for Node Package Manager. It's a :

  • repository of javascript packages that are primarily open-source and publicly available, but you can also create private ones
  • a command-line tool that manages project dependencies (installing packages, updating their version, or uninstalling them)

Before starting:

Make sure you have Node and npm installed.

Run the command npm --version on the Terminal; if you don't have a version, then you should install Node.

Creating a package.json file

Now that we know our vocabulary and have the necessary tools, let's create our first package it will be named yanis-array-utils, and it's an array utility library.

Create a folder and run npm init on the console.
Answer every question the command will ask you (give a different name to your package so you can publish it later as yanis-array-utils will be taken).

You will then have a file named package.json containing :

{
  "name": "the-name-of-your-package",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \\"Error: no test specified\\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Enter fullscreen mode Exit fullscreen mode

writing the code:

our first utility will be a function that returns the last element of an array, create a file named index.js

function last(array) {
  return array[array.length - 1];
}
// last(["first","last"]) will return "last"
module.exports = last
Enter fullscreen mode Exit fullscreen mode

That's it you now have an npm package.

Publishing the package:

Now that we have the code of the package let's share it with the world.

Go to npmjs.com/ and sign up.

In your command line run npm login then npm publish.

Using the package

you can create another project and install you package as a dependency

with npm install yanis-array-utils and use it as shown below

var last = require("yanis-array-utils");

console.log(last([1, 2, 5]));
Enter fullscreen mode Exit fullscreen mode

in the next article coming soon we will discuss tooling to support exporting to different modules format and then in the third part of this series we will discuss about CI/CD.

Discussion (0)