To set up linters and code formatting for a React and Express project, you’ll want to use ESLint for linting and Prettier for consistent formatting. Here’s a step-by-step guide for frontend and backend written in JavaScript.

1. Set Up ESLint and Prettier for Each Directory

In the root, install ESLint, Prettier, and the necessary plugins:

npm install --save-dev eslint prettier eslint-plugin-prettier eslint-config-prettier

2. Create ESLint and Prettier Configurations for Each Directory

Frontend (React)

  1. In the frontend directory, create an ESLint configuration file (frontend/.eslintrc.js):
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:prettier/recommended',
  ],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['react', 'prettier'],
  rules: {
    'prettier/prettier': 'error',
    // Additional rules for frontend
  },
};

In the frontend directory, create a Prettier configuration file (frontend/.prettierrc):

{
  "semi": true,
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2
}

Backend (Express)

  1. In the backend directory, create an ESLint configuration file (backend/.eslintrc.js)
module.exports = {
  env: {
    node: true,
    es2021: true,
  },
  extends: ['eslint:recommended', 'plugin:prettier/recommended'],
  parserOptions: {
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['prettier'],
  rules: {
    'prettier/prettier': 'error',
    // Additional rules for backend
  },
};

  1. In the backend directory, create a Prettier configuration file (backend/.prettierrc), or use the same settings as the frontend configuration.

3. Add Scripts in the Root package.json

In the root package.json, add scripts to lint and format both frontend and backend

"scripts": {
  "lint:frontend": "eslint frontend --ext .js,.jsx",
  "lint:backend": "eslint backend --ext .js",
  "lint": "npm run lint:frontend && npm run lint:backend",
  "format:frontend": "prettier --write \"frontend/**/*.{js,jsx,json,css,md}\"",
  "format:backend": "prettier --write \"backend/**/*.{js,json,css,md}\"",
  "format": "npm run format:frontend && npm run format:backend"
}
  • Linting: npm run lint will run linting for both frontend and backend.
  • Formatting: npm run format will format code in both directories.

4. Configure VS Code for Project-Wide Linting and Formatting

To ensure linting and formatting are applied correctly, add a .vscode/settings.json file in the root:

{
  "eslint.workingDirectories": [
    { "directory": "frontend", "changeProcessCWD": true },
    { "directory": "backend", "changeProcessCWD": true }
  ],
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}

This setup will help VS Code recognize both frontend and backend configurations for ESLint.