Skip to main content

4 posts tagged with "Front End"

View All Tags

Setting Up a Modern React Project with Linting, Formatting, Styling and Spell Checking

· 3 min read

When working on a React project, maintaining clean and consistent code is essential. This guide will walk you through setting up a React project with ESLint, Prettier, Stylelint, Husky, lint-staged, and cspell to automate code formatting, linting, and spell checking.

Step 1: Create a New React App

npx create-react-app my-app --use-npm
cd my-app

This sets up a new React project.


Step 2: Initialize Git

git init

Step 3: Install Dependencies

Install necessary development dependencies:

yarn add -D eslint prettier stylelint husky lint-staged stylelint-config-standard cspell stylelint-config-standard

Step 4: Configure ESLint

Initialize ESLint:

npx eslint --init

Modify .eslintrc.json:

{
"extends": ["react-app", "eslint:recommended", "plugin:prettier/recommended"],
"rules": {
"prettier/prettier": "error"
}
}

Create .eslintignore:

# Third party
**/node_modules

# Build products
build/
static/
docs/

Add ESLint Scripts to package.json

"scripts": {
"lint:ts": "eslint \"./src/**/*.{ts,tsx}\" --max-warnings 0",
"lint:ts:fix": "eslint --fix \"./src/**/*.{ts,tsx}\" --max-warnings 0"
}

Step 5: Configure Prettier

Create .prettierrc:

{
"arrowParens": "always",
"bracketSpacing": true,
"printWidth": 100,
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none"
}

Create .prettierignore:

.git
.github
.yarn
.husky
build
node_modules
static

Add Prettier Scripts to package.json

"scripts": {
"format": "prettier --write .",
"format:diff": "prettier --list-different ."
}

Step 6: Configure Stylelint

Create .stylelintrc:

{
"extends": "stylelint-config-standard",
"rules": {
"selector-class-pattern": null,
"value-keyword-case": ["lower", { "camelCaseSvgKeywords": true }]
}
}

Add Stylelint Scripts to package.json

"scripts": {
"lint:style": "stylelint \"**/*.css\"",
"lint:style:fix": "yarn lint:style --fix"
}

Step 7: Configure cspell (Spell Checker)

Initialize cspell:

npx cspell --init

Modify .cspell.json:

{
"version": "0.2",
"language": "en",
"ignorePaths": ["node_modules", "build", "static", ".docusaurus", "i18n"],
"dictionaryDefinitions": [
{
"name": "project-words",
"path": "./project-words.txt",
"noSuggest": true
}
],
"dictionaries": [
"css",
"html",
"fonts",
"typescript",
"softwareTerms",
"companies",
"lorem-ipsum",
"project-words"
]
}

Create a project-words.txt file to store custom words.

Add cspell Script to package.json

"scripts": {
"lint:spelling": "cspell \"docs/**/*.md\" \"blog/**/*.md\" \"src/**/*.js\" \"src/**/*.tsx\" \"docusaurus.config.js\" --no-progress --show-context --show-suggestions",
"lint:spelling:fix": "yarn rimraf project-words.txt && echo \"# Project Words - DO NOT TOUCH - This is updated through CI\" >> project-words.txt && yarn -s lint:spelling --words-only --unique --no-exit-code --no-summary \"**\" | cross-env LC_ALL=en_US.UTF-8 sort --ignore-case >> project-words.txt"
}

lint:spelling:fix does


Step 8: Configure Husky for Pre-Commit Hooks

Initialize Husky:

npx husky init

Add pre-commit hook:

echo "yarn run lint-staged" > .husky/pre-commit

Add pre-push hook:

echo "yarn run lint-staged" > .husky/pre-push

Step 9: Configure Lint-Staged

Modify package.json:

"lint-staged": {
"src/**/*.{js,jsx,ts,tsx}": [
"eslint --fix --max-warnings=0",
"prettier --write",
"cspell --no-progress --show-context --show-suggestions"
],
"src/**/*.{css,scss}": [
"stylelint --fix",
"prettier --write"
],
"{docs,blog}/**/*.{md,mdx}": [
"cspell --no-progress --show-context --show-suggestions"
]
}

Step 10: Run the Setup

yarn lint:ts
yarn format
yarn lint:style
yarn lint:spelling

Conclusion

By following these steps, your React project is now set up with:

  • ESLint for code linting
  • Prettier for code formatting
  • Stylelint for CSS linting
  • cspell for spell checking
  • Husky & lint-staged for pre-commit checks

This ensures cleaner, more readable, and error-free code throughout your development process. 🚀

Static Code Analysis in a React App

· 3 min read

Introduction

Code quality is crucial in modern web development, ensuring that projects remain maintainable, readable, and free from potential issues. In this guide, we will set up static code analysis in a React project using Yarn, integrating the following tools:

  • Husky → Manages Git hooks to enforce linting before commits.
  • Lint-staged → Runs linters only on staged files for efficiency.
  • ESLint → Lints JavaScript/TypeScript code for better quality.
  • Prettier → Formats code automatically for consistency.
  • Stylelint → Lints and fixes CSS/SCSS code.

Let's dive into the step-by-step setup.


1️⃣ Installing Required Packages

Run the following command to install all necessary dependencies as dev dependencies:

yarn add -D husky lint-staged eslint prettier stylelint eslint-config-prettier eslint-plugin-prettier eslint-plugin-react stylelint-config-standard

Why these tools?

  • ESLint: Ensures consistent JavaScript/TypeScript code by enforcing best practices and detecting potential issues.
  • Prettier: Automatically formats code to maintain a uniform style.
  • Stylelint: Lints and fixes CSS/SCSS styles.
  • Husky: Hooks into Git workflows to run linters before committing changes.
  • Lint-staged: Runs linters only on staged files to improve efficiency.

2️⃣ Configuring ESLint

To configure ESLint, create a file named .eslintrc.json in the root directory and add the following content:

{
"extends": ["react-app", "prettier"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}

Why ESLint?

✅ Catches syntax errors early.
✅ Helps maintain a consistent coding style.
✅ Enforces best practices in JavaScript and React development.


3️⃣ Configuring Prettier

To ensure consistent code formatting, create a .prettierrc.json file:

{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5"
}

Why Prettier?

✅ Automatically formats code on save.
✅ Eliminates debates over code style.
✅ Works seamlessly with ESLint.


4️⃣ Configuring Stylelint

To enforce CSS/SCSS best practices, create a .stylelintrc.json file:

{
"extends": "stylelint-config-standard",
"rules": {
"indentation": 2,
"string-quotes": "double"
}
}

Why Stylelint?

✅ Ensures consistent styling rules.
✅ Detects and fixes errors in CSS/SCSS.
✅ Avoids potential styling issues in projects.


5️⃣ Setting Up Husky & Lint-Staged

Installing Husky

Initialize Husky:

yarn husky install

Modify your package.json to include Husky and lint-staged:

"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"src/**/*.{css,scss}": [
"stylelint --fix",
"prettier --write"
]
}

Enable Pre-Commit Hook

Run the following command to enable Husky’s pre-commit hook:

yarn husky add .husky/pre-commit "yarn lint-staged"

Why Husky & Lint-Staged?

✅ Prevents committing bad code.
✅ Runs linters only on changed files (performance-friendly).
✅ Ensures consistent formatting and linting before every commit.


6️⃣ Running Linters Manually

To check code quality manually, run:

yarn lint       # Runs ESLint
yarn format # Runs Prettier
yarn stylelint # Runs Stylelint

Conclusion

By following these steps, we have successfully set up Husky, lint-staged, ESLint, Prettier, and Stylelint in a React project using Yarn. This setup ensures:

Better code quality
Automatic formatting
Enforced best practices
Prevention of bad code commits

With this configuration in place, your React project will maintain high coding standards, making it more maintainable and scalable! 🚀

Basics of Angular: Understanding Components

· 2 min read

Angular is a powerful front-end framework that allows developers to build dynamic, modern web applications. One of the fundamental building blocks of an Angular application is the Component. In this blog post, we will explore what an Angular component is, how it works, and different ways to define and style it.

What is a Component?

A Component in Angular is a reusable UI element that consists of three main parts:

  1. TypeScript class – Contains the logic and properties of the component.
  2. HTML template – Defines the structure and content to be displayed.
  3. CSS styles – Applies styles to the component.

Defining a Basic Angular Component

In Angular, a component is defined using the @Component decorator. Below is a simple example:

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: `Hello, {{ title }} {{ 1 + 2 }}`,
styles: [`:host {color: red;}`],
})
export class AppComponent {
title: string = 'NBT'; // A class property holding a title
}

Explanation:

  • selector: Defines the custom HTML tag to use this component. For example, <app-root />.
  • template: Contains the HTML structure, where {{ title }} binds data dynamically.
  • styles: Contains inline styles specific to this component.

Output:

Hello, NBT 3

Using External Template and CSS Files

Instead of defining the template and styles directly within the component file, we can separate them into external files.

app.component.ts (Component Definition)

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
selector: 'app-root',
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'NBT';
}

app.component.html (Template File)

<main id="main">
<div class="content">
<h1>Hello, {{ title }}</h1>
</div>
</main>

<router-outlet />

app.component.css (Stylesheet)

.content {
color: blue;
font-size: 20px;
}

Output:

Hello, NBT

Conclusion

In this blog post, we learned:

  • What an Angular component is.
  • How to create a basic component.
  • How to use external HTML and CSS files to organize code better.

Components are a crucial part of Angular applications. By using them effectively, we can create modular, reusable, and maintainable applications. Stay tuned for more Angular tips and best practices!

Creating an Angular Application from Scratch

· 2 min read

Setting up an Angular application from scratch may seem daunting at first, but with Angular CLI, the process is streamlined and efficient. This guide walks you through the essential steps, from installing dependencies to running your project.

1. Install the Latest Node.js

Before setting up Angular, ensure that you have the latest version of Node.js installed. Angular relies on npm (Node Package Manager) for dependency management.

Steps to Install Node.js:

  • Download and install Node.js from the official Node.js website.

  • Verify the installation by running the following commands in your terminal:

    node -v
    npm -v

    These commands should return the installed versions of Node.js and npm.

  • Ensure compatibility with Angular by checking Angular's version compatibility guide.

2. Install Angular CLI

Angular CLI (Command Line Interface) is a tool that simplifies Angular development by providing useful commands for creating, building, and serving applications.

Install Angular CLI:

  • Using npm:

    npm install -g @angular/cli
  • Using yarn:

    yarn global add @angular/cli

Verify the Installation:

Run the following command to check if Angular CLI is installed correctly:

ng version

This will display the installed Angular CLI version and its dependencies.

3. Create a New Angular Project

Once Angular CLI is installed, you can create a new Angular workspace and project using the CLI:

ng new my-app

Configuration Options:

  • Replace my-app with your desired project name.
  • The CLI will prompt you to choose configurations, such as:
    • Whether to include Angular routing
    • Preferred CSS preprocessor (CSS, SCSS, LESS, etc.)

After the project is created, navigate into the project folder:

cd my-app

4. Run the Angular Application

To launch the Angular application locally, start the development server using:

ng serve --open

What Happens?

  • The --open flag automatically opens the application in your default web browser.
  • By default, the app runs on http://localhost:4200/.
  • The server continuously watches for file changes and reloads the app as you modify the code.

Conclusion

Congratulations! You have successfully set up and run your first Angular application. From here, you can start modifying components, services, and styles to build your project. Angular's powerful framework will help you create dynamic and scalable web applications effortlessly. Happy coding! 🚀