"Code faster, look at the time" - does this sound familiar to you?
How about time and respect for code quality? Working in a team? Automated tests?
Code Linting is a way to improve code quality. The term "linter" comes from the tool "Lint", which originally analyzed C source code. Already at that time the goal was to analyze the source code as automatically as possible and to find optimizations. In the course of time additional features were added.
Nowadays there are linters for almost all programming languages. JavaScript linters like JSHint or ESLint detect potential errors as well as code that is difficult to maintain. They detect common errors in source code and ensure that best practices are followed. Automatically detecting errors before the reviewer manually checks the code thus saves time and money.
Outside of JavaScript, linters for CSS or HTML are also developed and used in web development.
4. NPM Setup:
Install NPM in the project folder:
$ npm init
The Package.json file should now look something like this:
{
"name": "my-eslint-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
$ npm i eslint -D
$ touch .eslintrc
In the .eslintrc you can now configure ESLint.
By default the default preset eslint:recommended is used.
With the ignorePatterns it is also possible to ignore single folders.
The config should look like this:
{
"env": {
"browser": true,
"es6": true
},
"extends": ["eslint:recommended"],
"ignorePatterns": [
“build/assets/javascripts/legacy/**/*.js”,
]
}
Via "Scripts" the test script can now be exchanged for "lint". For this, the name of the task is defined at the beginning and then the command.
With "npm run lint ESLint can now be executed automatically via the console.
{
"name": "eslint-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"lint": "eslint 'path/to/javascript/file.js'"
},
"author": "",
"license": "ISC",
"devDependencies": {
"eslint": "^7.32.0"
}
}
There is an optional possibility to install an additional ESLint preset from Airbnb. For this additional dependencies have to be installed. This is easily done with the following command:
$ npx install-peerdeps --dev ESLint-config-airbnb-base
The next step is to include the preset. For this, airbnb-base is inserted into the Extends array of the .eslintrc.
{
"extends": [
"eslint:recommended",
"airbnb-base"
],
"rules": [
"no-alert": "off"
],
}
ESLint rules can be overwritten / deactivated in two different ways.
Disable complete line:
var myTest = “hello world” // eslint-disable-line
Deactivate individual rules
alert(“hello world); // eslint-disable-line no-alert
{
...
"extends": [
"eslint:recommended",
"airbnb-base"
],
"rules": {
"no-alert": "off"
}
}
How about time and respect for code quality? Working in a team? Automated tests?