Markets

Stop arguing about code style – let the bot do it for you

Introduction

When we complete the project in the teams, each developer usually has their own understanding of the correctly written code. There are attributes of the whole code quality, so it is almost impossible to reach an agreement between a team or org level. Fortunately we have such tools today line and more proud What is stand out in the static code analysis. The use of such tools has the advantages of the whole bunch:

  1. You no longer need to have long discussions in the PRS about formatting and design. Prettier/Linter Config is the one who dictates the rules.
  2. There are many potential errors in the static analysis phase. Even before the code is dedicated.
  3. Significantly reduced efforts are required from developers to keep their code nice and clean. Most of the routine can be automated.
  4. If the boring routine is eliminated, you have more space for creativity and increased cognitive resources for higher business priorities.

In this tutorial, we set up a drama and arm with this complex static analysis tools.

What do you learn

  1. Setting up the environment: Preparation of the development environment with the necessary tools.
  2. Configuring Typescript Eslint: Add the library to the project and the fine tuning of the basic rules.
  3. By adding the gorgeous: Applying and tying with Eslind
  4. Setting a pre -hook hook: Add an extra gate to validate the code
  5. Configuring the Github action: The last setup limit

Setting up the environment

Before we dive, we need to make sure that we have the main configuration of the environment:

  • Nodejs V20.15.0 (NPM V10.7.0). Suggest to use the NVM node versions to manage

  • Create a storage facility on github and clon it on the spot with CLI

    GIT clone storage_adress

  • Open the terminal from the new storage folder and reset the NPM project

    npm init -y

  • Create .gitignore File with the following content

    node_modules

  • Install Typescript (V5.4) and some additional addictions

    npm i [email protected] ts-node @types/node @tsconfig/node20 -D
    
  • Create tsconfig.json file and place the configuration there

    {“Compileroptions”: {“Target”: “ES6”, “Module”: “Commonjs”, “Range”: True, “Esmoduleinop”: True, “Skiplibcheck”: True, “True” forceConsentcasinginnames “: True” True “Outdir”: ” [“src/**/*.ts”]”Field”: [“node_modules”] }

  • Add start script package.json

    “scripts”: {“Start”: “Ts-Node SRC/Index.ts”}

Creating a simple express server

We use a simple server for this tutorial express Library:

  • Set up more addictions

    npm install express
    npm i @types/express -D
    
  • Create src the catalog and index.ts File inside

    import express, { Request, Response } from 'express';
    
    const app = express(); const port = 3000;
    
    app.get('/', (req: Request, res: Response) => { res.send('Hello, world!'); });
    
    app.get('/error', (req: Request, res: Response) => { const a = 10 const b = 20 res.send('This endpoint has linting issues'); if (a == b) { console.log('This should be a strict equality check') } });
    
    app.listen(port, () => { console.log(Server is running on  });
    

Now we can try to start the server npm startTo. Unfortunately we will immediately get the Typescript error because we have an invalid code /error end -point handler

Of course, such a code is not even close to the scenario of real life, but we can easily fix this problem a to 20To.

app.get('/error', (req: Request, res: Response) => {
  const a = 20
  const b = 20
  res.send('This endpoint has linting issues');
  if (a == b) {
    console.log('This should be a strict equality check')
  }
});

Now we should be able to start and see the server without any problems Server is running on At the terminal.

Configuring Typescript Eslint

The next step is to install the Eslint package and its typescript addiction to our project:

npm i @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint -D

Also we have to create .eslintrc File with basic setting. We also add the rule

{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint"],
  "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
  "rules": {
  },
  "env": {
    "es6": true,
    "node": true
  }
}

This setup allows for the recommended configuration for binding. Other configurations (eg Airbnb, Alloy, Facebook, Shopify, etc.) have been adapted to specific technologies, but for the sake of simplicity we are currently maintaining the recommended configuration.

We add to the package.json: also the helper script:

"scripts": {
  "start": "ts-node src/index.ts",
  "lint": "eslint --ignore-path .eslintignore src/**/*.ts"
},

Adding new Eslint rules

The Eslint configuration is very flexible and supports hundreds of rules. We add a simple rule to us .eslintrc file

  "rules": {
    "eqeqeq": "error"
  },

This rules force typical equality operators === and !== instead == and !=To. Now we can catch this problem

npm run lint

Using the Eslint extension in your index

Most of the popular ideas have extensions for integrating Eslint. You can easily find instructions on your favorite code editor. It is strongly recommended to enable integration as it provides highlighting and some additional features, such as rule tips and automatic corrections.

After installing, you will see Eslint errors (vs. code) highlighted in IDE:

Correcting Eslint's errors

First, we will add a new inquiry handler to our Express server:

app.get('/animals/:id', (req: Request, res: Response) => {
  const { id } = req.params;
  if (id === '1') {
    return res.send({ animal: 'cat' });
  } else {
    return res.send({ animal: 'dog' });
  }
});

and an additional Eslint rule that gets a new handler's problem:

"rules": {
  "eqeqeq": "error",
  "no-else-return": "error"
},

If we run light npm run lint Again we get two mistakes:

There are several ways to improve them. The first and most obvious is to change the code manually. Although this is not a big effort in our example app, as we have only one problem so far, it can become a pain in the back if we try to add to the project related projects. Fortunately, there is another way to solve problems with the eskint command --fix Flag:

eslint --fix --ignore-path .eslintignore src/**/*.ts

Now we see it no-else-return The problem was resolved but an equality operator problem (eqeqeq) was not. This is because not all rules support Autofix for various reasons. (Here)[ you can find the list of rules that support autofix – they are marked with wrench icon. Let’s fix the remaining issue manually and continue with prettier setup.

Adding Prettier

After setting up ESLint, we’ll now integrate Prettier to handle code formatting. While ESLint focuses on code quality rules, Prettier is dedicated to code styling and formatting.

Installing Prettier

Let’s install Prettier and ESLint-related Prettier packages:

npm i prettier eslint-config-prettier eslint-plugin-prettier -D
  • prettier: The core Prettier library
  • eslint-config-prettier: Disables ESLint rules that might conflict with Prettier
  • eslint-plugin-prettier: Runs Prettier as an ESLint rule

Configuring Prettier

Create a .prettierrc file in your project root:

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "endOfLine": "auto"
}

Now, let’s update our .eslintrc file to integrate Prettier with ESLint:

{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint", "prettier"]"expanding": [
    "eslint:recommended", 
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ]"Rules": {"eqeqeq": "Error", "No-Else-Return": "Error", "Pretttim/Prettier": "Error"}, "ENV": {"ES6": TRUE, "Node": True}}}}

Adding the header scripts

Add the following scripts to your package.json:

"scripts": {
  "start": "ts-node src/index.ts",
  "lint": "eslint --ignore-path .eslintignore src/**/*.ts",
  "lint:fix": "eslint --fix --ignore-path .eslintignore src/**/*.ts",
  "format": "prettier --write \"src/**/*.ts\""
}

Now we can format our code:

npm run format

Let's try our more magnificent setting by adding a poorly formatted code for us index.ts File:

app.get('/badformat', (req: Request,res:Response) => {
    const message    = 'This endpoint has formatting issues';
    
    
    return res.send({message,
        timestamp: new Date()});
});

Working npm run format It automatically improves the formatting problems of this code block.

Setting a pre -hook hook

We use the code to ensure the quality of the code husky and lint-staged Linding and formatting automatically to start.

Husky and fiber installation

npm i husky lint-staged -D

Setup Setup

Lisa a lint-staged Your configuration package.json:

"lint-staged": {
  "*.ts": [
    "eslint --fix",
    "prettier --write"
  ]
}

Setup of Husky

Reset Husky:

npx husky install

Add script to allow Husky package.json:

"scripts": {
  "start": "ts-node src/index.ts",
  "lint": "eslint --ignore-path .eslintignore src/**/*.ts",
  "lint:fix": "eslint --fix --ignore-path .eslintignore src/**/*.ts",
  "format": "prettier --write \"src/**/*.ts\"",
  "prepare": "husky install"
}

Create a pre -committee:

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

Now that you try to deal with problems with formatting or linking the code, the pre -group automatically improves them or prevents the responsibilities when the problems are unbeatable.

Configuring Github operations

The final step is to set up github operations to trigger our lining and formatting controls at any thrust and tensile application.

Creating a workflow of Github operations

Create a catalog .github/workflows The root of your project:

mkdir -p .github/workflows

Create a file called code-quality.yml In this catalog:

name: Code Quality

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  lint-and-format:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
          cache: 'npm'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Run ESLint
        run: npm run lint
        
      - name: Check formatting with Prettier
        run: npx prettier --check "src/**/*.ts"

  build:
    runs-on: ubuntu-latest
    needs: lint-and-format
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
          cache: 'npm'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Build TypeScript
        run: tsc

This workflow organizes Eslint and the more magnificent checks whenever you press the main part of the fetus or the fetal pull application.

Conclusion

In this tutorial we have created a comprehensive code quality infrastructure using:

  1. In the letter To ensure the type of safety
  2. Eslin For the quality rules of the code
  3. More proud For consistent formatting of the code
  4. Husky and tired For pre -hooks
  5. Github activities For continuous integration

You can ensure this setup:

  • Consistent code style throughout your team
  • Early detection of possible errors and code problems
  • Formatting an automated code
  • Continuous code quality control in your CI/CD pipeline

This approach significantly reduces the time spent on code style discussions during code reviews and allows your team to focus on business logic and functionality instead.

Keep in mind that the purpose of these tools is not to make your development process more complex, but to simplify and automate the daily aspects of coding, allowing you to focus on creating your own code.

Additional resources

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button

Adblocker Detected

Please consider supporting us by disabling your ad blocker