Skip to content

Instantly share code, notes, and snippets.

@Monte9
Last active March 25, 2022 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Monte9/1e7c8a0fc6feeb0fae23f967f94330ee to your computer and use it in GitHub Desktop.
Save Monte9/1e7c8a0fc6feeb0fae23f967f94330ee to your computer and use it in GitHub Desktop.
Use ESLint, Prettier & lint-staged w/ Typescript

ESLint + Prettier + lint-staged

If you are working with Javascript or Typescript (React frontend, Node app, Lambda function, etc.) it's really useful to have eslint + prettier setup to ensure a standard code format.

In addition, lint-staged (with husky) will ensure that the code is automagically formatted when a new commit is made on the repo.

ESLint

ESLint is a JavaScript linter that you can use to lint either TypeScript or JavaScript code. It helps you enforce a set of style, formatting, and coding standards for your codebase.

npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
touch .eslintrc
touch .eslintignore
{
  "root": true,
  "parser": "@typescript-eslint/parser",
  "plugins": [
    "@typescript-eslint"
  ],
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "rules": { 
    "no-console": 1, // Means warning
  }
}
node_modules
build
src/graphql/generated.ts
"scripts": {
  "lint": "eslint . --ext .ts --cache --fix",
}
### ESLint
.eslintcache

Prettier

Prettier is an opinionated (yet fully configurable) code formatter. ESLint can kind of format code too, but it's mostly intended to sniff out when we're not following the mandated coding conventions.

npm install --save-dev prettier
touch .prettierrc
touch .prettierignore
{
  "semi": false,
  "trailingComma": "none",
  "singleQuote": true,
  "printWidth": 80
}
# Ignore the GraphQL generated file
src/graphql/generated.ts

# Ignore the build folder
build
"scripts": {
  "prettify": "prettier --config .prettierrc 'src/**/*.ts' --write"
}
// Default (format when you paste)
"editor.formatOnPaste": true

// Default (format when you save)
"editor.formatOnSave": true

ESLint + Prettier

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

eslint-prettier

lint-staged

This package provides the ability to run linter + prettier on a pre-commit hook (using husky) only on staged files. Super useful!

Github repo: https://github.com/okonet/lint-staged

Note: Make sure to setup ESLint + Prettier in your project first before running this.

npx mrm@2 lint-staged
"lint-staged": {
  "*.ts": [
    "yarn lint",
    "yarn prettify"
  ]
}

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment