Skip to content

Adding code analysis to a plugin

Louise Davies edited this page Feb 18, 2020 · 7 revisions

Adding static code analysis

Using Prettier and ESLint

Plugins should use Prettier and ESLint as their static code analysis tools - this provides a standard without having to debate code styles and rules. They can also be enabled as a pre-commit hook that should fix most of the issues automatically.

yarn add --dev eslint@5.16.0 @typescript-eslint/parser@1.13.0 @typescript-eslint/eslint-plugin@1.13.0 eslint-plugin-import eslint-plugin-cypress eslint-plugin-jsx-a11y eslint-plugin-react
yarn add --dev prettier eslint-plugin-prettier eslint-config-prettier

(Note: we need to use eslint@5.16.0 and typescript-eslint@1.13.0 because CRA does not support typescript-eslint v2 yet - see https://github.com/facebook/create-react-app/issues/7529. Once next version of CRA (version > 3.1.1) is released these can be upgraded, but then the below .eslintrc.js file may be out of date)

Add a .eslintrc.js file at the top level with the contents from the .eslintrc.js in this code base. If it exists, remove the "eslintConfig" option from the package.json since this is unnecessary when an .eslintrc.js file is present.

Add a .prettierrc file at the top level with the contents from the .prettierrc in this code base

Integrating the code analysis in to a pre-commit hook

Install Husky (unless you're developing for datagateway, then just install and add the lint-staged sections)

yarn add --dev husky lint-staged

OR (datagateway)

yarn add --dev lint-staged

then update package.json with the following sections

  "lint-staged": {
    "src/**/*.{tsx,js,jsx,json}": [
      "eslint --max-warnings=0 --ext=tsx --ext=ts --ext=js --ext=jsx  --fix",
      "prettier --write",
      "git add"
    ],
    "cypress/**/*.{tsx,js,jsx}": [
      "eslint --max-warnings=0 --ext=tsx --ext=ts --ext=js --ext=jsx  --fix",
      "prettier --write",
      "git add"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },

(again, remove the husky section if you're developing for datagateway - this controls husky at the top level)

Running code analysis from npm scripts

Add a new line to the scripts section of package.json:

"scripts": {
    "lint:js": "eslint --ext=tsx --ext=js --ext=jsx --fix ./src",

then to run the linting from the console use

yarn lint:js
Clone this wiki locally