Lint - GradedJestRisk/js-training GitHub Wiki

Table of Contents

General

Lint is static code checking:

  • formatting, eg indent (make code easier to read) - does not affect the AST
  • code-quality rules, eg no-unused-var (avoid bug introduction) - affect the AST
When come against a rule violation, they can work in 2 mode :
  • alert: warn, keep code as-is.
  • fix
Not in the scope, but tigthly coupled, is IDE-based prevention, such as proper formatting in the first place. Such an example is adding proper indentation when hitting .

Have a look at IDE configuration, such as editorconfig

Other may include:

standard

API

JS code : spellcheck

cspell

https://github.com/streetsidesoftware/cspell

eslint plugin

JS code: eslint

Rules here

install

Steps:

  • install module npm install eslint --save-dev
  • setup rules npx eslint --init
  • check your rules .eslintrc file, see here to use other format and nested folders
  • check detection single file npx eslint <PATH_TO_SOURCE> file
  • check automatic fix on single file npx eslint --fix <PATH_TO_FILE> file
  • add a task in package.json "lint": "npx eslint <PATH_TO_SOURCE_FILES>"

Configure several source type

List:

  • choose module syntax (CommonJS or ECMA script) with parser/sourceType API
    • ECMAScript modules (import (..) export): module
    • CommonJs (require (..) export): script
  • choose ECMA script version parser/ecmaVersion API
  • choose global environment variable with env API

Run

Run:

  • create a .js file
  • using npx npx run eslint <PATH_TO_SOURCE> file
  • using npm: npm run lint
  • directly ./node_modules/.bin/eslint <PATH_TO_SOURCE>
  • dry-run, overriding rule setting: npx eslint --rule <RULE_SETTING> <FILE>, eg. npx eslint --rule 'indent: ["error", 2]' foo.js
    • parser default is ECMA5, you may need to change this --parser-options=ecmaVersion:6
    • you can even dry-run stdin
echo 'const foo = 1' | npx eslint --stdin --parser-options=ecmaVersion:5 
> error  Parsing error: The keyword 'const' is reserved

Check rules checked for a single file:

  • list all npx eslint --print-config <PATH_TO_FILE>
  • get specific rule npx eslint --print-config <PATH_TO_FILE> | grep -C 3 <RULE_NAME>

Customize

Level:

  • defaults are here (checkmark)
  • one rule: add existing rule configuration in configuration file
  rules: {
    indent: ["error", 2]
  },
  extends: [
    'standard'
  ],
  • use a plugin for non-standard JS (eg, Node or frameworks, eg. Ember)
  • define as exception for a set of files
  overrides: [
    // node files
    {
      files: [
        'bar.js',
        'folder/*.js'
      ],
     //(as usual: env, extends, parserOptions..)
    }
  ]

style guide

Built-in:

  • eslint:recommended, active rules are those listed here, also with a checkmark on the right there
  • eslint:all
Popular:

define your own rules

Import

Sample here

Disallow specific import

"no-restricted-imports": ["error", {
    "name": "import-foo",
    "message": "Please use import-bar instead."
}

There are less options for CommonJS module (require) when restricting local module (eg. not package.json module but rather the code you're actually writing) - can restrict use on a particular file ( folder/file.js) - cannot restrict use of all files under a module ( /folder/**) - cannot restrict use of all files under a module but one ( /folder/** but /folder/file.js)





restrict language features

To prevent use of a language construct, use no-restricted-syntax rule.

Steps:

  • get the name of the Abstract Syntax Tree element, use this sandox
  • create the rule
  • test it here
Allowing only ISO8601 dates
"NewExpression[callee.name=Date][arguments.length=1][arguments.0.type=Literal]:not([arguments.0.value=/^[12][0-9]{3}-(0[0-9]|1[0-2])-([0-2][0-9]|3[01])(T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z)?$/])"

Faulty code (1 node found in esquery)

new Date('2020-01-01T15:00:34');

Correct code (0 node found in esquery)

new Date('2020-01-01T15:00:34Z')

CLI

List:

  • change file extension (js by default): eslint . --ext <FILE_EXTENSION>, eg eslint . --ext hbs

Lint YAML

Install plugin npm install eslint-plugin-yaml --save-dev

Update your configuration .eslintrc.js

"overrides" : [
]

.eslintrc.yaml

overrides&#58;
  &#45; files&#58; &#91; &quot;&#42;.yaml&quot;,  &quot;&#42;.yml&quot;&#93;
    plugins&#58; &#91;&quot;yaml&quot;&#93;
    extends&#58;
      &#45; &quot;plugin&#58;yaml/recommended&quot;

If you need to lint hidden files (here .circlecli/config.yml), update .eslintignore

&#33;.circleci

Lint-staged

Install npm install &#45;&#45;save&#45;dev lint&#45;staged

Add action, here linting: if test fail, file add to staging wil be blocked.

  “lint&#45;staged”&#58; &#123;
    “&#42;.js”&#58; &#91;“./node_modules/.bin/eslint — fix”, “git add”&#93;
  &#125;

Integrate markdown

This will lint you javascript code inside markown code blocks

Steps:

  • install plugin npm install &#45;&#45;save&#45;dev eslint eslint&#45;plugin&#45;markdown
  • add plugin to configuration .eslintrc.js
  extends&#58; &#91;
    &#39;plugin&#58;markdown/recommended&#39;,
    &#39;standard&#39;
  &#93;,
  • create a markown file with a JS block
  • check linting error is triggered

JS: formater / prettier

install

Steps:

  • install module npm install &#45;&#45;save&#45;dev prettier
  • list files to be ignored in .prettierignore
    • if using eslint, copy cp .eslintignore .prettierignore
    • if not, this one for NodeJS curl https&#58;//raw.githubusercontent.com/googleapis/nodejs&#45;language/master/.prettierignore &gt; .prettierignore
  • do a dry-run: npx prettier &#45;&#45;check .
  • setup an empty configuration touch .prettierrc.js (will hint IDE to use prettier)
module.exports &#61; &#123;
  singleQuote&#58; true,
  trailingComma&#58; &#39;none&#39;,
  printWidth&#58; 150,
&#125;&#59;

use

List:

  • do a dry-run: npx prettier &#45;&#45;check .
  • actually format: npx prettier &#45;&#45;write .
  • actually format single file: npx prettier &#45;&#45;write &lt;FILE_PATH&gt;

integrate with eslint

To get the following:

  • eslint and prettierrc to use same formatting rule
    • same outputnpx prettier &#45;&#45;check . as npx eslint .
    • same outputnpx prettier &#45;&#45;write . as npx eslint &#45;&#45;fix .
  • avoid any conflicting rule
  • store rules in one place: .prettierc
To use common rule definitions, use Steps:
  • install module npm install &#45;&#45;save&#45;dev eslint&#45;plugin&#45;prettier
  • update .eslintrc.json to include these settings
&#123;
  &quot;plugins&quot;&#58; &#91;&quot;prettier&quot;&#93;,
  &quot;rules&quot;&#58; &#123;
    &quot;prettier/prettier&quot;&#58; &quot;error&quot;
  &#125;
&#125;

More steps to make rules compatible

  • install module npm install &#45;&#45;save&#45;dev eslint&#45;config&#45;prettier
  • update .eslintrc to include these settings
&#123;
  &#39;extends&#39;&#58; &#91;
    (..)
     // should be the last one
    &#39;prettier&#39;
  &#93;
&#125;

Check:

  • do a dry-run: npx prettier &#45;&#45;check .
  • check message
    • if you get All matched files use Prettier code style&#33;, you're done
    • if you get Code style issues found in the above file(s). Forgot to run Prettier? there are rules conflicting, follow on
  • list the conflicting rules : npx eslint &#45;&#45;print&#45;config &lt;PATH_ANY_FILE&gt; &#124; npx eslint&#45;config&#45;prettier&#45;check, should get
The following rules are unnecessary or might conflict with Prettier&#58;
&#45; indent
  • look for such a rule in .eslintrc and deactivate it, run again till you get No rules that are unnecessary or conflict with Prettier were found.
  • run prettier again npx prettier &#45;&#45;check &lt;PATH_ANY_FILE&gt;
  • if you still have errors
    • check your config
    • save all work in a commit, then run npx prettier &#45;&#45;write &lt;PATH_ANY_FILE&gt; , check difference and rule in .prettierc
    • open an issue
Now, if you want to add a custom formatting rule, do this in .prettierc instead of .eslintrc
&#123;
  singleQuote&#58; true,
  trailingComma&#58; &#39;none&#39;
&#125;

integrate with editorconfig

Prettier can read .editorconfig file here

integrate with git

This involves:

  • a pre-commit hook using husky
  • a module able to
    • select code to be commited
    • fix it
    • staging it again
This is much more difficult than to prevent committing incorrect code ( eslint . is all taht is required).

If you use git add &#45;&#45;patch, consider git-format-staged option to get proper formatting without altering non-staged file.

lint-staged

Official doc

Steps:

  • install and configure husky and lint-staged through npx npx mrm lint&#45;staged
  • stage and commit
  • create and stage an improperly formatted file
  • commit it and check
    • the commit succeeded
    • the commited file is properly formatted

git-format-staged

Check prettier:

  • build your file filter, eg to format all JS files in src directory src/&#42;.js
  • create a non-correctly formatted file matching this filter, stage it
  • run prettier dry-run npx prettier &#45;&#45;check &lt;FILE_FILTER&gt;
  • check you get the message Code style issues found in the above file(s).
Install and check git-format-staged:
  • install git-format-staged npm install &#45;&#45;save&#45;dev git&#45;format&#45;staged
  • note: all ignored files in .prettier.ignore will be ignored
  • run npx git&#45;format&#45;staged &#45;f &#39;prettier &#45;&#45;ignore&#45;unknown &#45;&#45;stdin &#45;&#45;stdin&#45;filepath &quot;&#123;&#125;&quot;&#39; &#39;&lt;FILE_FILTER&gt;&#39;
  • check the staged file has been reformatted
  • remove file from staging and restore initial content
Plug with husky:
  • install husky npm install &#45;&#45;save&#45;dev husky
  • add husky configuration in package.json&gt;
  &quot;devDependencies&quot;&#58; &#123;
    (..)
  &#125;,
  &quot;husky&quot;&#58; &#123;
    &quot;hooks&quot;&#58; &#123;
      &quot;pre&#45;commit&quot;&#58; &quot;git&#45;format&#45;staged &#45;f &#39;prettier &#45;&#45;ignore&#45;unknown &#45;&#45;stdin &#45;&#45;stdin&#45;filepath \&quot;&#123;&#125;\&quot;&#39; &#39;&lt;FILE_FILTER&gt;&#39; &quot;
    &#125;
  &#125;
  • add to staging
  • commit: git commit &#45;m &quot;Commiting non&#45;formatted code, to be formatted by git&#45;format&#45;staged&quot;
  • check result
    • if code has been commited with formatted content
    • if you get the message /git&#45;format&#45;staged&#58; error&#58; formatter exited with non&#45;zero status, run standalone command

Markdown

Text

Lint text

Steps:

  • install linter npm install &#45;&#45;save&#45;dev markdownlint
  • install CLI npm install &#45;&#45;save&#45;dev markdownlint&#45;cli
  • create markdown file README.md
&#35;Title
Some text
  • run it markdownlint &#39;&#42;&#42;/&#42;.md&#39; &#45;&#45;ignore node_modules, should exit in error
  • modify README.md
Some text
  • run it again, should return no error
  • create task in package.json &quot;lint&#58;markdown&quot;&#58; &quot;npx markdownlint&#45;cli &#39;&#42;&#42;/&#42;.md&#39; &#45;&#45;ignore node_modules&quot;

Links

Lint text

Steps:

  • install linter npm install &#45;&#45;save&#45;dev markdown&#45;link&#45;check
⚠️ **GitHub.com Fallback** ⚠️