Lint - GradedJestRisk/js-training GitHub Wiki
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
- alert: warn, keep code as-is.
- fix
Have a look at IDE configuration, such as editorconfig
Other may include:
https://github.com/streetsidesoftware/cspell
Steps:
- install module
npm install eslint --save-dev - setup rules
npx eslint --init - check your rules
.eslintrcfile, 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>"
List:
- choose module syntax (CommonJS or ECMA script) with
parser/sourceTypeAPI- ECMAScript modules (
import (..) export):module - CommonJs (
require (..) export):script
- ECMAScript modules (
- choose ECMA script version
parser/ecmaVersionAPI - choose global environment variable with
envAPI
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
- parser default is ECMA5, you may need to change this
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>
Level:
- defaults are here (checkmark)
- one rule: add existing rule configuration in configuration file
rules: {
indent: ["error", 2]
},
- use a style-guide, eg JS standard
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..)
}
]
Built-in:
- eslint:recommended, active rules are those listed here, also with a checkmark on the right there
- eslint:all
- AirBnB
- Standard, use this module
"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)
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
"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')
List:
- change file extension (js by default):
eslint . --ext <FILE_EXTENSION>, egeslint . --ext hbs
Install plugin
npm install eslint-plugin-yaml --save-dev
Update your configuration .eslintrc.js
"overrides" : []
.eslintrc.yaml
overrides:
- files: [ "*.yaml", "*.yml"]
plugins: ["yaml"]
extends:
- "plugin:yaml/recommended"
If you need to lint hidden files (here .circlecli/config.yml), update .eslintignore
!.circleci
Install
npm install --save-dev lint-staged
Add action, here linting: if test fail, file add to staging wil be blocked.
“lint-staged”: {
“*.js”: [“./node_modules/.bin/eslint — fix”, “git add”]
}
This will lint you javascript code inside markown code blocks
Steps:
- install plugin
npm install --save-dev eslint eslint-plugin-markdown - add plugin to configuration
.eslintrc.js
extends: [
'plugin:markdown/recommended',
'standard'
],
- create a markown file with a JS block
- check linting error is triggered
Steps:
- install module
npm install --save-dev prettier - list files to be ignored in
.prettierignore- if using eslint, copy
cp .eslintignore .prettierignore - if not, this one for NodeJS
curl https://raw.githubusercontent.com/googleapis/nodejs-language/master/.prettierignore > .prettierignore
- if using eslint, copy
- do a dry-run:
npx prettier --check . - setup an empty configuration
touch .prettierrc.js(will hint IDE to use prettier)
module.exports = { singleQuote: true, trailingComma: 'none', printWidth: 150, };
List:
- do a dry-run:
npx prettier --check . - actually format:
npx prettier --write . - actually format single file:
npx prettier --write <FILE_PATH>
To get the following:
- eslint and prettierrc to use same formatting rule
- same output
npx prettier --check .asnpx eslint . - same output
npx prettier --write .asnpx eslint --fix .
- same output
- avoid any conflicting rule
- store rules in one place:
.prettierc
- install module
npm install --save-dev eslint-plugin-prettier - update
.eslintrc.jsonto include these settings
{
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
More steps to make rules compatible
- install module
npm install --save-dev eslint-config-prettier - update
.eslintrcto include these settings
{
'extends': [
(..)
// should be the last one
'prettier'
]
}
Check:
- do a dry-run:
npx prettier --check . - check message
- if you get
All matched files use Prettier code style!, 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
- if you get
- list the conflicting rules :
npx eslint --print-config <PATH_ANY_FILE> | npx eslint-config-prettier-check, should get
The following rules are unnecessary or might conflict with Prettier: - indent
- look for such a rule in
.eslintrcand deactivate it, run again till you getNo rules that are unnecessary or conflict with Prettier were found. - run prettier again
npx prettier --check <PATH_ANY_FILE> - if you still have errors
- check your config
- save all work in a commit, then run
npx prettier --write <PATH_ANY_FILE>, check difference and rule in.prettierc - open an issue
.prettierc instead of .eslintrc
{ singleQuote: true, trailingComma: 'none' }
Prettier can read .editorconfig file here
This involves:
- a pre-commit hook using husky
- a module able to
- select code to be commited
- fix it
- staging it again
eslint . is all taht is required).
If you use git add --patch, consider git-format-staged option to get proper formatting without altering non-staged file.
Steps:
- install and configure husky and lint-staged through npx
npx mrm lint-staged - stage and commit
- create and stage an improperly formatted file
- commit it and check
- the commit succeeded
- the commited file is properly formatted
Check prettier:
- build your file filter, eg to format all JS files in src directory
src/*.js - create a non-correctly formatted file matching this filter, stage it
- run prettier dry-run
npx prettier --check <FILE_FILTER> - check you get the message
Code style issues found in the above file(s).
- install git-format-staged
npm install --save-dev git-format-staged - note: all ignored files in
.prettier.ignorewill be ignored - run
npx git-format-staged -f 'prettier --ignore-unknown --stdin --stdin-filepath "{}"' '<FILE_FILTER>' - check the staged file has been reformatted
- remove file from staging and restore initial content
- install husky
npm install --save-dev husky - add husky configuration in
package.json>
"devDependencies": {
(..)
},
"husky": {
"hooks": {
"pre-commit": "git-format-staged -f 'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"' '<FILE_FILTER>' "
}
}
- add to staging
- commit:
git commit -m "Commiting non-formatted code, to be formatted by git-format-staged" - check result
- if code has been commited with formatted content
- if you get the message
/git-format-staged: error: formatter exited with non-zero status, run standalone command
Lint text
Steps:
- install linter
npm install --save-dev markdownlint - install CLI
npm install --save-dev markdownlint-cli - create markdown file
README.md
#Title Some text
- run it
markdownlint '**/*.md' --ignore node_modules, should exit in error - modify
README.md
Some text
- run it again, should return no error
- create task in package.json
"lint:markdown": "npx markdownlint-cli '**/*.md' --ignore node_modules"
Lint text
Steps:
- install linter
npm install --save-dev markdown-link-check