Intellij plugin: AirBnB ESLint w/ React - javascript

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

Related

How to remove comments when building TypeScript into JavaScripts using rollup

I am using rollup to build my TypeScript sources. I want to remove comments ONLY, without any minification, in order to hot update code when debugging.
I have tried rollup-plugin-terser, it can remove comments but it will also minify my code somehow, I cannot completely disable the minification.
How can I do that? Thanks!
Like #jujubes answered in the comments, the rollup-plugin-cleanup will do the task. I want to expand a bit.
Three things:
Add ts to extensions list, like extensions: ["js", "ts"] — otherwise sources won't be processed, even if transpiling step typescript() is before it — I originally came here investigating why rollup-plugin-cleanup won't work on TS files and it was just ts extension missing 🤦‍♂️
code coverage is important; on default settings, this plugin would remove istanbul statements like /* istanbul ignore else */ so it's good to exclude them, comments: "istanbul",
removing console.log is a separate challenge which is done with #rollup/plugin-strip and it goes in tandem to rollup-plugin-cleanup. In my case, depending is it a "dev" or "prod" Rollup build (controlled by a CLI flag --dev, as in rollup -c --dev), I remove console.log on prod builds only. But comments are removed on both dev and prod builds.
currently, I use:
import cleanup from "rollup-plugin-cleanup";
...
{
input: "src/main.ts",
output: ...,
external: ...,
plugins: [
...
cleanup({ comments: "istanbul", extensions: ["js", "ts"] }),
...
Here's an example of rollup-plugin-cleanup being used my Rollup config, here's my Rollup config generator (in monorepos, Rollup configs are hard to maintain by hand so I generate them). If you decide to wire up --dev CLI flag, the gotcha is you have to remove the flag from the commandLineArgs before script ends, otherwise Rollup will throw, see the original tip and it in action.
You should be able to achieve this too with just rollup-plugin-terser. It bases on terser so more information it's actually available on its README, here is the part related to minification. So in your case this part of rollup.config.js should looks like:
plugins: [
terser({
// remove all comments
format: {
comments: false
},
// prevent any compression
compress: false
}),
],
Keep in mind, that you can also enable part of configuration for production only. So having declared production const in your rollup.config.js you can do like that:
import { terser } from 'rollup-plugin-terser';
const production = !process.env.ROLLUP_WATCH;
export default {
plugins: [
production && terser({
// terser plugin config here
}),
],
};

Is there a way to get the unique errors reported from ESLint

I am refactoring am existing project with TypeScript and React. I have introduced ESLint and there are over 300 errors reported across the code.
This is quite a large task as these cannot be fixed automatically with ESLint itself.
Is there a way to get the distinct error from the ESLint CLI output then use that rule to get the files that throw the rule error so I can fix it rule-by-rule rather than file-by-file?
Eslint supports custom formatters. So you can do something along the lines:
Add file lint-formatter.js
module.exports = results => {
const byRuleId = results.reduce(
(map, current) => {
current.messages.forEach(({ ruleId, line, column }) => {
if (!map[ruleId]) {
map[ruleId] = [];
}
const occurrence = `${current.filePath}:${line}:${column}`;
map[ruleId].push(occurrence);
});
return map;
}, {}
);
return Object.entries(byRuleId)
.map(([ruleId, occurrences]) => `${ruleId} (total: ${occurrences.length})\n${occurrences.join('\n')}`)
.join('\n########################\n');
};
The above example groups errors/warnings by rule id, but of course everything in your hands.
Then run linter with your custom formatter:
eslint -f ./lint-formatter.js
Sample output:
object-curly-spacing (total: 2)
foo/bar.js:2:8
foo/bar.js:3:13
########################
no-trailing-spaces (total: 1)
foo/bar.js:7:11
########################
object-curly-newline (total: 2)
foo/bar.js:14:8
foo/bar.js:15:31
########################
space-infix-ops (total: 1)
foo/bar.js:18:29
I had 100s of eslint errors from a open source project.
Spent 2 hours in trying to fix them.
Below worked:
Install eslint-nibble along with any dependencies, I have installed as below:
npm i -g eslint
npm i -g eslint-config-standard
npm i -g eslint-plugin-import
npm i -g eslint-plugin-markdown
npm i -g eslint-plugin-n
npm i -g eslint-plugin-promise
npm i -g eslint-nibble
Now see by running eslint & eslint-nibble:
Normal eslint produces 100s of mixed warning & errors
eslint --fix **/*.js
eslint-nibble will show all errors group by rule.
Also asks which ones we type of eslint errors we want to see:
eslint-nibble **/*.js

Eslint: disable all rules except 1 rule?

I want to use Eslint to check the output of my minifier. Obviously, this would trigger a lot of errors. I'm only interested in a single rule (compat/compat). How can I disable all the other ones?
Edit:
Here's my .eslintrc.js:
module.exports = {
extends: ['plugin:compat/recommended'],
env: {
browser: true,
},
};
Edit:
I found the reset option in the docs, but it seems to be disabled for my installation:
$ npx eslint file.js --config .eslintrc.browserslist.js --quiet --reset
Invalid option '--reset' - perhaps you meant '--ext'?
$ npx eslint --version
v6.8.0
$ npx eslint -h
eslint [options] file.js [file.js] [dir]
Basic configuration:
--no-eslintrc Disable use of configuration from .eslintrc.*
-c, --config path::String Use this configuration, overriding .eslintrc.* config options if present
--env [String] Specify environments
--ext [String] Specify JavaScript file extensions - default: .js
--global [String] Define global variables
--parser String Specify the parser to be used
--parser-options Object Specify parser options
--resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default
Specifying rules and plugins:
--rulesdir [path::String] Use additional rules from this directory
--plugin [String] Specify plugins
--rule Object Specify rules
Fixing problems:
--fix Automatically fix problems
--fix-dry-run Automatically fix problems without saving the changes to the file system
--fix-type Array Specify the types of fixes to apply (problem, suggestion, layout)
Ignoring files:
--ignore-path path::String Specify path of ignore file
--no-ignore Disable use of ignore files and patterns
--ignore-pattern [String] Pattern of files to ignore (in addition to those in .eslintignore)
Using stdin:
--stdin Lint code provided on <STDIN> - default: false
--stdin-filename String Specify filename to process STDIN as
Handling warnings:
--quiet Report errors only - default: false
--max-warnings Int Number of warnings to trigger nonzero exit code - default: -1
Output:
-o, --output-file path::String Specify file to write report to
-f, --format String Use a specific output format - default: stylish
--color, --no-color Force enabling/disabling of color
Inline configuration comments:
--no-inline-config Prevent comments from changing config or rules
--report-unused-disable-directives Adds reported errors for unused eslint-disable directives
Caching:
--cache Only check changed files - default: false
--cache-file path::String Path to the cache file. Deprecated: use --cache-location - default: .eslintcache
--cache-location path::String Path to the cache file or directory
Miscellaneous:
--init Run config initialization wizard - default: false
--env-info Output execution environment information - default: false
--no-error-on-unmatched-pattern Prevent errors when pattern is unmatched
--debug Output debugging information
-h, --help Show help
-v, --version Output the version number
--print-config path::String Print the configuration for the given file
If you want to use your .eslintrc file to keep your configuration (parser, plugin settings, etc), you can use eslint-nibble with the --rule=compat/compat flag. This will respect your normal configuration, but only show you errors from that one rule.
Disclaimer: I'm the creator of eslint-nibble.
You can add root: true to the config file, that way it will not inherit the other config files.
The eslint.json file should look like this:
module.exports = {
root: true,
rules: {
semi: ["error", "always"],
}
};
Simply specify the rule you want to use in your ESLint config, for instance this would enable only the "semi" rule:
module.exports = {
"rules": {
"semi": ["error", "always"],
}
};
https://eslint.org/docs/user-guide/configuring#configuring-rules
Or you could specify it with the --rule flag
Eslint's parser options currently default to ecmaVersion: 5[1]. So in case, your code is using ECMAScript > 5, eslint will start enforcing the rules of ECMAScript 5, 6, and so on. Hence, apart from defining root: true, it's important finding the right ecmaVersion. An ideal eslint config for projects beyond ECMAScript 5 that has all eslint rules disabled looks as follows:
module.exports = {
root: true,
parserOptions: {
ecmaVersion: 9
},
rules: {}
};
Where parserOptions.ecmaVersion is tuned to the code base's ECMAScript version.
1: https://eslint.org/docs/user-guide/configuring/language-options#specifying-parser-options

Prettier and eslint indents not working together

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

Getting a Parsing error on a template string with ESLint, but I have ECMA 6 in config file

I can post my whole config and JavaScript file if needed, but I am trying to run ESLint on some JavaScript I'm writing.
My 'eslintrc.json' file has this in the config (with some other rules):
"rules":
{
// Thought this was my issue and hoped it would solve it.
"env":
{
"es6": true
},
"prefer-template": "error", //template literals
"quotes":
[
"error",
"double",
{ "avoidEscape": true, "allowTemplateLiterals": true }
]
}
Here is the error code that spits out in the .log file for ESLint, and the code it is failing at.
Parsing error: Unexpected character '`' FolderName\FileName.js:31:17
function Something()
{
// Seperated to try and debug the issue.
var message = `Starting Something: ${ arguments.callee.name}`;
// ^
Log.Message(message);
SomeOtherFile.UpdateEnvironmentVariables();
}
I know by default ESLint uses ECMAScript 5 (Specifying Parser Options) so I tried setting it to ECMA 6 (that has template strings - See above config file), but that didn't seem to help.
What's weird is that the ESLint documentation (rule : quotes) explains backticks and mentions that it is only in ECMAScript 6, etc.. But it seems like the parser that ESLint uses (Espree - On ESLint) is having an issue or something.
I really don't want to go through and replace all of these with some string concatenations, any suggestions?
Your code lints as written on eslint.org/demo when ECMA Version 2015 is set. Well, there are errors, but they aren't the template literal usage.
What this tells me is that you're running into a parsing error, not a linting error and need to set your parser settings.
Parsing error when ECMA Version set to 5
Parse is fine and you have LINTING errors when ECMA is 2015
Solution
To fix this, I think you have to provide an .eslintrc file somewhere that sets parser options to es2015 or later.
Double-check and try changing what's in yours to include this:
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "script",
"ecmaFeatures": {}
}
So even if your file includes the comment at the top...
/*eslint-env es6 */
... the parser options will win out and kill the template literal. And, as you show, your error is a parsing error, not a linting one:
Parsing error: Unexpected character '`' FolderName\FileName.js:31:17
I will readily admit that's a very confusing distinction. I didn't figure it out until banging my head on this answer for a while, but it explains why my env settings in my files don't always seem to "take"; the parser options override them.
In .eslintrc.json, I used babel-eslint and installed babel-eslint as devDependency in package.json. Hope that works for you too
.eslintrc.json file
{
"env": {...},
"parser": "babel-eslint",
"parserOptions": {...}
}
Edit 1:
babel-eslint is archived and it is suggested to use #babel/eslint-parser.
More info below
babel eslint
#babel/eslint-parser
{
"env": {...},
"parser": "#babel/eslint-parser",
"parserOptions": {...}
}
Edit 2:
#babel/eslint-parser needs #babel-core installed. If you are not already using #babel, then its best to upgrade your eslint to 7.5 and above. Here is the link to similar question:

Categories

Resources