Skip to content

Latest commit

 

History

History
87 lines (60 loc) · 2.75 KB

File metadata and controls

87 lines (60 loc) · 2.75 KB

Linting example (eslint)

Linting source code

yarn install
yarn lint

Expected behaviour

Three errors are shown:

  • LintFail.js: Unexpected var, use let or const instead
  • LintFail.js: Strings must use singlequote quotes
  • LintFail.js: Unexpected console statement

Each error is caused by a specific rule,

  • Unexpected var, use let or const instead: no-var
  • Strings must use singlequote: quotes
  • Unexpected console statement: no-console

Explanation

yarn lint refers to the lint script that is defined in package.json. This is equivalent to running ./node_modules/.bin/eslint src/ from the command line. eslint will validate that JavaScript source files pass a rules that help to avoid common errors or confusing code. It also enforces formatting to an extent.

eslint ruleset is configured in .eslintrc.

  • import plugin is used to validate that import statements resolve
  • eslint:recommended and google rulesets are used as a baseline.
  • some rules are overridden by specifying them in "rules".

Learn more

Motivations for rules

Each rule from eslint can be viewed at eslint rule documentation. The motivation and guidance on how to fix it (or when to turn it off) is given for each rule. Some rules can even be fixed automatically by running eslint with the --fix option.

Fixing linting errors

Try to fix the problems reported by eslint.

If a problem reported by eslint is not valid, rules can be disabled for a specific line or file.

Warning: You should not do this in 99% of the cases. The linter cannot help you if you disable it.

Disabling eslint for a line:

console.log("Hello world"); //eslint-disable-line no-console

Disabling eslint for the whole file:

/* eslint-disable no-console */

console.log("Hello world");

Note that different comment syntaxes are used for disabling lines versus whole files. This is to avoid accidentally disabling rules for the whole file. Such disable statements should be use very sparingly, otherwise the purpose of linting is defeated.

Linting continuously

Linting is useful to get immediate feedback about mistakes and is a much faster alternative to catching silly mistakes than testing manually in a web browser and watching out for execution errors. Configure your editor to run eslint automatically when the source file changes. Also add either a "pretest" or "prebuild" script to package.json to lint source files automatically when running yarn test or yarn build.