as i understood esLint + Prettier will clean and beautify your code, but not all – some thigs you will fix manually.
install eslint, better locally as below (source)
npm install eslint --save-dev
if no package.json create it through the terminal wizard with command
npm init
create a esLint config file through the terminal wizard with command
npx eslint --init
let’s config .eslintrc.js like this
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 12
},
"rules": {
"no-var": "error",
"semi": ["warn", "always"],
"indent": "error",
"no-multi-spaces": "error",
"space-in-parens": "error",
"no-multiple-empty-lines": "error",
"prefer-const": "error",
"no-use-before-define": "error"
}
};
Where do i get the rules ?
How to start esLint from terminal for separate file ?
npm run eslint -- ./index.js
and we will see report like this
How do i setup esLint in webstorm ?
And now on each save esLint will fix our code according to rules, but not all. Lets test it. Code below
const foo = 1
console.log(foo)
let bar
bar = 1
function test(
) {
console.log(baz);
}
const baz = 123
will be turned into this on Ctrl+S
const foo = 1;
console.log(foo);
let bar;
bar = 1;
function test(
) {
console.log(baz);
}
const baz = 123;
Can we do it else much better ? Yes, with Prettier. Install it
npm install --save-dev --save-exact prettier
Setup it
And now, on Ctrl + S we having this code
const foo = 1;
console.log(foo);
let bar;
bar = 1;
function test() {
console.log(baz);
}
const baz = 123;
Also we can try to connect prettier in .eslintrc.js like this
{
"plugins": [
"prettier",
],
"extends": [
"prettier",
],
"env": {
"es6": true,
"browser": true
},
rules: {
"no-var": "error",
"semi": "error",
"indent": "error",
"no-multi-spaces": "error",
"space-in-parens": "error",
"no-multiple-empty-lines": "error",
"prefer-const": "error",
"no-use-before-define": "error"
}
}
install plugins
npm ci eslint-plugin-prettier
npm ci eslint-config-prettier
and try to start script like this, but that didn’t work for me, need to analyze it more
npm run eslint -- ./index.js --fix
links