Skip to content

Javascript

Information

If you are a web developer or a web enthusiast, you have probably heard of JavaScript! Or why else would you be here?. But what exactly is JavaScript?!, and why is it so dominant in web and application development?! Suppose you had the ability to create a web page, game or application that can change its appearance based on the time of day, the weather, or the user’s preferences. Think of how amazing it would be if you could add interactive elements such as buttons, forms, sliders, or quizzes to your web page without reloading it. Envision what it would be like to create stunning animations and graphics that make your web page stand out from the crowd. JavaScript is the one true king of the web, and it can work wonders with minimal code. Whether you want to create dynamic websites, interactive games, or powerful apps, JavaScript can make it happen. In this eye-opening document, we will give you a brief overview of JavaScript, its history, its features, and its applications. You will learn how JavaScript can make your web pages more dynamic and interactive, and how it can help you create stunning web applications that run in the browser. Prepare to unleash the power of JavaScript with this mdx documentation. You will learn everything you need to create dynamic and interactive web applications from scratch. Whether you are a beginner or a seasoned coder, this guide will take your skills to the next level.

Design

Would you like to learn how to write JavaScript code that is clean, clear, and consistent? Do you have a passion and desire to solve common problems in software design with ease and elegance? How would you like to master JavaScript and dazzle your peers and clients with your brilliant code? Did any of these questions resonate with you? If that rings a bell, you’ve hit the jackpot by coming to this resource! We will introduce you to the power and beauty of design patterns and how they can enhance and transform your work. Design patterns are reusable solutions that help you organize your code, simplify your logic, and communicate your intent. They are like recipes or templates that you can use to cook up delicious and nutritious code for your app. You will learn about some of the most common and useful design patterns in JavaScript, such as creational, structural, and behavioral patterns. You will also see some real-world examples of how these patterns can make your code more efficient, maintainable, and readable. By the end of this documentation, you will have a better understanding of design within JavaScript and how to apply it to your own projects. And as a bonus, KBVE will also share with you some of the best resources and tools to learn more about design patterns and practice them in your own code. So do not miss this opportunity to become a better JavaScript developer! Read on, discover the secrets of design patterns and experience the magic and potential of design patterns for yourself below.

Design Patterns

The theory of javascript design patterns can be classified into three major categories, namely creational, structural, and behavioral patterns. These classes differ from each other in various distinctions and aspects, such as how complex and elaborate the pattern is, the level of detail it offers to the developer and end-user, and the scope of its impact on the system being designed. Understanding these divisions can help developers choose the most suitable design pattern for their specific needs and goals within the application, interface or project.

Creational Design Patterns

Creational patterns enable a more adaptable and reusable code by offering a flexible framework for creating objects or classes. In this nature, the design shields the users from the complex construction process and streamline their interaction with the classes. Thus, the pattern controls the user-class interaction and save the developers from handling complex construction.

Factories, builders and singletons are the three core concepts of creational design pattern.

Abstract Factory Design Pattern

The Abstract Factory design pattern is a fundamental component of creational patterns that offers a way to encapsulate a group of individual factories with a common theme without specifying their concrete classes. This pattern is especially useful in systems that need to be independent of how their products are created, composed, and represented.

Purpose

The Abstract Factory pattern is designed to provide an interface for creating families of related or dependent objects. It allows a system to be independent of how its products are created, composed, or represented. This pattern is beneficial for systems that require the flexibility to deal with diverse objects sharing a thematic or functional link.

Implementation

The pattern involves several key components:

  • Abstract Factory: An interface that declares a set of methods for creating each of the abstract products.
  • Concrete Factory: Implements the abstract factory methods to create concrete products.
  • Abstract Product: Declares an interface for a type of product object.
  • Concrete Product: Implements the abstract product interface; objects created through a factory.
  • Client: Uses only interfaces declared by Abstract Factory and Abstract Product classes.

Scenario and Example

Consider a scenario where a software developer is tasked with creating a cross-platform application that needs to generate various user interface components like buttons, modals, forms, text boxes, and menus. By employing the Abstract Factory, the developer can define an interface for creating these UI elements which can then be implemented by different concrete factories for specific platforms (e.g., Windows, Android, iOS, MacOS, Linux).

Advantages

  • Flexibility: Allows the creation of sets of related products without specifying their concrete classes.
  • Scalability: Supports adding new kinds of products without disturbing existing client code.

Asbtract Factory Tutorial

  1. Define Abstract Factory Interface:

    Create an interface for the abstract factory. This interface will declare methods for creating each type of vehicle.

    
    class VehicleFactory {
    createCar() {}
    createBoat() {}
    }
    
    
  2. Create Concrete Factory Classes:

    Implement concrete factories that extend the abstract factory interface. Each factory will provide specific implementations for creating vehicles suitable for its environment.

    
        class LandVehicleFactory extends VehicleFactory {
            createCar() {
                return new Sedan();
            }
            createBoat() {
                return new Canoe(); // Just for demonstration, usually wouldn't be in LandVehicleFactory
            }
        }
    
        class WaterVehicleFactory extends VehicleFactory {
            createCar() {
                return new AmphibiousCar();
            }
            createBoat() {
                return new SpeedBoat();
            }
        }
    
    
    
  3. Define Abstract Product Interfaces:

    Define interfaces for each type of vehicle. These interfaces will include methods that all concrete vehicle products must implement.

    
    class Car {
        drive() {}
    }
    
    class Boat {
        sail() {}
    }
    
    
  4. Create Concrete Product Classes:

    Implement the product interfaces with concrete classes. These classes will define the specific characteristics of vehicles.

    
    class Sedan extends Car {
        drive() {
            console.log("Driving a sedan on roads");
        }
    }
    
    class Canoe extends Boat {
        sail() {
            console.log("Canoeing in calm waters");
        }
    }
    
    class AmphibiousCar extends Car {
        drive() {
            console.log("Driving an amphibious car on land and water");
        }
    }
    
    class SpeedBoat extends Boat {
        sail() {
            console.log("Speeding through water with a speedboat");
        }
    }
    
    
  5. Implement Client Code:

    Write the client code that utilizes the factories to create objects. The client should interact with these objects through their abstract interfaces.

    
    function testVehicle(factory) {
        const car = factory.createCar();
        car.drive();
        const boat = factory.createBoat();
        boat.sail();
    }
    
    const landFactory = new LandVehicleFactory();
    const waterFactory = new WaterVehicleFactory();
    
    testVehicle(landFactory);
    testVehicle(waterFactory);
    
    
  6. Test Your Implementation: Test the implementation to confirm that the correct vehicle types are being created and that they behave as intended, ensuring that the factory logic correctly encapsulates the creation details.

    This example illustrates how the Abstract Factory pattern can be applied to a vehicle manufacturing scenario, facilitating the creation of products that are tailored for specific environmental conditions without exposing the creation logic to the client code.


Builder

The Builder design pattern is a creational pattern that separates the construction of a complex object from its representation. By doing so, the same construction process can create different representations. This pattern is particularly useful when an object must be created in multiple steps or with various configurations.

Purpose

The primary purpose of the Builder pattern is to allow the step-by-step construction of complex objects and to simplify the code by separating the construction of these objects from their class. This pattern is ideal for situations where multiple versions of an object need to be created, and a clear method of doing so is necessary.

Implementation

The Builder pattern involves three key components:

  • Builder: This is an interface that defines all the steps required to build a part of the object.
  • Concrete Builder: Implements the builder interface and provides an implementation for those steps. It keeps track of the representation it creates and provides an interface for retrieving the product.
  • Director: Takes a builder instance and executes the necessary operations to produce a part of the object. The director knows which builder to use to get the desired object configuration.
  • Product: The complex object that is being built. The builder returns the product as a final step.

Advantages

  • Flexibility in Object Construction: Builders can construct objects step-by-step, vary the process based on the situation, and easily create different types of objects with the same construction code.
  • Encapsulation and Construction Control: The product’s internal representation is protected from the client until it is fully built. This encapsulation helps in maintaining the integrity of the constructed object.

When to Use

Use the Builder pattern when constructing a complex object with multiple optional and mandatory fields, or when an object must be assembled in multiple steps or configurations. It is also beneficial when you need a clear way to create different representations of the same class.

The Builder design pattern greatly enhances the modularity and readability of code, making it easier to write, maintain, and modify code where complex objects are involved.

Singleton

Singleton is a design pattern that falls under the creational category, which concerns itself with the best ways to instantiate objects. The core principle of the Singleton pattern is to ensure that a class has only one instance and to provide a global point of access to that instance. This pattern is particularly useful when exactly one object is needed to coordinate actions across the system.

The implementation of the Singleton pattern involves creating a class with a method that creates a new instance of the class if one does not already exist. If an instance already exists, it simply returns a reference to that object. To ensure that no other instances can be created, the constructor of the class is made private.

A typical use of the Singleton pattern is in managing a connection to a database or the settings in a configuration file. By using a Singleton, multiple parts of an application can share a single connection or configuration object without the need to pass around a reference throughout the program.

Singletons also help in conserving system resources, as they avoid constant creation and destruction of objects when a single object is sufficient. However, care must be taken with Singletons as they can introduce global state into an application, which can complicate testing and limit flexibility.

Overall, the Singleton pattern provides an elegant solution to ensuring a class has only one instance while offering a global point of access, thereby contributing to a cleaner and more manageable codebase.

Structural Design Patterns

Structural Design Patterns, SDP, are concerned with how objects and classes are composed to form larger structures.

They help to ensure that changes in one part of the system do not affect other parts.

Structural Design Patterns (SDP) play a pivotal role in software architecture by focusing on how objects and classes can be assembled into larger and more complex structures. These patterns aim to improve the design of a system by ensuring that the individual components can be combined in such a way that maintains both the individual integrity and the overall flexibility of the system.

SDP are instrumental in simplifying the structure by identifying the relationships between the entities. This identification helps in facilitating better organization of the system components, making it easier to understand, maintain, and scale. Additionally, these patterns help in ensuring that changes in one part of a system do not adversely affect other parts, which is crucial for the stability and robustness of the system.

By using these patterns, developers can create systems that are more modular and easier to manage, with well-defined interconnections between different components. Structural Design Patterns are essential for developers looking to build complex systems that require high levels of inter-component flexibility and maintainability.

Behavioral Design Patterns

Behavioral Design Patterns, BDP, define the communication between objects and how they interact with each other.

They help to ensure that objects work together in a coordinated manner.

    Behavioral Design Patterns (BDP) are crucial in the realm of software engineering, specifically focusing on improving the communication and interaction between objects in software systems. These patterns facilitate a smooth and efficient orchestration of behaviors among different objects, enabling them to perform their tasks in a coordinated and cooperative manner.

    These patterns are distinguished by their ability to distribute responsibilities among objects, which helps in reducing the complexity of the code and increasing its flexibility. By defining standard communication protocols, BDP ensure that the objects can interact without being tightly coupled, thereby enhancing modularity and facilitating future scalability and maintenance.

Examples of Behavioral Design Patterns include the Observer pattern, which allows objects to be notified of changes in other objects without creating a direct dependency; the Strategy pattern, which enables the selection of an algorithm’s behavior at runtime; and the State pattern, which allows an object to alter its behavior when its internal state changes.

    Implementing these patterns can lead to more dynamic and adaptable software, with components that are easier to understand, extend, or modify. Behavioral Design Patterns are indispensable for developers aiming to create interactive systems that are robust, scalable, and maintainable.


NodeJS

Node.js is a dynamic open-source runtime environment that brings JavaScript to the server side. Running on Google’s powerful V8 engine, it allows for both client and server-side application development using JavaScript. This is streamlined by npm, Node’s package manager, which hosts a vast repository of open-source libraries.

Often simply called “Node,” this environment was created to extend the efficient and event-driven qualities of JavaScript beyond web browsers. Node.js executes code using the V8 engine and is designed around an event-driven, non-blocking I/O model that not only boosts efficiency but is also perfect for scalable and real-time applications.

Node.js really shines by bridging the gap between front-end and back-end development, allowing developers to work with JavaScript across the board. This unity simplifies the development process and makes it more cohesive. Npm, Node’s package manager, plays a critical role by offering a wealth of open-source libraries that help developers quickly construct applications using modules shared by the community.

Node’s utility extends beyond typical web applications. It’s also used for developing command-line tools, chat applications, data-intensive real-time applications, and even for IoT devices. With its continuous development, strong community support, and adaptability to modern development needs, Node.js is a prime example of how server-side development has transformed in the modern era.

NodeJS Installation

Getting Started with Node.js Installation

Node.js is a powerful JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to write server-side applications in JavaScript. Installing Node.js is the first step towards using its rich ecosystem for developing web applications, REST APIs, and more.

Choosing the Right NodeJS Version

When planning to install Node.js, you have two main versions to consider:

  • LTS (Long-Term Support): This version is best for most users, especially in production environments, because it receives security and stability updates for an extended period.
  • Current: This version includes the latest features and updates. It’s suitable for developers who want to experiment with the newest capabilities of Node.js but might be less stable than the LTS version.

Using the LTS version ensures that you are working on a stable and well-supported platform, which is crucial for application stability and security.

Version Management

For managing multiple Node.js versions on a single machine, tools like nvm (Node Version Manager) for Unix-based systems or nvm-windows for Windows are highly recommended. These tools allow you to switch between different Node.js versions easily, which is helpful when working on multiple projects that require different versions.

Here is how you can install nvm:

# Install nvm and use it to install Node.js
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
nvm install node # "node" is an alias for the latest version
nvm use node

Ubuntu NodeJS Install

  1. For Debian-based distributions like Ubuntu, Node.js can be installed via the package manager. First, update your package repository:

    sudo apt-get update
    
  2. Install Node.js:

    sudo apt-get install nodejs
    sudo apt-get install npm
    
  3. Verify the installation by typing node -v and npm -v in the terminal.

Windows NodeJS Install

  1. Download the Windows installer from the official Node.js website: Node.js

  2. Run the installer (.msi) and follow the prompts to set up Node.js.

    Make sure to include the installation of npm (Node Package Manager), which comes bundled with Node.js.

  3. After installation, open the Command Prompt and type node -v to verify the installation.

    The version of Node.js should appear.

MacOS NodeJS Install

Option A: Brew Install NVM

brew install nvm

Option B: Brew Install Node (directly)

  1. You can install Node.js via the package from the Node.js website or use a package manager like Homebrew.

    To install with Homebrew:

    brew install node
    
  2. Once installed, open a terminal window and type node -v to check the installed version.


Bun

    Bun is a modern JavaScript and TypeScript runtime, similar to Node.js but designed to be significantly faster and more efficient. It integrates several functionalities such as bundling, transpiling, package management, and running JavaScript/TypeScript code. Bun is optimized for performance and aims to streamline the development process by combining multiple tools into one comprehensive package.

Key Highlights of Bun

Essential Features of Bun.

Bundling

Bun comes with a built-in bundler that efficiently packages your JavaScript or TypeScript files into a single file, ready for production. This helps in reducing load times and improving performance by minimizing the number of server requests.

Transpiling

It supports on-the-fly transpilation of modern JavaScript and TypeScript, allowing developers to use the latest language features without worrying about browser compatibility.

Package Management

Bun includes a fast package manager that can install dependencies up to three times faster than npm or Yarn. It directly handles dependency resolution and integrates seamlessly with the broader npm ecosystem.

Task Running

Beyond running scripts, Bun can be used as a task runner, automating routine development tasks like minification, compilation, and testing, much like Gulp or Grunt.

Speed and Performance

One of the standout features of Bun is its focus on performance. Built on Zig, a language known for its speed and low overhead, Bun is engineered to execute JavaScript code very quickly, competing directly with established runtimes like Node.js and Deno.

Modern Syntax Support

Bun automatically supports modern JavaScript and TypeScript syntax without the need for additional plugins or configurations. This feature ensures developers can immediately take advantage of the latest language improvements and coding techniques.

Bun Install

Bun can be installed on MacOS, Linux, and Windows (via WSL) using a simple command-line interface (CLI). To install Bun, you can run the following command in your terminal: curl https://bun.sh/install | bash. Alternatively, MacOS and Linux users can install Bun using Homebrew. Start by adding Bun to your Homebrew with brew tap oven-sh/bun, then install it by running brew install bun.

Bun Docker

Integrating Bun into a Docker environment provides a robust and scalable solution for deploying JavaScript and TypeScript applications. Docker containers offer an isolated, consistent environment for applications, ensuring uniform operation across different deployment locations. Developers gain significant advantages from Docker’s encapsulation features combined with Bun’s impressive performance capabilities. Such a setup promotes easier version control, dependency management, and testing. Leveraging Docker with Bun enhances the development to production workflow, minimizing discrepancies between environments and reducing deployment conflicts. The abstraction layer simplifies configuration processes and boosts overall deployment efficiency and reliability.

Bun DockerFile

The Dockerfile sets up a more secure and structured environment for a Bun application. It ensures that all files are neatly organized in a specific working directory (/app), dependencies are installed there, and the application is exposed on port 3000. In addition, the DockerFile example below, addresses security best practices by running the application as a non-root user, which can help mitigate potential risks in production environments.

Bun Upgrade

To update Bun to the latest stable version, run the command bun upgrade in your terminal. If you want to experiment with the newest features, you can install the Canary version by using the command bun upgrade —canary. This will download and apply the latest experimental version available.

Bun Cheatsheet

This Bun Cheatsheet provides a concise overview of the most commonly used commands in the Bun toolkit. The sheet is designed to serve as a quick reference guide, helping developers efficiently navigate through Bun’s capabilities. Whether you’re installing packages, running scripts, or setting up projects, this cheatsheet can help streamline your workflow with Bun.

CommandDescriptionCommand ExampleNote
Bun RunThis will execute the script (Javascript / Typescript) within the runtime engine.bun runThis should replace npm run with bun run.
Bun CleanTo remove the cache:bun run clean-
Bun HotBun will live reload the application, similar to file watchers like nodemon.bun run --hot index.ts-
Bun Dependencies InstallThis will install the dependencies for the application using an extremely fast npm-compatible package manager.bun installThis should replace yarn install or npm install with bun install.

Bun Flags

FlagDescription
—npmUse npm for tasks & install
—yarnUse yarn for tasks & install
—pnpmUse pnpm for tasks & install
—forceOverwrite existing files
—no-installSkip installing node_modules & tasks
—no-gitDon’t initialize a git repository
—openStart & open in-browser after finish

React

React Three Fiber

React Three Fiber (R3F) is a React renderer for Three.js, a popular 3D library. R3F brings the power of React’s declarative component structure to Three.js applications, making it easier to build and manage complex 3D scenes. By integrating the two, developers can leverage React’s state management and component lifecycle with Three.js’s 3D rendering capabilities.

React Unity

The main library is located at React Unity WebGL

React Unity Install

  • Install via Package Manager

  •       yarn add react-unity-webgl
    
  • For NPM:

        npm add react-unity-webgl
    

React Unity Component

  • The simple way to render the entity will be from below:

  •   import React from 'react';
      import { Unity, useUnityContext } from 'react-unity-webgl';
    
      function App() {
          const { unityProvider } = useUnityContext({
              loaderUrl: 'build/kbveapp.loader.js',
              dataUrl: 'build/kbveapp.data',
              frameworkUrl: 'build/kbveapp.framework.js',
              codeUrl: 'build/kbveapp.wasm',
          });
    
          return <Unity unityProvider={unityProvider} />;
      }
    
  • You can replace the variable of kbveapp with the app name of your finished webgl build.


Svelte

Threlte

An amazing and s3xy Three.js component library for Svelte. Official Repo

The Threlte library is broken into four modules that can be referenced uniquely through these packages:

  1. @threlte/core - This package contains the core components library for Three.js with symbolic hooks for Svlete.
  2. @threlte/preprocess - This package is the preprocessor for @threlte/core.
  3. @threlte/extras - Additional components, helpers, hooks and more that extend the core functionality of Threlte.
  4. @threlte/rapier - Rapier physics engine integration through components and hooks within Threlte.

Astro

Astro Svelte

An example of calling or rendering Svelte objects inside of Astro with a slot:

<object client:only="svelte">
    <!-- Slot -->
</object>

Without a slot:

<object client:only="svelte" />

MDX

MDX Cheatsheet

For indenting within a markdown file, we can use this code to produce a tab.

    &emsp;

TailwindCSS

TailwindCSS is a popular utility-first CSS framework that allows developers to rapidly build custom user interfaces without writing a single line of custom CSS. Unlike traditional CSS frameworks that provide predefined components, Tailwind offers low-level utility classes that let developers compose and style elements directly in their markup. This approach promotes consistency, reusability, and efficiency in styling, making it easy to create responsive and visually appealing designs. TailwindCSS also features a highly customizable configuration, enabling developers to tailor the framework to fit their specific design needs and preferences.

TailWindCSS Setup

  1. Create a New TailwindCSS Project Directory

    Open your terminal and create a new directory for your tailwindcss project. Navigate into the directory.

    mkdir my-tailwind-project
    cd my-tailwind-project
    

    After creating the directory, go ahead and initialize a new pnpm project!

    pnpm init -y
    
  2. Install TailwindCSS

    You can use the npm or pnpm to install Tailwindcss.

    pnpm install tailwindcss
    

    After installing the tailwindcss package, go ahead and initialize the tailwindcss configuration with the command below.

    npx tailwindcss init
    

    This will generate a tailwind.config.fs file within your project root.

  3. Configure TailwindCSS:

    Create a directory for your CSS files (e.g., src).

    mkdir src
    

    Create a main CSS file (e.g., src/styles.css).

    touch src/styles.css
    

    After creating the src/styles.css, open it up and paste in the default Tailwind imports.

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    

    Then update your tailwind.config.js file to specify the paths to all of your template files. This is necessary for purging unused styles in production.

    module.exports = {
    	content: ['./src/**/*.{html,js,jsx,ts,tsx}'],
    	theme: {
    		extend: {},
    	},
    	plugins: [],
    };
    
  4. Set Up a Build Process:

    To use TailwindCSS, you need to process your CSS file, we can use a couple different tools to help us. In the example below, we will use PostCSS but we can also use Webpack or ESBuild.

    Install PostCSS and Autoprefixer:

    pnpm install postcss postcss-cli autoprefixer
    

    Then create a PostCSS config file in your project root and add the following default configuration:

    module.exports = {
    	plugins: {
    		tailwindcss: {},
    		autoprefixer: {},
    	},
    };
    
  5. Build The CSS:

    Update the scripts section in your package.json to include a build script:

    "scripts": {
        "build:css": "postcss src/styles.css -o dist/styles.css"
    }
    

    Then to run the build script, we can execute the command below to generate the CSS files:

    pnpm build:css
    
  6. Include the Compiled CSS in Your HTML:

    Create an index.html file in your project root and include the compiled CSS file:

    <!doctype html>
    <html lang="en">
    	<head>
    		<meta charset="UTF-8" />
    		<meta
    			name="viewport"
    			content="width=device-width, initial-scale=1.0" />
    		<title>TailwindCSS Project</title>
    		<link href="dist/styles.css" rel="stylesheet" />
    	</head>
    	<body>
    		<h1 class="text-3xl font-bold underline">Hello, TailwindCSS!</h1>
    	</body>
    </html>
    
  7. Development Workflow:

    If you have serve already installed, then you can run the serve from the dist directory.

    By default, serve will serve the contents of the current directory on port 3000. If you want to specify a different directory (e.g., dist), you can do so:

    serve dist
    

    Then open your browser and navigate to http://localhost:3000 to view your TailwindCSS project.

    You have successfully set up, installed, and configured TailwindCSS in your project. From here, you can start building and styling your web pages using Tailwind’s utility classes. For more advanced configuration and customization, refer to the official TailwindCSS documentation.

TailwindCSS Buttons

These are the Dojo buttons







TailWindCSS Animation

Animation Utility provides animating elements, which can be extended and abstractly layered through Rive/Lottie.

The default animations are:

  • animate-spin : Which uses a keyFrames spin to transform / rotate the object, primary use case is for loading indictions.

  • animate-ping : Uses transform to slowly scale out the element and create a radar / ripple effect upon the element, primary use case is for notifications.

  • animate-pulse : Alter the opacity of the element, to create a fading in and out effect, primary use case is for skeleton loaders.

  • animate-bounce : Transform the Y access of the element. primary use case is for aesthetics.

  • hover:$animation : Conditional statement, where if the mouse is over the element, perform the animation.

TailWindCSS Spin-Slow

This is a custom animation that you can add to TailWindCSS by extending the animations field within the configuration file.

Scoped: animation: { 'spin-slow': 'spin 5s linear infinite', }

Proof of Concept:

/** @type {import('tailwindcss').Config} */
module.exports = {
	theme: {
		extend: {
			animation: {
				'spin-slow': 'spin 5s linear infinite',
			},
		},
	},
};

MUI

MUI, formerly known as Material-UI, stands as a prominent React UI framework that brings Google’s Material Design principles to life. Offering an extensive collection of React components and CSS-in-JS styling solutions, MUI enables developers to create responsive and visually consistent web applications with ease. With its standardized design components and patterns, MUI ensures cohesive and professional user interfaces, making it an invaluable asset for modern web development.

MUI Setup

  1. Install PNPM (Optional):

    If pnpm is not already installed, you can install it globally using npm:

    npm install -g pnpm
    
  2. Initialize Your Project:

    Create a new project directory and initialize it with pnpm:

    mkdir my-mui-project
    cd my-mui-project
    pnpm init
    
  3. Install React and React DOM:

    Install React and React DOM, which are required for using MUI:

    pnpm add react react-dom
    
  4. Install MUI Core:

    Install the core MUI package and its dependencies:

    pnpm add @mui/material @emotion/react @emotion/styled
    
  5. Set Up Your Project Structure:

    We will create a basic project structure for this MUI example!

    • Directorymy-mui-project/
      • Directorypublic/
        • index.html
      • Directorysrc/
        • App.js
        • index.js
        • style.css
      • package.json
      • pnpm-lock.yaml
    • README.md
  6. Create an HTML File:

    In the public directory, create an index.html file:

    <!doctype html>
    <html lang="en">
    	<head>
    		<meta charset="UTF-8" />
    		<meta
    			name="viewport"
    			content="width=device-width, initial-scale=1.0" />
    		<title>MUI Project</title>
    	</head>
    	<body>
    		<div id="root"></div>
    	</body>
    </html>
    
  7. Create Your React Application:

    In the src directory, create an index.js file to serve as the entry point for your React application:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import './styles.css';
    
    ReactDOM.render(
    	<React.StrictMode>
    		<App />
    	</React.StrictMode>,
    	document.getElementById('root'),
    );
    
  8. Create the Main App Component:

    Create an App.js file in the src directory and set up a basic MUI component:

    import React from 'react';
    import { Button, Container, Typography } from '@mui/material';
    
    function App() {
    	return (
    		<Container>
    			<Typography variant="h2" component="h1" gutterBottom>
    				Welcome to MUI
    			</Typography>
    			<Button variant="contained" color="primary">
    				Hello World
    			</Button>
    		</Container>
    	);
    }
    
    export default App;
    
  9. Add Basic Styling:

    Create a styles.css file in the src directory to add some basic styling:

    body {
    	margin: 0;
    	font-family: 'Roboto', sans-serif;
    }
    
    #root {
    	display: flex;
    	justify-content: center;
    	align-items: center;
    	height: 100vh;
    	background-color: #f5f5f5;
    }
    
  10. Configure Babel:

    If your project uses advanced JavaScript features or JSX, you might need to set up Babel. First, create a .babelrc file in the root directory:

    {
    	"presets": ["@babel/preset-env", "@babel/preset-react"]
    }
    

    Next, install Babel dependencies:

    pnpm add -D @babel/core @babel/preset-env @babel/preset-react babel-loader
    
    • Directorymy-mui-project/
      • Directorypublic/
        • index.html
      • Directorysrc/
        • App.js
        • index.js
        • style.css
      • package.json
      • pnpm-lock.yaml
      • .babelrc
    • README.md
  11. Configure Webpack:

    To bundle your application, you may want to set up Webpack. Create webpack.config.js in the root directory:

    • Directorymy-mui-project/
      • Directorypublic/
        • index.html
      • Directorysrc/
        • App.js
        • index.js
        • style.css
      • package.json
      • pnpm-lock.yaml
      • .babelrc
      • webpack.config.js
    • README.md
    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
    	entry: './src/index.js',
    	output: {
    		path: path.resolve(__dirname, 'dist'),
    		filename: 'bundle.js',
    	},
    	module: {
    		rules: [
    			{
    				test: /\.(js|jsx)$/,
    				exclude: /node_modules/,
    				use: {
    					loader: 'babel-loader',
    				},
    			},
    			{
    				test: /\.css$/,
    				use: ['style-loader', 'css-loader'],
    			},
    		],
    	},
    	plugins: [
    		new HtmlWebpackPlugin({
    			template: './public/index.html',
    		}),
    	],
    	resolve: {
    		extensions: ['.js', '.jsx'],
    	},
    	devServer: {
    		contentBase: path.join(__dirname, 'dist'),
    		compress: true,
    		port: 3000,
    	},
    };
    

    Install Webpack and its dependencies:

    pnpm add -D webpack webpack-cli webpack-dev-server html-webpack-plugin style-loader css-loader
    
  12. Add Scripts to Package.json:

    Add the following scripts to your package.json to build and start your application:

    {
    	"scripts": {
    		"start": "webpack serve --mode development",
    		"build": "webpack --mode production"
    	}
    }
    
  13. Start Your Development Server:

    Run the development server to see your MUI application in action:

    pnpm start
    

    Open your browser and navigate to http://localhost:3000. You should see your MUI application running with a button and some text.


Lottie

Lottie is a dynamic and innovative library developed by Airbnb that bridges the gap between designers and developers by allowing the incorporation of rich, high-quality animations into applications with ease. Built to interpret and render animations exported as JSON data from Adobe After Effects, Lottie facilitates the use of intricate animations without the overhead of traditional image or video files. With platform-specific integrations for iOS, Android, and the web, Lottie ensures that animations remain sharp and fluid across different screen resolutions and devices. By providing a more interactive and visually engaging user experience, Lottie has become a game-changer in the realm of modern app design and development.

Lottie Web Setup

  1. Install Lottie Web:

    First, you need to install the Lottie web library. You can do this using npm or pnpm. Open your terminal and run the following command:

    pnpm add lottie-web
    
  2. Set Up Your Project Structure:

    Create a basic lottie web project structure Here is an example of the layout:

    • Directorymy-project/
      • Directorysrc/
        • index.html
        • Directoryanimations/
          • animation.json
        • Directoryjs/
          • main.js
      • Directorycss/
        • styles.css
      • package.json
      • pnpm-lock.yaml
    • README.md
  3. Create an HTML File:

    Create an index.html file in the src directory: Here is a starter html template:

    <!doctype html>
    <html lang="en">
    	<head>
    		<meta charset="UTF-8" />
    		<meta
    			name="viewport"
    			content="width=device-width, initial-scale=1.0" />
    		<title>Lottie Animation Example</title>
    		<link rel="stylesheet" href="../css/styles.css" />
    	</head>
    	<body>
    		<div
    			id="animationContainer"
    			style="width: 500px; height: 500px;"></div>
    		<script src="../js/main.js"></script>
    	</body>
    </html>
    
  4. Add Lottie Animation JSON File:

    Place your Lottie animation JSON file in the src/animations directory. You can export this JSON file from Adobe After Effects using the Bodymovin plugin.

    You can also use our sister website, Rare Icon, to grab Lottie JSONs.

  5. Add Lottie to Your JavaScript File:

    In your js/main.js file, initialize Lottie and load your animation:

    import lottie from 'lottie-web';
    
    const animationContainer = document.getElementById('animationContainer');
    
    const animation = lottie.loadAnimation({
    	container: animationContainer, // the DOM element that will contain the animation
    	renderer: 'svg', // the rendering method: 'svg', 'canvas', or 'html'
    	loop: true, // whether the animation should loop
    	autoplay: true, // whether the animation should start automatically
    	path: '../animations/animation.json', // the path to the animation JSON file
    });
    
  6. Add Basic CSS:

    Add some basic CSS to css/styles.css to style your page:

    body {
    	display: flex;
    	justify-content: center;
    	align-items: center;
    	height: 100vh;
    	margin: 0;
    	font-family: Arial, sans-serif;
    }
    
    #animationContainer {
    	border: 2px solid #333;
    }
    
  7. Test Your Setup:

    Start a local server to test your setup. You can use a simple server like http-server:

    # Install http-server globally
    npm install -g http-server
    
    # Start the server
    http-server src
    

    Open your browser and navigate to the URL provided by http-server. You should see your Lottie animation playing in the animationContainer div.


SWUP

SWUP is a JavaScript library that brings a smooth, app-like feel to websites. Instead of traditional page reloads, SWUP provides seamless transitions with customizable animations, making browsing more enjoyable and engaging. When a link is clicked, SWUP loads new content asynchronously, avoiding the need for a full page refresh. The library is flexible and extensible, offering a variety of plugins to enhance functionality, such as improving accessibility, managing scripts, and maintaining scroll positions. SWUP is perfect for creating dynamic and responsive web applications that deliver a modern user experience.

SWUP Setup

  1. Install SWUP:

    First, you need to install SWUP. Open your terminal and add the swup package:

    pnpm add swup
    
  2. Install SWUP Plugins:

    To enhance SWUP’s functionality, install some useful plugins. Run the following command in your terminal:

    pnpm add @swup/scripts-plugin @swup/a11y-plugin @swup/head-plugin @swup/slide-theme @swup/scroll-plugin @swup/preload-plugin @swup/body-class-plugin @swup/debug-plugin
    
  3. Set Up Your Project Structure:

    Create a basic project structure. Here’s an example:

    • Directorymy-project/
      • Directorysrc/
        • index.html
        • about.html
        • contac.html
      • Directorypublic/
        • Directoryassets/
          • robots.txt
      • Directorycss/
        • styles.css
      • Directoryjs/
        • main.js
      • package.json
      • pnpm-lock.yaml
    • README.md
  4. Create HTML Files

    Create some HTML files in the src directory. Here’s an example for index.html:

    <!doctype html>
    <html lang="en">
    	<head>
    		<meta charset="UTF-8" />
    		<meta
    			name="viewport"
    			content="width=device-width, initial-scale=1.0" />
    		<title>Home</title>
    		<link rel="stylesheet" href="../css/styles.css" />
    	</head>
    	<body>
    		<div id="swup" class="transition-fade">
    			<h1>Home Page</h1>
    			<nav>
    				<a href="index.html">Home</a>
    				<a href="about.html">About</a>
    				<a href="contact.html">Contact</a>
    			</nav>
    		</div>
    		<script src="../js/main.js"></script>
    	</body>
    </html>
    

    Repeat the structure for about.html and contact.html, changing the content inside the div with id="swup".

  5. Add SWUP to Your JavaScript File:

    In your js/main.js file, initialize SWUP and its plugins:

    import Swup from 'swup';
    import SwupScriptsPlugin from '@swup/scripts-plugin';
    import SwupA11yPlugin from '@swup/a11y-plugin';
    import SwupHeadPlugin from '@swup/head-plugin';
    import SwupSlideTheme from '@swup/slide-theme';
    import SwupScrollPlugin from '@swup/scroll-plugin';
    import SwupPreloadPlugin from '@swup/preload-plugin';
    import SwupBodyClassPlugin from '@swup/body-class-plugin';
    import SwupDebugPlugin from '@swup/debug-plugin';
    
    const swup = new Swup({
    	plugins: [
    		new SwupScriptsPlugin(),
    		new SwupA11yPlugin(),
    		new SwupHeadPlugin(),
    		new SwupSlideTheme(),
    		new SwupScrollPlugin(),
    		new SwupPreloadPlugin(),
    		new SwupBodyClassPlugin(),
    		new SwupDebugPlugin(),
    	],
    });
    
  6. Add CSS for Transitions:

    Add some basic CSS to css/styles.css to handle the transitions:

    /* CSS for SWUP transitions */
    html,
    body {
    	margin: 0;
    	padding: 0;
    	font-family: Arial, sans-serif;
    }
    
    nav a {
    	margin: 0 10px;
    	text-decoration: none;
    	color: #333;
    }
    
    .transition-fade {
    	opacity: 1;
    	transition: opacity 0.4s;
    }
    
    html.is-leaving .transition-fade {
    	opacity: 0;
    }
    
  7. Test Your Setup

    Start a local server to test your setup. You can use a simple server like http-server:

    # Install http-server globally
    npm install -g http-server
    
    # Start the server
    http-server src
    

    Open your browser and navigate to the URL provided by http-server. Click the links in your navigation to see the smooth transitions provided by SWUP.

SWUP Install

  • Adding swup page into your nodejs application via yarn.

        pnpm add swup
    

    or yarn

  • Plugins to install for swup via yarn.

        yarn add @swup/scripts-plugin @swup/a11y-plugin @swup/head-plugin @swup/slide-theme @swup/scroll-plugin @swup/preload-plugin @swup/body-class-plugin @swup/debug-plugin
    

ESBuild

ESBuild is a fast JavaScript bundler and minifier that has gained popularity due to its remarkable speed and efficiency. Designed with performance in mind, ESBuild leverages Go’s concurrency model to provide lightning-fast build times, often outperforming other popular tools like Webpack and Rollup. It supports modern JavaScript features and can handle TypeScript, JSX, and even various CSS formats, making it a versatile choice for web development projects. Additionally, ESBuild’s simplicity in configuration and its ability to be integrated with other tools and workflows make it a compelling option for developers seeking a high-performance, scalable build solution.

ESBuild Setup

  1. Install ESBuild:

    First, you need to install ESBuild. You can do this using npm or yarn. Open your terminal and run one of the following commands:

    npm install esbuild --save-dev
    
  2. Create Your Project Structure:

    Set up a basic project structure

    • Directorymy-project/
      • Directorysrc/
        • Directorycomponents/
          • Graph.jsx
      • Directorypublic/
        • index.html
      • package.json
      • esbuild.config.js
    • README.md
  3. Write Your JSX Component:

    Create a simple React component in src/components/Graph.jsx:

    // src/components/Graph.jsx
    import React from 'react';
    
    const Graph = () => {
    	return <div>This is a Graph component.</div>;
    };
    
    export default Graph;
    
    • Directorymy-project/
      • Directorysrc/
        • Directorycomponents/
          • Graph.jsx
      • Directorypublic/
        • index.html
      • package.json
      • esbuild.config.js
    • README.md
  4. Create an HTML File;

    Create a simple HTML file in public/index.html to include your bundled script:

    <!doctype html>
    <html lang="en">
    	<head>
    		<meta charset="UTF-8" />
    		<meta
    			name="viewport"
    			content="width=device-width, initial-scale=1.0" />
    		<title>ESBuild Example</title>
    	</head>
    	<body>
    		<div id="root"></div>
    		<script src="graph.js"></script>
    	</body>
    </html>
    
    • Directorymy-project/
      • Directorysrc/
        • Directorycomponents/
          • Graph.jsx
      • Directorypublic/
        • index.html
      • package.json
      • esbuild.config.js
    • README.md
  5. Create an ESBuild Configuration File:

    Create an esbuild.config.js file in the root of your project:

    // esbuild.config.js
    const esbuild = require('esbuild');
    
    esbuild
    	.build({
    		entryPoints: ['src/components/Graph.jsx'],
    		bundle: true,
    		outfile: 'public/graph.js',
    		minify: true,
    		sourcemap: true,
    		platform: 'browser',
    		target: 'es2020',
    		jsxFactory: 'React.createElement',
    		jsxFragment: 'React.Fragment',
    	})
    	.catch(() => process.exit(1));
    
  6. Add Build Script to package.json:

    In your package.json, add a script to run the ESBuild configuration:

    {
    	"name": "my-project",
    	"version": "1.0.0",
    	"scripts": {
    		"build": "node esbuild.config.js"
    	},
    	"devDependencies": {
    		"esbuild": "^0.13.0",
    		"react": "^17.0.0",
    		"react-dom": "^17.0.0"
    	}
    }
    
  7. Build Your Project:

    Run the build script from your terminal:

    npm run build
    

    This command will bundle your Graph.jsx component, minify the output, generate a source map, and output the final script to public/graph.js.

  8. Serve Your HTML File:

    You can use any static file server to serve your public directory. For simplicity, you can use the serve package:

    # Install the serve package globally
    npm install -g serve
    
    # Serve the public directory
    serve public
    

    Now, open your browser and navigate to the URL provided by the serve command. You should see your HTML page with the bundled Graph component.

ESBuild Example


esbuild src/components/Graph.jsx --bundle --outfile=public/graph.js --minify --sourcemap --platform=browser --target=es2020 --jsx-factory=React.createElement --jsx-fragment=React.Fragment

This command tells esbuild to:

  • Bundle the Graph.jsx file.
  • Output the bundle to public/graph.js.
  • Minify the output.
  • Generate a source map.
  • Set the platform to browser (handles browser globals like window).
  • Target modern JavaScript (es2020).
  • Properly handle JSX for React.

Explanation of Key Options:

  • —bundle: Bundles all dependencies into one file.
  • —outfile: Specifies the output file.
  • —minify: Minimizes the output.
  • —sourcemap: Generates a source map.
  • —platform: Specifies the platform (node or browser).
  • —target: Sets the ECMAScript target version.
  • —jsx-factory and —jsx-fragment: Sets up JSX processing for React.

ESBuild Configuration Table

Configuration OptionDescriptionExample Value
entryPointsArray of entry points for the bundle.['src/components/Graph.jsx']
bundleBundles all dependencies into one file.true
outfileSpecifies the output file.'public/graph.js'
minifyMinimizes the output.true
sourcemapGenerates a source map.true
platformSpecifies the platform (node or browser).'browser'
targetSets the ECMAScript target version.'es2020'
jsxFactorySpecifies the JSX factory function for React.'React.createElement'
jsxFragmentSpecifies the JSX fragment function for React.'React.Fragment'
defineReplaces global identifiers with constant expressions.{ 'process.env.NODE_ENV': '"production"' }
externalExcludes specific modules from the bundle (e.g., node_modules packages).['react', 'react-dom']
loaderSpecifies a custom loader for specific file types.{ '.js': 'jsx' }
pluginsAdds custom plugins to the build process.[myPlugin()]
formatSets the output format (iife, cjs, esm).'iife'
globalNameSpecifies a global variable name to be used in the output bundle (for iife format).'MyLibrary'
injectSpecifies a list of files to be automatically injected into the bundle.['src/shim.js']
outdirSpecifies the output directory (used instead of outfile for multiple entry points).'dist'
entryNamesSpecifies the name pattern for output files when multiple entry points are used.'[dir]/[name]-[hash]'
assetNamesSpecifies the name pattern for output assets (e.g., images, fonts).'assets/[name]-[hash]'
chunkNamesSpecifies the name pattern for output chunks created via code-splitting.'chunks/[name]-[hash]'
splittingEnables code-splitting (only for esm format).true
metafileGenerates a JSON file with metadata about the bundle.true
watchEnables watch mode, automatically rebuilding on file changes.true
logLevelSets the logging level (silent, error, warning, info, debug).'info'
incrementalEnables incremental builds for faster rebuilds.true
treeShakingControls tree shaking behavior.true
minifyWhitespaceMinifies whitespace in the output.true
minifyIdentifiersMinifies variable and function names.true
minifySyntaxMinifies syntax without changing semantics.true
charsetControls the character set used in the output (default is utf8).'ascii'
legalCommentsControls how legal comments are handled (none, inline, eof, linked).'eof'

Shiki

Shiki is a syntax highlighter based on the same syntax definitions as Visual Studio Code, ensuring accurate and visually consistent code highlighting. When integrated with MDX, a format that combines Markdown and JSX, Shiki can provide syntax highlighting for code blocks within MDX content. The combination ensures that developers get a high-quality, themeable code highlighting experience in their MDX-based documents or blogs.

Shiki Setup

To set up Shiki, a powerful syntax highlighter, simply install it using npm with the command npm i shiki. This will allow you to integrate rich code syntax highlighting into your projects, enhancing the readability and aesthetics of code snippets on web pages or in documentation.

Shiki Configurations

Template themes for Shiki:

export type Theme =
	| 'css-variables'
	| 'dark-plus'
	| 'dracula-soft'
	| 'dracula'
	| 'github-dark-dimmed'
	| 'github-dark'
	| 'github-light'
	| 'hc_light'
	| 'light-plus'
	| 'material-darker'
	| 'material-default'
	| 'material-lighter'
	| 'material-ocean'
	| 'material-palenight'
	| 'min-dark'
	| 'min-light'
	| 'monokai'
	| 'nord'
	| 'one-dark-pro'
	| 'poimandres'
	| 'rose-pine-dawn'
	| 'rose-pine-moon'
	| 'rose-pine'
	| 'slack-dark'
	| 'slack-ochin'
	| 'solarized-dark'
	| 'solarized-light'
	| 'vitesse-dark'
	| 'vitesse-light';

Signature Pad

Signature Pad is a JavaScript library that utilizes HTML5 canvas technology to facilitate smooth signature drawing on web pages. It’s designed to function seamlessly across all modern desktop and mobile browsers without the need for any external libraries. Signature Pad supports various features like variable width Bézier curve interpolation, allowing for natural pen strokes and is ideal for applications requiring users to provide signatures digitally. You can install it via npm or directly embed it into your web pages using a script tag. For developers looking to implement detailed canvas-based interactions, Signature Pad offers extensive API options for managing signature data.

Singature Pad Tutorial

  1. Install and Include Signature Pad:

    You can install Signature Pad using npm or yarn, or directly include it in your HTML file. If you are using npm or yarn, run one of the following commands in your project directory:

    npm install signature_pad
    

    Alternatively, you can directly include Signature Pad in your HTML page using a script tag. This method is particularly useful if you’re not using a JavaScript module bundler:

    <script src="https://cdn.jsdelivr.net/npm/signature_pad@latest/dist/signature_pad.umd.min.js"></script>
    

    This script tag links to the latest version of Signature Pad hosted on the jsDelivr CDN, making it immediately available for use in your project.

  2. Create a Canvas Element:

    Add a canvas element to your HTML where the signature will be drawn:

    <canvas id="signature-pad" width="400" height="200"></canvas>
    
  3. Initialize Signature Pad:

    In your JavaScript file, initialize Signature Pad on the canvas element:

    const canvas = document.getElementById('signature-pad');
    const signaturePad = new SignaturePad(canvas);
    
  4. Configure Options (Optional):

    Configure Signature Pad with options such as pen color or background color:

    const options = {
    	backgroundColor: 'rgb(255, 255, 255)', // Set canvas background color
    	penColor: 'rgb(0, 0, 0)', // Set pen color
    };
    const signaturePad = new SignaturePad(canvas, options);
    
  5. Handling Resize:

    Add event listeners to resize the canvas appropriately when the window size changes:

    function resizeCanvas() {
    	const ratio = Math.max(window.devicePixelRatio || 1, 1);
    	canvas.width = canvas.offsetWidth * ratio;
    	canvas.height = canvas.offsetHeight * ratio;
    	canvas.getContext('2d').scale(ratio, ratio);
    	signaturePad.clear(); // otherwise isEmpty might return incorrect value
    }
    
    window.addEventListener('resize', resizeCanvas);
    resizeCanvas();
    
  6. Save and Clear Functions:

    Implement functions to save the signature to an image or clear the canvas:

    document.getElementById('save').addEventListener('click', function () {
    	const dataURL = signaturePad.toDataURL();
    	console.log(dataURL); // Save the data URL of the signature image
    });
    
    document.getElementById('clear').addEventListener('click', function () {
    	signaturePad.clear();
    });
    

Tools

This section provides an overview of essential JavaScript tools that can significantly enhance your project’s development and maintenance processes. From code editors and linters that ensure code quality and consistency, to frameworks and libraries that expedite development with ready-made functions and components, these tools cover a broad spectrum of functionalities. Additionally, we’ll explore build tools and task runners that automate routine tasks like minification and testing, alongside version control systems that track changes and facilitate collaboration. Whether you’re building a small application or a large-scale enterprise solution, integrating the right tools can streamline your workflow and increase efficiency.

Cypress

Cypress stands out as a comprehensive testing framework specifically tailored for modern web applications and written in JavaScript. Developers favor Cypress for its ability to streamline the testing process, enabling the creation of end-to-end tests, integration tests, and unit tests in a manner that is both coherent and straightforward. Unlike other testing tools, Cypress operates directly within the browser and executes commands concurrently with the application’s run loop. Such synchronization facilitates real-time interaction and debugging while its automatic waiting feature minimizes the inconsistencies commonly associated with asynchronous test execution. The framework’s extensive API library and user-friendly dashboard further bolster test automation and monitoring. These features collectively make Cypress a highly regarded tool among developers aiming to enhance the robustness and reliability of web applications.

Cypress Table

File / DirectoryDescription
cypress.jsonConfiguration file for Cypress settings. It allows customization of default behaviors for running tests.
cypress.env.jsonEnvironment variables specific to Cypress can be stored here, providing a secure place to store sensitive information outside of source control.
commands.tsCustom commands can be added to Cypress in this file, enhancing its functionality and reusability across tests.
index.tsThis file within the Cypress plugin folder is used to load plugins or modify internal behavior of Cypress via its API.
fixtures/Directory for storing static data that can be used during test runs. Helps in managing test data separately from test cases.
integration/Default directory where test files are located. Cypress will look for test files here unless configured otherwise.
plugins/Contains JavaScript files that are executed when a project is opened or re-opened. Useful for tasks like modifying webpack configuration, handling environment variables, etc.
support/Files in this directory are loaded before each test file execution. Useful for overriding configurations, creating global functions etc.

Cypress Command Table

CommandDescription
cy.get(selector)Retrieves one or more DOM elements by selector. Commonly used to interact with or assert the properties of elements on the page.
cy.request(url)Makes HTTP requests to specified URLs. Useful for testing backend APIs directly or to prepare application state before a test.
cy.trigger(eventName)Triggers an event on a DOM element. This is handy for testing interactive behavior like mouseover or keypress events.
cy.should(assertion, value)Attaches one or more assertions to elements yielded by the previous command. Frequently used to check if elements contain expected properties or states.
cy.invoke(functionName)Invokes a function on the previously yielded subject. Useful for invoking jQuery methods or other functions provided by DOM elements.
cy.contains(content)Finds and yields DOM elements containing the specified content, which can be text or a regular expression.
cy.visit(url)Visits the specified URL. It is the starting point for most end-to-end tests that interact with web pages.
cy.wait(alias)Waits for a specific alias to resolve before moving on. Aliases are typically used with cy.route() to wait for requests or responses.
cy.route(method, url, response)Intercepts and manages the behavior of network requests. cy.route() is essential for stubbing network calls to control test environments.
cy.click(options)Issues a click event on the first element within a set of DOM elements. Options can modify the behavior, like forcing the click or specifying the mouse button.

Cypress Advance Table

CategoryCommandDescription
Context and Hooksdescribe() / context()Define a test suite.
it() / specify()Define a test case.
before()Run once before all tests in a block.
after()Run once after all tests in a block.
beforeEach()Run before each test in a block.
afterEach()Run after each test in a block.
Assertions.should('not.exist')Assertion to check if element does not exist.
.should('be.visible')Assertion to check if element is visible.
.should('contain', 'text')Assertion to check if element contains text.
.should('have.value', 'value')Assertion to check if form element has a value.
.should('be.checked')Asserts that the element is checked.
.should('have.class', 'className')Asserts that the element has a specific class.
Utility Commandscy.log()Log a message to the Cypress Command Log.
cy.clearCookies()Clear browser cookies.
cy.fixture()Load a fixed set of data located in a file.
cy.reload()Reload the current page.
cy.screenshot()Take a screenshot of the current state of the application.
Selection Commandscy.get(selector)Select DOM elements.
cy.contains(content)Select elements containing specific text or content.
cy.root()Get the root DOM element.
cy.within()Scope upcoming commands to within a DOM element.
Action Commandscy.click()Click a DOM element.
cy.type('text')Type text into a DOM element.
cy.check()Check a checkbox or radio button.
cy.uncheck()Uncheck a checkbox.
cy.select('option')Select an option in a dropdown.
cy.submit()Submit a form.
Browser Commandscy.visit(url)Visit a URL.
cy.location()Get the current URL, pathname, or hash.
cy.title()Get the title of the current page.
cy.url()Get the current URL as a string.
cy.go('back') / cy.go('forward')Navigate back or forward in the browser’s history.
Network Requestscy.request()Make an HTTP request.
cy.server()Start a server to manage HTTP requests.
cy.route()Control behavior of network requests.
Aliasescy.as('aliasName')Assign an alias for later use.
cy.get('@aliasName')Retrieve an aliased element.
File Handlingcy.readFile()Read a file’s contents.
cy.writeFile()Write data to a file.
Environment and ConfigurationCypress.env('VAR')Access environment variables.
Cypress.config('key')Get or set configuration.
Debuggingcy.debug()Debug the command’s subject in the developer tools.
cy.pause()Pause test execution.

Cypress Tutorial

  1. Install Cypress in your project:

    npm install cypress --save-dev
    

    This command adds Cypress to your project as a development dependency, ensuring that it’s available for writing and running tests.

  2. Open Cypress for the first time:

    npx cypress open
    

    Running this command sets up the initial Cypress configuration and opens the Cypress Test Runner, which helps you manage and run your tests.

  3. Create the test files:

    After opening Cypress, it automatically generates a cypress folder in your project. Inside this folder, create two files: app.cy.ts for your test cases and app.po.ts for your page objects, which help manage element selectors and interactions in a reusable manner.

    app.po.ts File:

    // app.po.ts
    export class PageObjects {
    	getSubmitButton() {
    		return cy.get('button[type="submit"]');
    	}
    }
    

    app.cy.ts File:

    // app.cy.ts
    import { PageObjects } from './app.po';
    
    describe('App Test', () => {
    	const page = new PageObjects();
    
    	beforeEach(() => {
    		cy.visit('http://localhost:3000'); // Adjust URL to your application's URL
    	});
    
    	it('Should click the submit button', () => {
    		page.getSubmitButton().click();
    		cy.url().should('include', '/success'); // Adjust the assertion to match expected behavior
    	});
    });
    
  4. Run your tests:

    npx cypress run
    

    The command runs your tests in the headless mode, which is suitable for continuous integration environments or local test runs without the GUI.

  5. Review test results:

    After running the tests, Cypress provides detailed results in the terminal or command prompt. If you prefer a graphical interface, you can use npx cypress open to run tests and observe their execution in real time.

Cypress JSON API Example

Example Function:

export const checkJSONendpointAPI = (endpoints: string[]) => {
	endpoints.forEach((endpoint) => {
		cy.request(endpoint).then((response) => {
			expect(response.status).to.eq(200);
			expect(response.headers['content-type']).to.include(
				'application/json',
			);
			expect(response.body).to.be.an('object');
		});
	});
};
  1. Define the Function and Parameters: Begin by declaring the function checkJSONendpointAPI and specify that it accepts an array of strings, where each string represents an API endpoint URL.

    export const checkJSONendpointAPI = (endpoints: string[]) => {};
    

    This setup allows the function to handle multiple endpoints, making it versatile for API testing.

  2. Iterate Over the Endpoints: Use the forEach method to loop through each endpoint provided in the array. This method applies a function to each item in the array, which in this case is used to initiate a Cypress request to the endpoint.

    endpoints.forEach((endpoint) => {});
    

    This step is crucial for automating the process of sending requests to multiple endpoints without repeating code.

  3. Make a Request to Each Endpoint:

    Within the loop, use cy.request() to send an HTTP request to the current endpoint. This Cypress command is designed to handle asynchronous requests and fetches data from the specified endpoint.

    cy.request(endpoint).then((response) => {});
    

    Here, cy.request returns a promise that resolves with the response object, allowing you to inspect the response further in the subsequent steps.

  4. Check the Response Status: After receiving the response, ensure that the HTTP status code is 200. This status code indicates that the request was successful.

    expect(response.status).to.eq(200);
    

    Checking the status code is a basic validation to confirm that the endpoint is reachable and responding as expected.

  5. Validate the Content-Type: Verify that the Content-Type header of the response includes application/json. This step confirms that the endpoint is indeed returning JSON data.

    expect(response.headers['content-type']).to.include('application/json');
    

    It’s essential to check the Content-Type to ensure that the data format is correct, as the subsequent validation assumes JSON format.

  6. Assess the Response Body: Finally, ensure that the response body is an object. This check is vital because JSON data, when parsed, should typically be an object or an array.

    expect(response.body).to.be.an('object');
    

    The assertion verifies that the parsed JSON data structure is as expected, reinforcing the integrity of the response.

  7. Close out the function and then check if it executes without any issues!


Biome

Biome.js is a comprehensive toolchain specifically designed for web projects, providing a range of functionalities to maintain and enhance project quality. It features a formatter and linter that can be utilized through a Command Line Interface (CLI) or a Language Server Protocol (LSP). The toolchain supports JavaScript, TypeScript, JSX, and JSON, offering a high degree of compatibility with existing formatting standards like Prettier, and includes over 200 linting rules to help improve code quality.

Biome.js is designed to function interactively within an editor, allowing it to format and lint code as it is written, which is particularly useful for developers looking for immediate feedback on their code quality. For those looking to integrate Biome.js into their projects, it can be installed with npm and used directly from the command line to format, lint, and check code, making it a versatile addition to development workflows.

For detailed usage and more information about setting up Biome.js in your projects, you can visit their official GitHub page here.

Biome Setup

  1. Install Biome:

    You can install Biome using npm or your preferred Node.js package manager in a directory that contains a package.json file. This installation method is quick and integrates easily with your existing Node.js setup.

    npm install --save-dev --save-exact @biomejs/biome
    

    Alternatively, if you prefer not to use Node.js, you can download a standalone CLI binary from the Biome GitHub releases page, suitable for your operating system, and give it execution permissions.

  2. Configure Biome:

    To streamline your Biome usage across different environments (like your editor and CI systems), it’s recommended to create a biome.json configuration file in your project’s root directory. This file ensures consistent settings are used everywhere Biome is run. You can generate this file by running the following command:

    npx @biomejs/biome init
    

    This command will create a biome.json file with default settings, which you can modify as needed.

  3. Usage:

    Biome can be used to format, lint, and apply safe fixes to your code. You can run these tools individually or together depending on your needs.

    • To format your code:
      npx @biomejs/biome format --write ./src
      
    • To lint and apply safe fixes:
      npx @biomejs/biome lint --apply ./src
      
    • To check (format, lint, and organize imports) all at once:
      npx @biomejs/biome check --apply ./src
      
  4. Integrating with Your Editor: For an improved development experience, integrating Biome with your code editor is recommended. This enables features like format-on-save and provides inline suggestions and fixes. Most popular editors have plugins or extensions available for Biome.

  5. Set Up Continuous Integration: Incorporate Biome into your CI/CD pipeline to ensure all submitted code meets your formatting and linting standards before it is merged. Using Biome in your CI setup helps maintain code quality and reduces manual review time.

    Head over to the Git for CICD tutorials, information.

    Example of a Github Action from Biome Docs:

    name: Code quality
    
    on:
    push:
    pull_request:
    
    jobs:
    quality:
        runs-on: ubuntu-latest
        steps:
        - name: Checkout
            uses: actions/checkout@v4
        - name: Setup Biome
            uses: biomejs/setup-biome@v2
            with:
            version: latest
        - name: Run Biome
            run: biome ci .
    

Size Limit

Size Limit is a powerful tool designed to help developers control the size of their packages. It offers a suite of functionalities to measure various metrics such as the time it takes to load your package on a 3G network, the execution time of your JavaScript, and the overall size of your package. These measurements can assist in optimizing performance and ensuring your application loads efficiently for users.

Size Limit is particularly useful in a continuous integration environment, as it can be integrated with GitHub Actions through the Size-limit Report. This GitHub Action automates the process of tracking and reporting on the size impacts of new code, making it easier to prevent performance regressions during development