How to Setup Eslint and Prettier With Git Precommit Hooks in React Typescript Project

You should probably create a new react app with typescript using like so:

1npx create-react-app my-app --template typescript

Now let's get started to setup eslint and prettier.
Remove eslintConfig from package.json.
Install prettier using these commands:

1yarn add --dev --exact prettier
2# these are for making eslint and prettier to play well together
3yarn add --dev eslint-config-prettier eslint-plugin-prettier 

Create config files like this:

1touch .eslintrc.js .eslintignore .prettierrc.js .prettierignore

Use same contents for both ignore files:

1build
2node_modules
3.github

You can use cli init command for eslint and prettier config, but here's a ready-to-go scripts:

 1// .eslintrc.js
 2module.exports = {
 3    env: {
 4        browser: true,
 5        es6: true,
 6        node: true,
 7    },
 8    extends: [
 9        'prettier',
10        'prettier/prettier',
11        'eslint:recommended',
12        'plugin:react/recommended',
13        'plugin:react-hooks/recommended',
14        'plugin:prettier/recommended',
15        'plugin:jsx-a11y/strict',
16    ],
17    parser: '@typescript-eslint/parser',
18    parserOptions: {
19        ecmaFeatures: {
20            jsx: true,
21        },
22        ecmaVersion: 2020,
23        sourceType: 'module',
24    },
25    plugins: ['react', 'jsx-a11y', '@typescript-eslint'],
26    rules: {
27        'react-hooks/exhaustive-deps': 'error',
28        'no-var': 'error',
29        'brace-style': 'error',
30        'prefer-template': 'error',
31        radix: 'error',
32        'space-before-blocks': 'error',
33        'import/prefer-default-export': 'off',
34    },
35    overrides: [
36        {
37            files: [
38                '**/*.test.js',
39                '**/*.test.jsx',
40                '**/*.test.tsx',
41                '**/*.spec.js',
42                '**/*.spec.jsx',
43                '**/*.spec.tsx',
44            ],
45            env: {
46                jest: true,
47            },
48        },
49    ],
50};
1//.prettierrc.js
2module.exports = {
3    printWidth: 100,
4    tabWidth: 2,
5    singleQuote: true,
6    semi: false,
7    trailingComma: 'all',
8    arrowParens: 'avoid',
9};

Add these scripts to package.json file:

1"lint": "eslint . --fix",
2"format": "prettier . --write"

Now you are good to run yarn lint and yarn format.

Let's setup git precommit hooks with husky and lint-staged.
Install lint-staged first:

1yarn add --dev lint-staged

Add these lines to your package.json file:

1"lint-staged": {
2    "*.{js,ts,tsx}": [
3        "eslint --quiet --fix"
4    ],
5    "*.{json,md,html}": [
6        "prettier --write"
7    ]
8}

Install and configure husky like so:

1npx husky-init
2yarn
3npx husky add .husky/pre-commit "yarn lint-staged"

That's pretty much it.
Happy coding! :)

comments powered by Disqus