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
Related
I am using Eslint: v7.26.0 and have the following rule added to it:
'react/sort-prop-types': [
2,
{
callbacksLast: true,
ignoreCase: false,
requiredFirst: true,
sortShapeProp: true,
noSortAlphabetically: false,
},
],
However, when I run the command to fix the ESLint issues, the issues thrown by this rule are not auto-fixed.
eslint --fix --format table someFile.js
Is there a way to auto-fix the errors thrown by this rule?
Sadly, this rule is not auto-fixable.
You can check the list of all the supported rules here.
It also tells you if the rule fixable with eslint --fix and if it is enabled by default.
If you are using VSCode and have installed the ESLint extension, then it will show you all the errors during active development which you can then fix.
The only con of this is that you will have to manually fix the errors if you are in the middle of development
sort-prop-types autofixer does sort within the spread boundaries:
I think this is expected.
https://github.com/yannickcr/eslint-plugin-react/blob/4a72e6a0784f7cc7f16f4574ce7f14de55540a73/tests/lib/rules/sort-prop-types.js#L1007-L1037
I'm trying to find the rules or plugins of ES-Lint to identify the commented code so that I can remove that unnecessary code and clean my repository.
I would like to identify the multiline as well as single line code:
/* import CreateIncentive from './containers/create-incentive';
import AffiliateFilters from './containers/affiliate-filters'; */
//import NotificationsSettings from './containers/notifications-settings';
I have tried with below rules Bt it is not identifying the above kind of code :
"rules": {
"no-warning-comments": [1, { "terms": ["todo", "fixme", "xxx"], "location": "anywhere" }],
"spaced-comment": ["error", "always", { "exceptions": ["-", "+"] }]
}
So I found the way to consider the code commented rule for Sonar. It is just a matter of Quality Profile.I had set the DEFAULT profile to sonar-way but it has only 100 rules specified.
While the other profile available for JAVASCRIPT is Sonar way Recommended which has 148 rules and it also includes the rule to identify the code commented.
So switching the default profile to Sonar Way Recommended had the default rule to identify the commented code for multi-line or single line code.
I have created a plugin for that purpose:
Install
npm install eslint-plugin-no-comments --save-dev
Configuration
// eslintrc.js
{
"plugins": ["eslint-plugin-no-comments"],
"rules": {
"eslint-plugin-no-comments/disallowComments": "error"
}
}
Full Documentation
Maybe you can try no-inline-comments ESLint rule
https://eslint.org/docs/rules/no-inline-comments
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.
In my Chai tests I often find myself wanting to use their assertions that are something like .to.be.empty, .to.be.true e.t.c., because I find them to be cleaner to read than .to.be.length(1) or .to.be.equal(true). However, this breaks my linter (I'm using default Airbnb linting).
I could use the // disable-eslint-line syntax, but then I'd have to add it to every single line that reads like that and that seems tedious.
I've also read about the DirtyChai library, but that would require me to go back through my entire testing library adding brackets to them all which seems like something I shouldn't have to do simply to get my linter to pass something it should probably be OK with in the first place.
Does anyone know a nicer way to handle this than the ways I've outlined above?
You can disable the rule for the entire file using eslint-disable at the top of the file in question:
/* eslint-disable no-unused-expressions */
expect(someTrueValue).to.be.true;
However, adding this at the top of every test file can be tedious. To disable this rule for all relevant files, you can:
Put a new .eslintc configuration file in the same directory as your test files, configured to disable that rule. This allows you to use the default configuration for all other rules while ignoring that rule specifically only on files in that folder. ESLint calls this Configuration Cascading.
{
"rules": {
"no-unused-expressions": "off"
}
}
Use the overrides key in your main .eslintrc file to disable rules for groups of files with glob pattern matching:
{
"overrides": [
{
"files": ["*.test.js", "*.spec.js"],
"rules": {
"no-unused-expressions": "off"
}
}
]
}
This also allows you to disable other rules which become troublesome in testing, such as no-underscore-dangle when using rewire.
Just found another option using Relative Glob Patterns:
In your .eslintrc file:
"overrides": [
{
"files": "*.test.js",
"rules": {
"no-unused-expressions": "off"
}
}
]
I've made a small plugin called eslint-plugin-chai-friendly that overrides the default no-unused-expressions rule and makes it friendly towards chai. The modified rule ignores the expect and should statements while keeping default behavior for everything else.
Combining jonalvarezz's answer with Ihor Diachenko's answer gave me exactly what I wanted:
npm install --save-dev eslint-plugin-chai-friendly
// .eslintrc.js
module.exports = {
// ...
plugins: ['chai-friendly'],
overrides: [{
files: '*.test.js',
rules: {
'no-unused-expressions': 'off',
'chai-friendly/no-unused-expressions': 'error',
},
}],
// ...
}
This way, the no-unused-expression rule will only be overridden in *.test.js files
AND
a no-unused-expression rule will still be in place to catch any unused expressions in the test files that are unrelated to chai.
In case anyone is stumbling upon this today, I had the same issue and found this solution on eslint documentation. In your eslint configuration file, you can specify one or several environments, which will predefine global variables for this environment. For us, it'd be mocha, and you'd configure like this in your .eslintrc.json:
{
"env": {
"mocha": true
},
...
...
...
}
As a result, it will remove all false positive about mocha describe, it, beforeEach, etc. without needing to completely disable eslint or completely disable any specific rule.
Tested with ESLint v.4.11 and mocha 5.0
I had this issue with tslint and solved it by simply moving the rule for unused expressions down one level. My ./tslint.json has all the other rules I care about, then I made ./src/tslint.json that just looks like
{
"rules": {
"no-unused-expression": true
},
"extends": "../tslint.json"
}
tslint automatically checks for a config file in every level as it descends the tree (with --project or using the VSCode extension) so this means that my tests (under ./test/) have all the other rules applied, but no-unused-expression only applies to files under ./src/.
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.