I just realized that there is something better than JSLint and I am having a bit of a hassle with it. I am referring to ESLint.
I am setting it up for VS Code, with the official Plugin by Dirk Baeumer.
So far, everything is running great, until I ran into the indent setting.
I am using a customized auto-beautify setting for my editor and it defaults to 4 spaces/tabs indentation on save.
I am getting 2 errors from ESLint due to integrated code convention types:
[ESLint] Expected indentaion of 2 spaces but found 4. (indent)
and also, for some other case scenarios, I get the following:
[ESLint] Expected indendation of 6 spaces but found 8. (indent)
and so on.. 10 but 12 , 12 but 14... you get the point.
How can I default ALL the indentations troughout my document to be 4 spaces?
My current .eslintrc settings:
{
"extends": [
"eslint:recommended"
],
"root": true,
"rules": {
// '===' instead of '==' rule
"eqeqeq": [2, "allow-null"],
// ^^^ '===' instead of '==' rule
"indent": [2, 4],
"quotes": [2, "single"],
"semi": [2, "always"],
"no-console": 0
},
"env": {
"es6": false,
"browser": true,
"commonjs": true,
"node": false,
"jquery": true
}
}
My "indent": [2, 4], is not working the way I expect it to.
Sample code for reference:
window.setTimeout(function () {
'use strict';
$(document).ready(function () {
var current_width = $(window).width();
if (current_width <= 481) {
$('.widget-form-list').addClass('supv');
$('.widget-form-item').addClass('supv-form-item');
}
})
// window resize
$(window).resize(function () {
var current_width = $(window).width()
if (current_width < 481) {
$('.widget-form-list').addClass('supv')
$('.widget-form-item').addClass('supv-form-item')
}
})
}, 1000)
ESLint configurations are cascading. Meaning that you can have multiple .eslintrc files in different subdirectories and they will be merged at lint time. Your configuration for indent rule looks correct, but based on the error messages you are getting, chances are - it's being overridden by something that sets default number of indentation spaces to 2.
To figure out what is going on, you can use two different commands in ESLint. First, you can run (from command line) ESLint with print-config option. It requires a file to lint, and it will output computed configuration that ESLint will use for this file. Verify that indent is set to [2, 4] in that configuration. If it's not, you can run ESLint with debug flag, which should print out locations of all config files that are being used. That should show you which file overrides your default configuration.
Problem fixed.
The issue was that while configuring the .eslintrc file using the terminal it somehow created another .eslintrc file within my */js/ directory by itself, which contains some default settings which override my */root/ file.
If you are experiencing the same issue - search for a second .eslintrc file within your project folder.
Related
I traying setup my vim based typescript developing environment, but have an issue with indent management.
Probably 'eslint' says: indent: Expected indentation of 2 spaces but found 4. after prettier reformat.
My .eslintrc.js:
module.exports = {
parser: '#typescript-eslint/parser', // Specifies the ESLint parser
extends: [
'plugin:react/recommended', // Uses the recommended rules from #eslint-plugin-react
'plugin:#typescript-eslint/recommended', // Uses the recommended rules from #typescript-eslint/eslint-plugin
'prettier/#typescript-eslint',
'plugin:prettier/recommended',
],
parserOptions: {
ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
ecmaFeatures: {
jsx: true, // Allows for the parsing of JSX
tsx: true, // Allows for the parsing of TSX ???
},
},
rules: {
indent: ['error', 2],
quotes: ['error', 'single'],
semi: ['error', 'never'],
'sort-keys': ['error', 'asc', { caseSensitive: true, natural: false }],
},
}
My .prettierc:
module.exports = {
semi: false,
trailingComma: 'all',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
};
As per this Kai Cataldo's comment on this GitHub issue:
ESLint's indent rule and Prettier's indentation styles do not match - they're completely separate implementations and are two different approaches to solving the same problem ("how do we enforce consistent indentation in a project").
Therefore, when using prettier, you'd better disable eslint's indent rule. It's guaranteed that they will clash.
This should fix it https://github.com/prettier/eslint-config-prettier
It disables rules in eslint that conflict with prettier
in eslintrc add indent: [2, 2, { SwitchCase: 1}]
Parameters defined
new eslint rules want the first parameter to be a number: Severity should be one of the following: 0 = off, 1 = warn, 2 = error.
the amount of indent
The object is stating how to indent switch and case statements following the options here.
Turning off default Visual Studio Code parser and just leaving the eslint parser on save fixed it for me.
Just go to settings Ctrl/Cmd + ,, choose User (global settings) or Workspace (only for the working repo) and on top right corner click the paper with a turning arrow. That will open the declared settings on a json file. With the following settings it should work on any case:
{
// other settings
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.organizeImports": false
},
// other settings
}
Normally at the bottom of the Visual Studio Code window you have a Fix on save: X flag. That should be linked with this setting so make sure to leave it consistent.
I ran into the same issue. Thing is you can just manually override any clashing rules. In my case it was the prettier/prettier plugin for ESLint, so that can be solved adding the indent rule, under the required plugin.
"rules": {
// "indent":["error",10]
"prettier/prettier":[ //or whatever plugin that is causing the clash
"error",
{
"tabWidth":4
}
]
}
You can override specific rules like this, to get rid of any clashes.
Most annoying thing.. so fixed with: eslint-config-prettier
{
"rules": {
"no-tabs": ["error", {"allowIndentationTabs": true}]
}
}
eslint-config-prettier will disable all ESLint formatting rules that may conflict with Prettier's rules.npm i --save-dev eslint-config-prettier
eslint-plugin-prettier is the plugin that will add Prettier's formatting rules.
Let's tell ESLint we'll use Prettier's recommended configuration:
npm i --save-dev eslint-plugin-prettier
//eslintrc.js
{
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest",
"plugin:prettier/recommended"
]
}
It seems on my end, the only conflict is with ternary operations. Another option to fix the issue is to use the following eslint rule.
"indent": ["error", 2, { "offsetTernaryExpressions": true }],
There are a lot more options here: https://eslint.org/docs/latest/rules/indent#offsetternaryexpressions
I find eslint's indent rules more configurable and would use them over prettier.
I had this issue and by changing Prettier to Use Tabs in the settings menu (ctrl + shift + P), it fixed the issue for me.
In my case I just changed CRLF (Carriage Return, Line Feed) to LF (Line Feed) on VSCode
If you are using VS-Code and configured the eslint and prettier settings as per the others answers here, then also check this option in VS-Code ;)
Change it to 'Tab' instead.
In my case what I did was I removed the indentation rule from the .eslintrc file and added useTabs: true to my .prettierrc file.
After reloading the VS Code it works perfectly with the tab size indentation.
So, npm i --save-dev eslint-config-prettier fixed the Issue as pointed out by Akshay
I'm trying to set some ESLint rules to my new Vue project extending both eslint-plugin-vue and airbnb. I could set up everything just fine, except for the tag inside Vue components.
The accepted default would be like:
<script>
export default {
name: 'Login',
};
</script>
However I'm trying to get this code style to be accepted:
<script>
export default {
name: 'Login',
};
</script>
Using the rule vue/script-indent ( https://eslint.vuejs.org/rules/script-indent.html ) I could get the job done with the baseIndent set to 1. However, the lint rule is still complaining about it.
I tried placing this in this .eslintrc.json file:
"overrides": [
{
"files": [",*.vue"],
"rules": {
"indent": "off"
}
}
]
Also tried using the ignoredNodes from indent rules ( https://eslint.org/docs/rules/indent ) however I think I couldn't get my AST selectors right.
This is my current .eslintrc.json file:
{
"extends": [
"plugin:vue/recommended",
"#vue/airbnb"
],
"rules": {
"indent": [2, 4],
"vue/html-indent": [2, 4],
"vue/script-indent": [2, 4, {
"baseIndent": 1
}],
"vue/singleline-html-element-content-newline": 0,
"vue/eqeqeq": 2
},
"plugins": [
"html"
]
}
I get these errors when running lint:
8:1 error Expected indentation of 0 spaces but found 4 indent
9:1 error Expected indentation of 4 spaces but found 8 indent
10:1 error Expected indentation of 0 spaces but found 4 indent
If you're using VSCode, this setting will probably help you out:
// settings.json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
// ...
}
At the time I saved the file before this setting, it linted with rules that wasn't defined by me even though I've written them on .eslintrc.js.
This setting made it work just fine.
But also check out the conflicts between eslint-plugin-html and eslint-plugin-vue.
Background
I just get into learning react.js, and find out a lot people are using prettier and eslint to format their code. But after I setup my own based on the online guides, wired things happened. It can format code correctly when I'm saving the file, but not when I manually trigger format function (Shift+option+F). It will format the file to a wired way that eslint will give me errors.
Here's the vscode settings that I'm using:
"editor.formatOnSave": true,
"[javascript]": {
"editor.formatOnSave": false
},
"eslint.autoFixOnSave": true,
"eslint.alwaysShowStatus": true,
"prettier.disableLanguages": [
"js"
],
"editor.detectIndentation": true,
"editor.tabSize": 2,
and I also have a .eslintrc file
{
"extends": ["react-app", "plugin:prettier/recommended"],
}
and a .prettierrc file
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"jsxBracketSameLine": true
}
What I assume here is the vscode keyboard shorcut(Shift+option+F) is not using the same configuration (or even not the same tool) as autoFixOnSave.
But also I don't understand how these tools work and integrated together, and which one overrides which one. Can some one help?
Why are you disabling js for prettier?
Do you know Prettier can be integrated flawlessly with ESLint?
Take a look at this article: Prettier: Integrating with ESLint
In your user/workspace settings, just add:
"files.autoSave": "off",
"editor.formatOnSave": true,
"eslint.autoFixOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": true
},
"eslint.options": {
"extensions": [".js", ".jsx"]
},
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
Also it is recommended having a .editorconfig in your root folder:
# http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = crlf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
And finally, in your .eslintrc file, add:
"extends": ["react-app", "plugin:prettier/recommended", "prettier/react"],
Check out the eslint-plugin-react for validating react.
I am not looking at the mac version of VS code, but I think that hotkey is supposed to be Shift + Option + F
Edit: I usually disable the default javascript formatter in vscode, because it can conflict with my eslint rules, which makes it impossible for eslint to properly format my code.
ESLint has it's own Fix command which does not have a hotkey on my setup, but I have eslint.autoFixOnSave: true.
Prettier does not hook into the internal vscode format command. It also has it's own command set up. The default hotkey to run prettier format for the majority of the available prettier extensions is CMD + Shift + P -> Format Document but will trigger on save if editor.formatOnSave is true.
I am getting aמ indentation error that I am having a hard time reasoning. Would really appreciate some help. Here's the stripped down Header.js file where ESlint thinks something is amiss:
import React from 'react';
function Header() {
return <p>Test</p>;
}
module.exports = Header;
ESlint throws an error
4:3 error Expected indentation of 1 tab character but found 0 indent
my .eslintrc file is as follows:
{
"parser": "babel-eslint",
"env": {
"browser": true,
"node": true
},
"extends": "airbnb",
"rules": {
"arrow-body-style": [0],
"comma-dangle": 0,
"indent": [2, "tab", {"SwitchCase": 1}],
"no-console": 0,
"react/prop-types": 0,
"react/jsx-indent-props": [2, "tab"]
}
}
ESLint version is 2.11.1
I am definitely missing something to get this error. But can't figure out what. I have looked into ESlint documentation; but my usage seems correct. I have checked the tab spacing on line 4 too.
Update 1:
The error disappeared when I typed out the same code in vim. I think the error has to do with some sublime settings/plugins that I installed recently.
Update 2:
Figured out the problem.
My sublime settings mentioned
"tab_size": 4,
That is incompatible with my .eslintrc file. I changed the settings to
"tab_size": 2,
and the issue was resolved.
Thanks a lot for all of you who commented
Using Intellij Idea 15.0.2 on Ubuntu 15.10 and trying to configure ESLint to work.
Followed the instructions on Jetbrains' site, but no dice.
Here's a screencap of my settings at languages&frameworks > javascript > code quality tools > ESLint. And here's a screencap of my nodejs/npm settings within IntelliJ.
And my .eslintrc file, in the root project directory:
{
"extends": "airbnb",
"rules": {
"comma-dangle": 0
}
}
Here's a snip from /index.js that produces no errors or warnings in IntelliJ:
var superman = {
default: { clark: "kent" },
private: true
};
Here's the output when I run eslint index.js from the terminal:
4:1 error Unexpected var, use let or const instead no-var
5:5 error Expected indentation of 2 space characters but found 4 indent
5:23 error Strings must use singlequote quotes
6:5 error Expected indentation of 2 space characters but found 4 indent
Note: I believe ESLint is running, since before I changed my .eslintrc to the AirBNB version, I was using an .eslintrc from Github that threw a number of ESLint errors in IntelliJ (that is, errors in the .eslintrc file itself, not my code).
Once I fixed those errors, though, the plugin quieted down and didn't yell at me when I tested it by producing mistakes.
JetBrains (Idea, Webstorm) settings
File > Settings > Plugins > Browse repositories... > Search: eslint > Install > Restart WebStorm
File > Settings > Languages & Frameworks > JavaScript > Code Quality Tools > ESLint
After that it should work like this:
ESLint config
ESLint doesn't come with a config. You have to create your own or use a preset:
npm install --save-dev eslint-config-airbnb eslint
Then in your .eslintrc
{
"extends": "airbnb"
}
You can also selectively disable/modify some rules from preset (0 - disable rule, 1 - warning, 2 - error):
{
'extends': 'airbnb',
'rules': {
'indent': [2, 'tab', { 'SwitchCase': 1, 'VariableDeclarator': 1 }],
'react/prop-types': 0,
'react/jsx-indent-props': [2, 'tab'],
}
}
Read: Turning off eslint rule for a specific line.
If you don't want to use airbnb config (most popular javascript style guide) you can create your own. Here is the instruction for react: How to config ESLint for React on Atom Editor.
To create your own preset you have to create npm package named eslint-config-myname and then use 'extends': 'myname', http://eslint.org/docs/developer-guide/shareable-configs
You can use command line to check if eslint works:
./node_modules/.bin/eslint .
You may though exclude some files from eslinting (node_modules are excluded by default) in .eslintignore:
bundle.js
There is also a --fix switch for eslint.
.editorconfig
Good companion for ESLint is editorconfig. Here is an example which works in JetBrains products:
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
# Matches multiple files with brace expansion notation
# Set default charset
[*.{js,jsx,html,sass}]
charset = utf-8
indent_style = tab
indent_size = 4
trim_trailing_whitespace = true
# don't use {} for single extension. This won't work: [*.{css}]
[*.css]
indent_style = space
indent_size = 2
I also have a github repository which already has these files set https://github.com/rofrol/react-starter-kit/
Based on this https://www.themarketingtechnologist.co/how-to-get-airbnbs-javascript-code-style-working-in-webstorm/
More here https://www.jetbrains.com/webstorm/help/using-javascript-code-quality-tools.html