Eslint: disable all rules except 1 rule? - javascript

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

Related

Jest command not recognized

So i just started learning about Test Driven Developement and as an example i was asked to run the command npm test helloWorld.spec.js in the terminal but i got this error :
> javascript-exercises#1.0.0 test
> jest "helloWorld.spec.js"
'jest' n’est pas reconnu en tant que commande interne
ou externe, un programme exécutable ou un fichier de commandes.
// in english jest isn't recognized as an internal command or external
I'm working on windows and the only thing i have installed is node so what do i have to do?
Choose one of the following methods
1) Install globally
You need to install jest globally:
npm install jest -g
Note: You will have to call it as jest something.spec.js in your cli or specify a test command in your package.json.
2) Install locally
Install jest locally with npm install jest -D.
You can use a script in your package.json called test which would be "test": "jest".
If any of the above don't work, try reinstalling jest.
If it still doesn't work, try removing node_modules and npm cache clean --force and npm install
3) Config file
If you already have jest installed but it's not working, you can use a config file to track files based on regex pattern (you can do a lot more if you check out the docs).
The following part is from the docs:
Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
Or through JavaScript:
// Sync object
/** #type {import('#jest/types').Config.InitialOptions} */
const config = {
verbose: true,
};
module.exports = config;
// Or async function
module.exports = async () => {
return {
verbose: true,
};
};
Or through TypeScript (if ts-node is installed):
import type {Config} from '#jest/types';
// Sync object
const config: Config.InitialOptions = {
verbose: true,
};
export default config;
// Or async function
export default async (): Promise<Config.InitialOptions> => {
return {
verbose: true,
};
};
When using the --config option, the JSON file must not contain a "jest" key:
{
"bail": 1,
"verbose": true
}
Regex options
testMatch [array]
(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ])
The glob patterns Jest uses to detect test files. By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js.
Note: Each glob pattern is applied in the order they are specified in the config. (For example ["!**/__fixtures__/**", "**/__tests__/**/*.js"] will not exclude __fixtures__ because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after **/__tests__/**/*.js.)
testRegex [string | array]
Default: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
The pattern or patterns Jest uses to detect test files. By default it looks for .js, .jsx, .ts and .tsx files inside of \_\_tests\_\_ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js. See also testMatch [array], but note that you cannot specify both options.

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
}),
],
};

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

Define WebSocket as a global in ES Lint for a React Native app

I get the following eslint error:
42:21 error 'WebSocket' is not defined no-undef
You cannot import WebSocket from react-native because it's a global, but when I add WebSocket as globals to my .eslintrc.yml it doesn't change the outcome of the error:
globals:
WebSocket: true
How do I define WebSocket as a global in ES Lint for a React Native app?
Can this be fixed? Currently my .eslintrc looks like this:
env:
browser: false
es6: true
commonjs: true
node: true
extends: 'airbnb'
parser: babel-eslint
globals:
WebSocket: true
parserOptions:
ecmaFeatures:
experimentalObjectRestSpread: true
jsx: true
sourceType: module
plugins:
- react
- react-native
rules:
indent:
- error
- tab
- {"SwitchCase": 1}
linebreak-style:
- error
- unix
quotes:
- error
- double
semi:
- error
- never
no-tabs: off
max-len: off
no-console: off
no-plusplus: off
global-require: off
import/no-unresolved: off
import/extensions: off
class-methods-use-this: off
react/jsx-no-bind: off
react/forbid-prop-types: off
react/prefer-stateless-function: off
react/jsx-indent: [2, 'tab']
react/jsx-indent-props: [2, 'tab']
react/jsx-filename-extension: [1, { extensions: ['.js', '.jsx'] }]
react/jsx-uses-react: error
react/jsx-uses-vars: error
react-native/no-unused-styles: 2
react-native/split-platform-components: 2
react-native/no-inline-styles: off
react-native/no-color-literals: off
I can get rid of it using the inline comment
/* globals WebSocket:true */
Also when I don't inherit from the airbnb eslint, but I can't figure out which lint rule in Airbnb is responsible for blocking this.
Based on the information you provided, it looks like your config file is not being picked up for some reason. Configuration for globals looks correct and should work. In order to figure out what is going on, you should do two things. First you can run eslint --print-config path_to_some_js_file to see how your config looks like after ESLint resolves all dependencies and cascading. Most likely that config will not have globals declared. After that, you can run eslint --debug path_to_file to see all config files that are being used by ESLint. If your file is not being included, check all other config files and verify that they don't have root: true in them (which would prevent ESLint from merging configs in parent directories). For more information about CLI flags you can look at ESLint documentation

Intellij plugin: AirBnB ESLint w/ React

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

Categories

Resources