Typescript Linting & Formatting

Intro

Most stuff comes with eslint nowadays (e.g. ionic, nextjs), but not with prettier, husky and lint-staged. There are so many packages and plugins in this eco-system, and all I really want is to have formatting on git commits.

ESLint, Prettier, Husky, Lint-Staged, etc.

tl;dr

see here: https://niteshseram.in/blog/setting-up-eslint-prettier-and-husky-with-lint-staged-for-your-nextjs-project

npm i -D husky \
         prettier \
         lint-staged \
         eslint-config-prettier

Add the following to package.json:

{
  ...,
  "scripts":{
    ...,
    "format": "prettier --write .",
    "prepare": "husky install",
    "precommit": "lint-staged"
  },
  "prettier": {
    "printWidth": 100,
    "semi": true,
    "singleQuote": true,
    "trailingComma": "es5",
    "tabWidth": 2,
    "useTabs": false
  },
  "lint-staged": {
    "*.{html,js,jsx,ts,tsx}": [
      "prettier --write"
    ]
  }	
}

Finally, set up husky and its precommit hook with:

npm run prepare
npx husky add .husky/pre-commit "npm run precommit"

Gotchas

If you have a dir with a package.json file with its own lint-staged configuration, then lint-staged will parse and try to apply those configs.

Linting?

Suppose you want to also enforce stylistic rules (e.g. no for loops allowed) in your code. Suppose that whenever you write a for loop, your code starts emitting errors and refusing to compile. How do you implement this? I.e., how do you intergrate eslint with your IDE and typescript server?

Answer: don’t bother; life is too short; just rely on prettier.

If you have eslint installed and configured in your project and want to see linting suggestions within vscode, then that is easy enough: just enable the microsoft ESLint extension.

Comments

Leave a Reply

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