Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details

introduce

NPM is a package manager that provides JS developers with modules they can use in their projects to increase productivity. I use popular NPM packages such as Lodash and Date Functions to make my development workflow simpler. Using the NPM package is simple. You simply use the NPM installation package, import it, and invoke the module by calling functions.

However, not all available NPM packages will solve your problem. Sometimes you have to write your own code to solve a problem. But what if another developer runs into the same problem? You can save other developers countless hours by converting the code you just wrote into an NPM package. Therefore, this article explores how to create and publish your first NPM package so that other users can use your library!

Create NPM package

For demonstration purposes, let’s create and publish a math library that can:

  • Detecting odd and even numbers
  • To add, subtract, multiply, and divide a group of numbers.

Now that we understand the requirements, we can begin development.

Step 01- Prerequisites

Before we start developing the library, make sure you meet the following criteria

  1. Node.JS: Download and install the latest stable version of Node.JS.
  2. NPM: Make sure you have NPM installed on your machine (this is pre-installed with Node.js).
  3. NPM account: To distribute packages, you need an NPM account, so create your account on NPM to get started.

Step 02- Log in to your NPM account from a terminal

NPM requires an authentication token to access your NPM account from a terminal. From a terminal (or command prompt), run the command NPM login. Enter your NPM username and password to log in to your NPM account through the NPM CLI. If you have successfully logged in to your NPM account, you should see the following output.

Step 03- Initialize the new NPM package

With NPM successfully set up, we can create an empty NPM package for writing math libraries. To do this, locate the code folder and run the following command.

npm init
Copy the code

It will ask you to enter the name of the library. It is important to note that the library name must be unique. I’ll name my package “math-computers”. For other configurations, use the default values provided by the CLI. After that, it will generate a package. Json files containing metadata, third-party dependencies. Your package.json should look something like this.

{
  "name": "math-computers"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "repository": {
    "type": "git"."url": "git+https://github.com/lakindu2002/math-computer.git"
  },
  "author": "Lakindu Hewawasam"."license": "MIT"."bugs": {
    "url": "https://github.com/lakindu2002/math-computer/issues"
  },
  "homepage": "https://github.com/lakindu2002/math-computer#readme"
}
Copy the code

Step 04- Configuring ESLint

Installing ESLint is optional, but recommended when writing JavaScript code. ESLint helps detect potential bugs, vulnerabilities, and implement coding best practices to ensure that libraries perform well. Therefore, I personally use ESLint in all JavaScript projects. To add ESLint to a new NPM package, simply run the command NPM init@ESLint/config in your project’s root directory. Along the way, be sure to have the command install ESLint as a development dependency. In addition, the command will require you to set custom configurations. To do this, add the configuration shown below.

Be sure to use ESlint in your project

Select the type of JS Modules

Choose the framework for the project

Whether to use TS

Choose the platform

style

Choose Airbnb code style

Select the type of configuration fileWith these configuration options provided, the command will generate an ESLint configuration file (.eslintrc.yml) in the root directory with the configuration shown below.

env:
  browser: true
  es2021: true
  node: true
extends:
  - airbnb-base
parserOptions:
  ecmaVersion: latest
  sourceType: module
rules: {}
Copy the code

Step 05- Configure Babel

As modern JavaScript developers, we are familiar with using ECMA2015+. Therefore, we will use ECMA2015+ to write our NPM package. Therefore, to improve compatibility, we need to convert the code in the package to cross-browser compatible JavaScript. This is where Babel comes in. Adding Babel to an NPM project is simple. First, you need to install Babel as a development dependency in your project. To do this, run the following command.

npm install --save-dev @babel/cli @babel/core @babel/preset-env
Copy the code

Then create a file named “.babelrc “in the root directory to configure Babel. Add the code shown below to the newly created file to successfully configure Babel for your NPM project.

{
  "presets": [["@babel/env", {
      "targets": {
        "node": "current"}}]],"plugins": [
    "@babel/plugin-proposal-class-properties"."@babel/plugin-proposal-object-rest-spread"]}Copy the code

The configuration shown above will ensure that we can use expansion operators, classes, and import/export statements in our JavaScript files.

Step 06 – Write a mathematical function

After configuring development dependencies such as ESLint and Babel, we can start writing math libraries. First, let’s create a new directory called “lib” in the root directory. The “lib” directory specifies the library code. In the directory, create another directory named “modules”. In the Module directory, create two files:

  • Number-functions. js- Write functions that detect odd/even numbers
  • Math-functions. js- Writes addition, subtraction, division, and multiplication functions for a set of numbers.

After the directories and files have been created, the project structure should look like this.

. ├ ─ ─ package - lock. Json ├ ─ ─ package. The json ├ ─ ─ the eslintrc. Yml ├ ─ ─ the gitignore └ ─ ─ lib └ ─ ─ modules ├ ─ ─ math - functions provides. Js └ ─ ─ number-functions.jsCopy the code

Add library functions

When defining functions for an NPM package, always ensure that the functions are unit-testable. It ensures that your code is bug-free and reliable.

Add odd and even functions

With this in mind, let’s add functions to detect odd and even numbers in the file number-functions.js. The code is shown below.

// module to compute odd and even numbers

/**
 * This function will be used to determine if a number if an even number.
 * @param {Number} number: Number to be tested
 * @returns {Boolean} A boolean to indicate if the number is even or not.
 */
export const isEven = (number) = > number % 2= = =0;

/**
 * This function will be used to determine if a number if an odd number.
 * @param {Number} number: Number to be tested
 * @returns {Boolean} A boolean to indicate if the number is odd or not.
 */
export const isOdd = (number) = > number % 2! = =0;
Copy the code

The above snippet declares two functions that take a number and test for odd and even numbers. You may notice that both functions are exported. This is done to ensure that users who install the library can import the required functions into their projects.

Add mathematical functions

After that, we can open the math-functions.js file and add the functions needed to perform the math calculations. These functions are shown below.

/* eslint-disable arrow-body-style */
/* eslint-disable max-len */
// module to perform mathematical operations

const startingPoint = 0;

/**
 * This method will accept an array of numbers and compute the sum of all the numbers.
 * @param {number[]} numbers - An array of numbers to be summed.
 * @returns {number} - The sum of all the numbers in the array.
 */
export const add = (numbers) = > {
  return numbers.reduce(
    (total, currentNumber) = > total + currentNumber,
    startingPoint,
  );
};

/**
 * This method will accept an array of numbers and substract each number from the next number in the array.
 * @param {number[]} numbers - An array of numbers to be substracted.
 * @returns {number} - The value computed.
 */
export const subtract = (numbers) = > {
  return numbers.reduce(
    (total, currentNumber) = > total - currentNumber,
    startingPoint,
  );
};
/**
 * This method will accept an array of numbers and multiply each number from the next number in the array.
 * @param {number[]} numbers - An array of numbers to be multiplied.
 * @returns {number} - The multiplied answer.
 */
export const multiply = (numbers) = > {
  return numbers.reduce(
    (total, currentNumber) = > total * currentNumber,
    startingPoint + 1,); };/**
 * This method will accept an array of numbers and divide each number from the next number in the array.
 * @param {number[]} numbers - An array of numbers to be divided.
 * @returns {number} - The divided answer.
 */
export const divide = (numbers) = > {
  return numbers.reduce(
    (total, currentNumber) = > total / currentNumber,
    startingPoint + 1,); };Copy the code

You may have noticed that we added a JavaScript document for each function. This is done to provide a guide for the end user to understand the function.

Export the function in the entry file index.js

To ensure that users can import functions without diving into the library, we can add a file “index.js” to the root directory and import and export all functions from that file. In this way, the user can import all functions through the index.js file. As shown below.

const {
  add,
  divide,
  subtract,
  multiply,
} = require('./lib/modules/math-functions');

const { isEven, isOdd } = require('./lib/modules/number-functions');

module.exports.add = add;
module.exports.divide = divide;
module.exports.subtract = subtract;
module.exports.multiply = multiply;
module.exports.isEven = isEven;
module.exports.isOdd = isOdd;
Copy the code

Step 07 – Test the library

Use Babel to create distribution files

After adding the function to index.js, we can now generate distribution code for the library. This is done using Babel using the following command.

npx babel lib --out-dir dist
Copy the code

This creates a new directory called “Dist” in the root directory that contains the compiled JavaScript.

Link the package for local testing

After that, we can start testing the NPM library. We don’t need to release libraries to test it. NPM allows us to simulate this process in the local link library with the command NPM link. This creates a global version of the package that can be installed locally. To simulate the installation, run the command NPM link<< package-name >> to add the PACKAGE to the node_modules of your test project. First, let’s run NPM Link on the NPM project we created.

Test the package locally

After that, you can test the package locally. To do this, I’ll use the NPX Create React app my test app to generate a React application. In the React application, open a terminal and run the command NPM link<< package-name >> to link the locally simulated math PACKAGE to the React application for testing.

After that, we can start using the library in our React application. Its example usage is shown below.

import "./App.css";
import { add, divide, isEven, isOdd, multiply, subtract } from "math-computers";

const App = () = > {
  const numbers = [1.2.3.4.5.6.7.8.9.10];
  return (
    <div className="App">
      <div>Number List: {numbers.join(",")}</div>
      <div>Addition: {add(numbers)}</div>
      <div>Subtraction: {subtract(numbers)}</div>
      <div>Multiplication: {multiply(numbers)}</div>
      <div>Division: {divide(numbers)}</div>
      <div>Is 3 Odd: {isOdd(numbers) ? "True" : "False"}</div>
      <div>Is 3 Even: {isEven(numbers) ? "True" : "False"}</div>
    </div>
  );
};

export default App;
Copy the code

The code snippet above shows the libraries being imported and called.

The output is shown below.

Our library passed the test successfully! We can go ahead and publish the NPM package to the NPM repository so that other users can download and use the library.

Step 08- Publish the library to NPM

To publish the NPM library, open a terminal on the NPM project and run the command shown below.

npm publish
Copy the code

This will automatically publish your NPM package and make it available to external users.

You have successfully created and published your first NPM package. You can try this package out by running the following command.

npm i math-computers // install the package we published
Copy the code

conclusion

This article delves into how to create and distribute an NPM package that can be downloaded for use by third-party developers. Hopefully, this article encourages you to create your own NPM packages and contribute to the Node.js developer community!

Translation: enlear academy/publishing -…