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:
1 | npm install --save-dev eslint prettier eslint-plugin-prettier eslint-config-prettier |
2. Create ESLint and Prettier Configurations for Each Directory
Frontend (React)
- In the
frontend
directory, create an ESLint configuration file (frontend/.eslintrc.js
):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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
):
1 2 3 4 5 6 | { "semi" : true , "singleQuote" : true , "printWidth" : 80, "tabWidth" : 2 } |
Backend (Express)
- In the
backend
directory, create an ESLint configuration file (backend/.eslintrc.js
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 }, }; |
- 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
1 2 3 4 5 6 7 8 | "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:
1 2 3 4 5 6 7 8 9 10 | { "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.