The open blogging platform. Say no to algorithms and paywalls.

Top 10 NPM Packages

This is a short compilation of 10 npm relevant packages to build robust applications and backend logic, explained with text and code.

Developer — Imagined with AI

What is NPM?

NPM (Node Package Manager) is a package manager for the JavaScript programming language. It is used to install, update, and manage packages or modules for Node.js applications. NPM helps developers find, share, and reuse code with ease, and makes it easier to maintain the code over time.

Top 10 npm packages

  1. Express
  2. React
  3. Axios
  4. Lodash
  5. Moment
  6. Webpack
  7. Redux
  8. Babel
  9. Jest
  10. TypeScript

Express

Express is a web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js. Express is the backend component of the MEAN stack, together with the MongoDB database software and AngularJS frontend framework. Express provides a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy.

Why use express?

Express is a popular Node.js web application framework that provides a wide range of features for web and mobile applications. It is designed to make the development of web applications easier and more efficient. Express simplifies the development of complex web applications by providing robust routing, robust middleware support, and a template engine. It also supports several popular databases and provides a way to connect to them. Express also provides a wide range of features such as session management, caching, and more. It also supports a number of popular web development frameworks such as Angular and React.

Express Key Features

  1. Fast: Express is a fast and lightweight web framework built on top of Node.js that helps developers quickly create robust applications.
  2. Easy to Use: Express is easy to use and requires minimal configuration, making it a great choice for developers who want to get their applications up and running quickly.
  3. Flexible: Express provides a wide range of features, including routing, middleware, and templating. This makes it a great choice for developers who need more flexibility and control over th eir applications.
  4. Robust: Express is built on top of Node.js, which provides a powerful and reliable platform for building applications.
  5. Scalable: Express is designed to be highly scalable, so it can easily handle large amounts of traffic.

Express Code Example

Create a basic Express API

Install express run in the command line / terminal:

create an app.js file

npm install --save express
const express = require('express');  
const app = express();  
  
// set up the routes  
app.get('/api/users', (req, res) => {  
    const users = [  
        {id: 1, name: 'Mars'},  
        {id: 2, name: 'Zayn'},  
        {id: 3, name: 'Justin'}  
    ];  
    res.json(users);  
});  
  
const port = 5000;  
  
app.listen(port, () => console.log(`Server started on port ${port}`));

Run on the terminal:

node app.js

Check Express Official Documentation

React

React is a JavaScript library for building user interfaces. It is used for creating interactive front-end applications and helps developers create reusable UI components. React allows developers to create complex UIs from small, reusable components.

Why use React?

React is a popular JavaScript library used for building user interfaces. It is used for creating complex and interactive web and mobile applications that are fast and scalable. React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It allows developers to create large web applications that use data and can change over time without reloading the page. React also allows developers to create components that can be reused across different projects. React makes it easier to create interactive UIs and helps developers write code that is easier to maintain and understand.

React Key Features

  1. Component-Based: React is built around components, which are small, reusable pieces of code. Components can be combined to create complex UIs.
  2. Virtual DOM: React uses a virtual DOM (Document Object Model) to track and update changes to the UI. This allows React to update the UI quickly and efficiently.
  3. JSX: React uses a special syntax called JSX to describe how the UI should look. JSX makes it easy to create and update UIs.
  4. Lifecycle Methods: React provides built-in methods that allow developers to control the lifecycle of their components. This allows developers to create components that respond to user input and other events.
  5. React Native: React Native is a framework for creating native mobile apps using React. It allows developers to create apps for both Android and iOS.

React App.js basic template example

import React, { Component } from 'react';  
import logo from './logo.svg';  
import './App.css';  
  
class App extends Component {  
  render() {  
    return (  
      <div className="App">  
        <div className="header">  
          <img src={logo} className="logo" alt="logo" />  
          <h2>React</h2>  
        </div>  
        <p className="intro">  
          Welcome to react!  
        </p>  
      </div>  
    );  
  }  
}  
  
export default App;

Read React Official Documentation.

Axios

Axios is an open-source library that allows you to make HTTP requests from the browser or Node.js. It is a promise-based HTTP client for the browser and Node.js. It works by sending an HTTP request to a server and returning a response. Axios supports the Promise API, interceptor API, and can be used to make both asynchronous and synchronous requests. It is also compatible with a variety of other libraries, such as jQuery, React, and Angular. Axios is a great choice for making API calls, as it can be used to send and receive data in a variety of formats, including JSON, XML, and HTML.

Why use Axios?

Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js. It allows you to make HTTP requests from the browser and Node.js to help you easily integrate data into your application. It also supports a wide range of features including automatic transformation of JSON data, client side protection against cross-site request forgery, and automatic conversion to JSON. Axios also provides a number of additional features such as the ability to set custom headers, transform request and response data, and cancel requests.

Axios Key Features

  1. Promise-based: Axios is based on promises, which makes it easier to handle asynchronous operations.
  2. Interceptors: Axios provides a way to intercept requests and responses, which can be used to modify or reject requests before they are sent to the server.
  3. Automatic transformation of data: Axios automatically transforms the data into the format required by the server, making it easier to work with.
  4. Easy to use: Axios is easy to use and can be quickly integrated into any project.
  5. Support for multiple platforms: Axios supports multiple platforms, including Node.js, React, and Angular.
  6. Security: Axios provides built-in security features, such as CSRF protection, to keep your data safe.

Axios Code Example- Receive a JSON

Create an API app.js with this code:

const express = require('express');  
const app = express();  
  
// set up the routes  
app.get('/api/animals', (req, res) => {  
    const users = [  
        {id: 1, name: 'Cat'},  
        {id: 2, name: 'Dog'},  
    ];  
    res.json(users);  
});  
  
const port = 5000;  
  
app.listen(port, () => console.log(`Server started on port ${port}`));

Start the app, run on the terminal:

node app.js

Create a file called receiveJSON.js

const axios = require("axios");  
  
axios.get("http://localhost:5000/api/animals")  
  .then(response => {  
    const data = response.data;  
    console.log(data);  
  })  
  .catch(error => {  
    console.log(error);  
  });

Run in the terminal:

node .\receiveJSON.js

Your response:

Response JSON

Lodash

Lodash is an open-source JavaScript library that provides utility functions for common programming tasks. It is a popular library for developers who need to manipulate and traverse data structures with ease. It also provides support for functional programming, allowing developers to write code that is more concise and easier to debug. Lodash is available as an NPM package, which can be installed with the command npm install lodash. With this package, developers can access the full range of Lodash functions, including map, reduce, filter, and find. Additionally, Lodash provides a wide range of custom builds that can be used to reduce the size of the library and improve performance.

Why use Lodash?

Lodash is a JavaScript library that helps developers write more concise and maintainable code. It provides many utility functions for dealing with arrays, objects, strings, and other data types. It also provides methods for manipulating and iterating over collections, creating composite functions, and other tasks that are commonly encountered when writing JavaScript. Lodash can help developers write code faster and more efficiently, making it easier to maintain and debug.

Lodash Key Features

  1. Collection Methods: Lodash provides a wide range of collection methods, such as map, filter, reduce, forEach, and find. These methods can be used to iterate over arrays, objects, and strings, and to manipulate and combine data.
  2. Utility Functions: Lodash provides utility functions for common programming tasks like escaping, cloning, and checking for type. These functions are designed to make coding faster and easier.
  3. Chaining: Lodash provides a powerful method chaining feature that allows you to easily combine multiple functions together to create complex operations.
  4. Performance: Lodash is designed to be fast and efficient, and its collection methods are optimized for performance.
  5. Modularization: Lodash is modularized, meaning that you can choose which modules to include in your project, allowing you to reduce the size of your code and improve performance.

Lodash code example- Manipulating Arrays

const lodash = require("lodash");  
// Removing an item from an array:  
  
const array1 = [1, 2, 3, 4, 5];  
  
const updatedArray = lodash._.pull(array1, 3);  
console.log(updatedArray)  
  
// updatedArray = [1, 2, 4, 5]  
  
// Filtering an array:  
  
const array2 = [1, 2, 3, 4, 5];  
  
const filteredArray = lodash._.filter(array2, item => item > 3);  
console.log(filteredArray)  
// filteredArray = [4, 5]  
  
// Sorting an array:  
  
const array3 = [1, 5, 2, 4, 3];  
  
const sortedArray = lodash._.sortBy(array3);  
console.log(sortedArray)  
// sortedArray = [1, 2, 3, 4, 5]

Moment NPM Package

Moment.js is a popular JavaScript library for parsing, validating, manipulating, and formatting dates and times. It is a lightweight and powerful library that simplifies working with dates and times in JavaScript. Moment.js provides a number of useful functions for working with dates, such as formatting, parsing, and manipulating dates and times. It also provides a number of helpful utility functions for working with times, such as calculating the difference between two times, or calculating the difference between two dates. Moment.js is also compatible with a wide range of browsers and platforms, making it a great choice for developers who need to work with dates and times across multiple platforms.

Why use Moment?

Moment is a JavaScript library that helps developers work with dates and times. It makes it easier to parse, validate, manipulate, and format dates and times. It also provides a unified interface for working with dates and times across different timezones and languages. Moment can be used to simplify date and time calculations, format dates and times, and parse and display dates and times in different formats.

Moment Key Features

The Moment NPM Package is a lightweight JavaScript library that helps developers to parse, validate, manipulate, and display dates and times. It is designed to work both in the browser and in Node.js. Its key features include:

  • Parse, validate, manipulate, and display dates and times in a user-friendly way.
  • Supports i18n (internationalization) and l10n (localization) for displaying dates and times in different formats.
  • Provides a simple API for working with dates and times.
  • Supports a variety of date and time formats, including ISO 8601, RFC 2822, and Unix Timestamps.
  • Allows developers to add custom date and time formats.
  • Supports relative time formatting.
  • Supports calendar and duration formatting.
  • Provides a plugin system for extending the library’s features.

Moment example code — Calculate time between two dates

const moment = require('moment');  
const startDate = moment('2020-03-02');  
const endDate = moment('2020-03-05');  
  
const duration = moment.duration(endDate.diff(startDate));  
  
console.log(duration.asYears());  
console.log(duration.asDays());  
console.log(duration.asMinutes());  
console.log(duration.asSeconds());

Output:

Output Moment Script

Webpack

Webpack is a module bundler for JavaScript applications. It takes modules with dependencies and generates static assets representing those modules. Webpack takes modules with dependencies and generates static assets representing those modules. It can also be used to bundle CSS, images, and other assets.

NPM (Node Package Manager) is a package manager for JavaScript. It is used to install, uninstall, and manage Node.js packages. It is the default package manager for Node.js, and it is used to install, update, and manage Node.js packages.

Webpack and NPM work together to help developers create and maintain applications. Webpack bundles JavaScript modules into static assets, while NPM helps manage the packages used in the application. NPM can be used to install, update, and uninstall packages, while Webpack can be used to bundle those packages into static assets. Together, they provide developers with a powerful tool for creating and maintaining applications.

Why use Webpack?

Webpack is a powerful and popular tool used to bundle JavaScript modules and other assets for use in modern web applications. It can be used to optimize code, reduce the size of bundles, and help manage complex build processes. Webpack also allows developers to use modern JavaScript features, including ES2015 modules, and compile them into a single bundle for use in the browser. Additionally, Webpack can be used to process and bundle stylesheets, images, and other assets, making it a great choice for modern web applications.

Webpack Key Features

  1. Code splitting: Webpack allows developers to split their code into multiple bundles which can then be loaded on demand or in parallel. This helps reduce the initial load time of an application.
  2. Hot Module Replacement (HMR): Webpack provides an HMR API which allows developers to replace modules at runtime without the need for a full page refresh.
  3. Loaders: Webpack provides a wide range of loaders which allow developers to pre-process files before they are added to a bundle. This allows developers to work with a wide range of languages, transpilers and pre-processors.
  4. Plugins: Webpack also provides a wide range of plugins which can be used to extend the core functionality of the bundler. This allows developers to customize the build process to suit their needs.

Redux

Redux is a state container for JavaScript applications. It is used for managing the state of an application in a predictable and efficient manner. Redux works by having a single source of truth for the application’s state, which is stored in a “store”. This store is then updated using “reducers” which take the current state and an action, and return a new state. This new state is then passed to the view layer, which updates the UI accordingly. Redux also provides tools for debugging, such as the Redux DevTools, which allow developers to view the current state of the application.

Why use Redux?

Redux helps to keep the state of an application organized, making it easier to debug, maintain, and test. It also helps to ensure that the state of an application is consistent across different components and users.

Redux Key Features

  1. Single source of truth: The state of your whole application is stored in an object tree within a single store.
  2. State is read-only: The only way to change the state is to emit an action, an object describing what happened.
  3. Changes are made with pure functions: To specify how the state tree is transformed by actions, you write pure reducers.

Babel

Babel is an open-source JavaScript compiler that enables developers to write JavaScript code that can be transpiled (converted) into code that can run in any JavaScript environment, including older browsers and server-side environments.

It can also be used to transform code written in other languages into JavaScript. Babel is available as an NPM (Node Package Manager) package, allowing developers to install and use it in their projects. The package includes a CLI (Command Line Interface) that can be used to transpile code, as well as a set of plugins and presets that can be used to customize the transpilation process.

Why use Babel?

Babel is a JavaScript compiler that allows developers to write code in the latest version of JavaScript and then have it compiled into a version that is supported by most browsers. This makes it easier to write modern JavaScript code without having to worry about compatibility issues. Additionally, Babel can be used to transpile code from other languages such as TypeScript, CoffeeScript, and Flow into JavaScript.

Babel Key Features

— Compiles ES2015+ down to ES5 — Supports the JSX syntax — Allows you to use the latest version of JavaScript — Uses a plugin system to add additional features — Includes a built-in development server with hot reloading — Provides a CLI utility to compile files from the command line — Includes a polyfill to support older browsers

Jest

Jest is a JavaScript testing framework created by Facebook. It is used to test JavaScript code and is designed to ensure that the code works as expected. It is an open source project and can be used to test React, Angular, Vue, Node, and other JavaScript libraries and frameworks. Jest provides a simple and intuitive API for writing tests, and it has a powerful assertion library for verifying the results of tests. It also includes a mocking library for mocking functions and objects, and it has built-in support for code coverage reporting. Additionally, Jest is compatible with most popular Continuous Integration (CI) tools, such as Travis CI and CircleCI.

Why use Jest?

Jest is a popular JavaScript testing library that is used to test code written in JavaScript. It is used to test all types of JavaScript code, including React, Node, and Angular. It is also used to test applications written in TypeScript. Jest is easy to use and provides a powerful testing framework with features such as mocking, code coverage, and snapshot testing. It is also fast, reliable, and open-source.

Jest — Key Features

  1. Automated Mock Creation: Jest automatically mocks JavaScript modules when it detects a mock subdirectory in the project root. This allows for easy setup and configuration of mocks for modules without the need for manual intervention.
  2. Snapshot Testing: Jest has the ability to take snapshots of React trees or other serializable values to simplify testing and to provide a way to ensure the UI does not change unexpectedly.
  3. Built-in Assertion Library: Jest includes an assertion library that is automatically included in all tests. This library provides a simple and straightforward way to test JavaScript code without the need for external assertion libraries.
  4. Watch Mode: Jest can be configured to watch files for changes and rerun tests automatically when a file is changed. This is useful for quickly iterating on tests and making sure that the tests are up-to-date.
  5. Parallel Testing: Jest can be configured to run tests in parallel, which can significantly reduce the amount of time it takes to run tests. This is especially useful for larger projects with many tests.
  6. Coverage Reporting: Jest has the ability to generate coverage reports that show how much of the codebase is covered by tests. This can be used to identify areas of the codebase that need more tests or to ensure that the tests are covering the code adequately.

TypeScript

TypeScript is a programming language developed by Microsoft that is a superset of JavaScript. It adds optional static typing, classes, and modules to JavaScript, to help developers write more organized, efficient, and scalable code. TypeScript is compiled into JavaScript, so it can be used in any environment that JavaScript runs in.

Why use TypeScript?

TypeScript is a strongly typed, object-oriented programming language that is a superset of JavaScript. It provides developers with additional features such as static typing, classes, interfaces, and modules that can be used to create more robust, maintainable, and scalable applications. With TypeScript, developers can create applications that are easier to debug, refactor, and maintain. Additionally, TypeScript provides support for the latest JavaScript features, including ECMAScript 6, which makes it easier for developers to use the latest JavaScript features in their applications.

TypeScript — Key Features

  1. Type Annotations: TypeScript adds optional types to JavaScript that can be used to define variables, functions, and properties. This allows developers to better document and understand their code, as well as catch errors early on in the development process.
  2. Classes and Interfaces: TypeScript introduces the concept of classes, interfaces, and modules, which allow for greater code organization and readability.
  3. Compile-time Type Checking: TypeScript’s compiler will check your code for type errors at compile-time, allowing you to catch errors much earlier in the development process.
  4. ES6/ES7 Support: TypeScript supports the latest versions of JavaScript, including ES6 and ES7, allowing developers to use the latest language features.
  5. Tooling Support: TypeScript has great tooling support, including IDEs and editors, which makes it easier to develop with TypeScript.

Conclusion

Hope you find this article helpful as an overview of JavaScript powerful Node Package Manager. At the time of writing this article there are more than 1.3 million packages available at the main npm registry.

So knowledge of more relevant packages for developing specific features is important to succeed as JavaScript developer.




Continue Learning