Step-by-Step Guide to Setting Up Linters for React + Vite with TypeScript Using pnpm
google

Step-by-Step Guide to Setting Up Linters for React + Vite with TypeScript Using pnpm

Linting is an essential part of modern web development. It helps maintain code quality, enforce coding standards, and catch errors early in the development process. In this guide, we’ll walk through how to set up ESLint and Prettier for a React + Vite + TypeScript project using the pnpm package manager. By the end of this guide, you’ll have a fully configured linting setup that integrates seamlessly with your development workflow and GitHub Actions.

Prerequisites

  1. Node.js (v18 or later recommended)
  2. pnpm (install it globally via npm install -g pnpm)
  3. A React + Vite + TypeScript project. If you don’t have one, create it using:

//bash
pnpm create vite@latest my-app --template react-ts
cd my-app        

Step 1: Install Required Dependencies

We’ll install ESLint, Prettier, and their necessary plugins for TypeScript and React.

Run the following command in your project root:

//bash
pnpm add --save-dev eslint typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y eslint-config-prettier eslint-plugin-prettier prettier        

Here’s what each package does:

  • eslint: The core linting library.
  • typescript: TypeScript compiler.
  • @typescript-eslint/parser: ESLint parser for TypeScript.
  • @typescript-eslint/eslint-plugin: ESLint plugin for TypeScript rules.
  • eslint-plugin-react: ESLint plugin for React-specific rules.
  • eslint-plugin-react-hooks: ESLint plugin for React Hooks rules.
  • eslint-plugin-jsx-a11y: ESLint plugin for accessibility rules in JSX.
  • eslint-config-prettier: Disables ESLint rules that conflict with Prettier.
  • eslint-plugin-prettier: Runs Prettier as an ESLint rule.
  • prettier: Code formatting tool.

Step 2: Configure ESLint

Create an .eslintrc.json file in the root of your project and add the following configuration:

{
  "parser": "@typescript-eslint/parser",
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended",
    "plugin:jsx-a11y/recommended",
    "plugin:prettier/recommended"
  ],
  "plugins": ["@typescript-eslint", "react", "react-hooks", "jsx-a11y", "prettier"],
  "rules": {
    "prettier/prettier": "error",
    "react/react-in-jsx-scope": "off",
    "@typescript-eslint/explicit-module-boundary-types": "off",
    "@typescript-eslint/no-unused-vars": "warn"
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  },
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  },
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  }
}        

Step 3: Configure Prettier

Create a .prettierrc.json file in the root of your project and add the following configuration:

{
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "printWidth": 80,
  "tabWidth": 2,
  "jsxSingleQuote": false,
  "bracketSpacing": true,
  "arrowParens": "always"
}        

Step 4: Updated eslint.config.js file:

Update your eslint.config.js file to include the ignores property.

module.exports = {
  // Other ESLint configurations
  ignores: [
    'node_modules/',
    'dist/',
    '*.test.js',
  ],
};        

Step 5: Add Scripts to package.json

Add the following scripts to your package.json to make it easier to run ESLint and Prettier:

"scripts": {
  "lint": "eslint .",
  "lint:fix": "eslint . --fix",
  "format": "prettier --write \"src/**/*.{ts,tsx,js,jsx,json,css,scss,md}\""
}        

  • pnpm lint: Runs ESLint to check for errors.
  • pnpm lint:fix: Runs ESLint and automatically fixes fixable issues.
  • pnpm format: Formats your code using Prettier.

Step 6: Stylelint

Run:

pnpm add --save-dev [email protected] [email protected] [email protected] [email protected]        

  1. Add .stylelintrc.json to the root directory of your project.

{
  "extends": ["stylelint-config-standard"],
  "plugins": ["stylelint-scss", "stylelint-csstree-validator"],
  "rules": {
    "at-rule-no-unknown": [
      true,
      {
        "ignoreAtRules": ["tailwind", "apply", "variants", "responsive", "screen"]
      }
    ],
    "scss/at-rule-no-unknown":  [
      true,
      {
        "ignoreAtRules": ["tailwind", "apply", "variants", "responsive", "screen"]
      }
    ],
    "csstree/validator": true
  },
  "ignoreFiles": ["build/**", "dist/**", "**/reset*.css", "**/bootstrap*.css", "**/*.js", "**/*.jsx", "**/*.tsx"]
}        
Run npx stylelint "**/*.{css,scss}" on the root of your directory of your project.        

Step 7: Configure Vite to Use ESLint

Then, update your vite.config.ts file:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import eslint from 'vite-plugin-eslint';

export default defineConfig({
  plugins: [
    react(),
    eslint({
      fix: true,
      include: ['src/**/*.ts', 'src/**/*.tsx'],
    }),
  ],
});        

Step 8: Set Up GitHub Actions for Linting

To automate linting checks on GitHub, create a GitHub Actions workflow.

  1. Create a .github/workflows directory in your project.
  2. Add a lint.yml file with the following content:

name: Linters

on: pull_request

env:
  FORCE_COLOR: 1

jobs:
  eslint:
    name: ESLint
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18.x'
      - name: Install pnpm
        run: npm install -g pnpm
      - name: Install Dependencies
        run: pnpm install
      - name: Run ESLint
        run: pnpm eslint "**/*.{js,jsx,ts,tsx}"

  stylelint:
    name: Stylelint
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18.x'
      - name: Install pnpm
        run: npm install -g pnpm
      - name: Install Dependencies
        run: pnpm install
      - name: Run Stylelint
        run: pnpm stylelint "**/*.{css,scss}"

  nodechecker:
    name: Node Modules Checker
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v3
      - name: Check node_modules existence
        run: |
          if [ -d "node_modules/" ]; then 
            echo -e "\e[1;31mThe node_modules/ folder was pushed to the repo. Please remove it from the GitHub repository and try again."
            echo -e "\e[1;32mYou can set up a .gitignore file with this folder included to prevent this from happening in the future." 
            exit 1; 
          fi        

Step 9: Enforce Linting in Pull Requests

To ensure that all pull requests pass linting checks before they can be merged:

  1. Go to your repository on GitHub.
  2. Navigate to Settings > Branches.
  3. Under Branch protection rules, click Add rule.
  4. Set the branch name pattern (e.g., main).
  5. Enable the option Require status checks to pass before merging.
  6. Select the Lint Codebase workflow from the list of status checks.
  7. Click Save changes.

Step 10: View Linter Results on Pull Requests

When you create or update a PR, the GitHub Actions workflow will automatically:

  • Run the following command:

pnpm lint        

  • Annotate linter issues directly on the PR under the Checks tab.

Conclusion

You’ve now set up a robust linting and formatting configuration for your React + Vite + TypeScript project using pnpm. This setup ensures consistent code quality and integrates seamlessly with your development workflow and GitHub Actions.

By following this guide, you’ve:

  1. Configured ESLint and Prettier.
  2. Integrated linting with Vite.
  3. Automated linting checks using GitHub Actions.
  4. Enforced linting as a requirement for pull requests.

Happy coding! ??


Mohsin Ali

I'm not a magician but I can make your Ads budget turn into conversation. SPECIALIST in "Facebook ads / Google ads / Amazon PPC"

2 周

Cfbr Btw .. brother I’m part of a WhatsApp group where we help each other grow on LinkedIn by engaging with eachother posts for more getting clients. For joining that send me connection request If you are comfortable... Best, [Mohsin Ali]"

回复

要查看或添加评论,请登录

Umair Hamza的更多文章

社区洞察

其他会员也浏览了