52.0.0 • Published 13 days ago

eslint-plugin-unicorn v52.0.0

Weekly downloads
618,087
License
MIT
Repository
github
Last release
13 days ago

eslint-plugin-unicorn Coverage Status npm version

More than 100 powerful ESLint rules

You might want to check out XO, which includes this plugin.

Propose or contribute a new rule ➡

Install

npm install --save-dev eslint eslint-plugin-unicorn

Usage (eslint.config.js)

Requires ESLint >=8.23.0.

Use a preset config or configure each rule in eslint.config.js.

If you don't use the preset, ensure you use the same languageOptions config as below.

ES Module (Recommended)

import eslintPluginUnicorn from 'eslint-plugin-unicorn';
import * as eslintrc from '@eslint/eslintrc';

export default [
	{
		languageOptions: {
			globals: eslintrc.Legacy.environments.get('es2024'),
		},
		plugins: {
			unicorn: eslintPluginUnicorn,
		},
		rules: {
			'unicorn/better-regex': 'error',
			'unicorn/…': 'error',
		},
	},
	// …
];

CommonJS

'use strict';
const eslintPluginUnicorn = require('eslint-plugin-unicorn');
const eslintrc = require('@eslint/eslintrc');

module.exports = [
	{
		languageOptions: {
			globals: eslintrc.Legacy.environments.get('es2024'),
		},
		plugins: {
			unicorn: eslintPluginUnicorn,
		},
		rules: {
			'unicorn/better-regex': 'error',
			'unicorn/…': 'error',
		},
	},
	// …
];

Usage (legacy: .eslintrc.* or package.json)

Use a preset config or configure each rule in package.json.

If you don't use the preset, ensure you use the same env and parserOptions config as below.

{
	"name": "my-awesome-project",
	"eslintConfig": {
		"env": {
			"es2024": true
		},
		"parserOptions": {
			"ecmaVersion": "latest",
			"sourceType": "module"
		},
		"plugins": [
			"unicorn"
		],
		"rules": {
			"unicorn/better-regex": "error",
			"unicorn/…": "error"
		}
	}
}

Rules

💼 Configurations enabled in.\ ✅ Set in the recommended configuration.\ 🔧 Automatically fixable by the --fix CLI option.\ 💡 Manually fixable by editor suggestions.

Name                                   Description💼🔧💡
better-regexImprove regexes by making them shorter, consistent, and safer.🔧
catch-error-nameEnforce a specific parameter name in catch clauses.🔧
consistent-destructuringUse destructured variables over properties.🔧💡
consistent-function-scopingMove function definitions to the highest possible scope.
custom-error-definitionEnforce correct Error subclassing.🔧
empty-brace-spacesEnforce no spaces between braces.🔧
error-messageEnforce passing a message value when creating a built-in error.
escape-caseRequire escape sequences to use uppercase values.🔧
expiring-todo-commentsAdd expiration conditions to TODO comments.
explicit-length-checkEnforce explicitly comparing the length or size property of a value.🔧💡
filename-caseEnforce a case style for filenames.
import-styleEnforce specific import styles per module.
new-for-builtinsEnforce the use of new for all builtins, except String, Number, Boolean, Symbol and BigInt.🔧
no-abusive-eslint-disableEnforce specifying rules to disable in eslint-disable comments.
no-anonymous-default-exportDisallow anonymous functions and classes as the default export.💡
no-array-callback-referencePrevent passing a function reference directly to iterator methods.💡
no-array-for-eachPrefer for…of over the forEach method.🔧💡
no-array-method-this-argumentDisallow using the this argument in array methods.🔧💡
no-array-push-pushEnforce combining multiple Array#push() into one call.🔧💡
no-array-reduceDisallow Array#reduce() and Array#reduceRight().
no-await-expression-memberDisallow member access from await expression.🔧
no-await-in-promise-methodsDisallow using await in Promise method parameters.💡
no-console-spacesDo not use leading/trailing space between console.log parameters.🔧
no-document-cookieDo not use document.cookie directly.
no-empty-fileDisallow empty files.
no-for-loopDo not use a for loop that can be replaced with a for-of loop.🔧💡
no-hex-escapeEnforce the use of Unicode escapes instead of hexadecimal escapes.🔧
no-instanceof-arrayRequire Array.isArray() instead of instanceof Array.🔧
no-invalid-remove-event-listenerPrevent calling EventTarget#removeEventListener() with the result of an expression.
no-keyword-prefixDisallow identifiers starting with new or class.
no-lonely-ifDisallow if statements as the only statement in if blocks without else.🔧
no-negated-conditionDisallow negated conditions.🔧
no-nested-ternaryDisallow nested ternary expressions.🔧
no-new-arrayDisallow new Array().🔧💡
no-new-bufferEnforce the use of Buffer.from() and Buffer.alloc() instead of the deprecated new Buffer().🔧💡
no-nullDisallow the use of the null literal.🔧💡
no-object-as-default-parameterDisallow the use of objects as default parameters.
no-process-exitDisallow process.exit().
no-single-promise-in-promise-methodsDisallow passing single-element arrays to Promise methods.🔧💡
no-static-only-classDisallow classes that only have static members.🔧
no-thenableDisallow then property.
no-this-assignmentDisallow assigning this to a variable.
no-typeof-undefinedDisallow comparing undefined using typeof.🔧💡
no-unnecessary-awaitDisallow awaiting non-promise values.🔧
no-unnecessary-polyfillsEnforce the use of built-in methods instead of unnecessary polyfills.
no-unreadable-array-destructuringDisallow unreadable array destructuring.🔧
no-unreadable-iifeDisallow unreadable IIFEs.
no-unused-propertiesDisallow unused object properties.
no-useless-fallback-in-spreadDisallow useless fallback when spreading in object literals.🔧
no-useless-length-checkDisallow useless array length check.🔧
no-useless-promise-resolve-rejectDisallow returning/yielding Promise.resolve/reject() in async functions or promise callbacks🔧
no-useless-spreadDisallow unnecessary spread.🔧
no-useless-switch-caseDisallow useless case in switch statements.💡
no-useless-undefinedDisallow useless undefined.🔧
no-zero-fractionsDisallow number literals with zero fractions or dangling dots.🔧
number-literal-caseEnforce proper case for numeric literals.🔧
numeric-separators-styleEnforce the style of numeric separators by correctly grouping digits.🔧
prefer-add-event-listenerPrefer .addEventListener() and .removeEventListener() over on-functions.🔧
prefer-array-findPrefer .find(…) and .findLast(…) over the first or last element from .filter(…).🔧💡
prefer-array-flatPrefer Array#flat() over legacy techniques to flatten arrays.🔧
prefer-array-flat-mapPrefer .flatMap(…) over .map(…).flat().🔧
prefer-array-index-ofPrefer Array#{indexOf,lastIndexOf}() over Array#{findIndex,findLastIndex}() when looking for the index of an item.🔧💡
prefer-array-somePrefer .some(…) over .filter(…).length check and .{find,findLast}(…).🔧💡
prefer-atPrefer .at() method for index access and String#charAt().🔧💡
prefer-blob-reading-methodsPrefer Blob#arrayBuffer() over FileReader#readAsArrayBuffer(…) and Blob#text() over FileReader#readAsText(…).
prefer-code-pointPrefer String#codePointAt(…) over String#charCodeAt(…) and String.fromCodePoint(…) over String.fromCharCode(…).💡
prefer-date-nowPrefer Date.now() to get the number of milliseconds since the Unix Epoch.🔧
prefer-default-parametersPrefer default parameters over reassignment.🔧💡
prefer-dom-node-appendPrefer Node#append() over Node#appendChild().🔧
prefer-dom-node-datasetPrefer using .dataset on DOM elements over calling attribute methods.🔧
prefer-dom-node-removePrefer childNode.remove() over parentNode.removeChild(childNode).🔧💡
prefer-dom-node-text-contentPrefer .textContent over .innerText.💡
prefer-event-targetPrefer EventTarget over EventEmitter.
prefer-export-fromPrefer export…from when re-exporting.🔧💡
prefer-includesPrefer .includes() over .indexOf() and Array#some() when checking for existence or non-existence.🔧💡
prefer-json-parse-bufferPrefer reading a JSON file as a buffer.🔧
prefer-keyboard-event-keyPrefer KeyboardEvent#key over KeyboardEvent#keyCode.🔧
prefer-logical-operator-over-ternaryPrefer using a logical operator over a ternary.💡
prefer-math-truncEnforce the use of Math.trunc instead of bitwise operators.🔧💡
prefer-modern-dom-apisPrefer .before() over .insertBefore(), .replaceWith() over .replaceChild(), prefer one of .before(), .after(), .append() or .prepend() over insertAdjacentText() and insertAdjacentElement().🔧
prefer-modern-math-apisPrefer modern Math APIs over legacy patterns.🔧
prefer-modulePrefer JavaScript modules (ESM) over CommonJS.🔧💡
prefer-native-coercion-functionsPrefer using String, Number, BigInt, Boolean, and Symbol directly.🔧
prefer-negative-indexPrefer negative index over .length - index when possible.🔧
prefer-node-protocolPrefer using the node: protocol when importing Node.js builtin modules.🔧
prefer-number-propertiesPrefer Number static properties over global ones.🔧💡
prefer-object-from-entriesPrefer using Object.fromEntries(…) to transform a list of key-value pairs into an object.🔧
prefer-optional-catch-bindingPrefer omitting the catch binding parameter.🔧
prefer-prototype-methodsPrefer borrowing methods from the prototype instead of the instance.🔧
prefer-query-selectorPrefer .querySelector() over .getElementById(), .querySelectorAll() over .getElementsByClassName() and .getElementsByTagName().🔧
prefer-reflect-applyPrefer Reflect.apply() over Function#apply().🔧
prefer-regexp-testPrefer RegExp#test() over String#match() and RegExp#exec().🔧💡
prefer-set-hasPrefer Set#has() over Array#includes() when checking for existence or non-existence.🔧💡
prefer-set-sizePrefer using Set#size instead of Array#length.🔧
prefer-spreadPrefer the spread operator over Array.from(…), Array#concat(…), Array#{slice,toSpliced}() and String#split('').🔧💡
prefer-string-replace-allPrefer String#replaceAll() over regex searches with the global flag.🔧
prefer-string-slicePrefer String#slice() over String#substr() and String#substring().🔧
prefer-string-starts-ends-withPrefer String#startsWith() & String#endsWith() over RegExp#test().🔧💡
prefer-string-trim-start-endPrefer String#trimStart() / String#trimEnd() over String#trimLeft() / String#trimRight().🔧
prefer-switchPrefer switch over multiple else-if.🔧
prefer-ternaryPrefer ternary expressions over simple if-else statements.🔧
prefer-top-level-awaitPrefer top-level await over top-level promises and async function calls.💡
prefer-type-errorEnforce throwing TypeError in type checking conditions.🔧
prevent-abbreviationsPrevent abbreviations.🔧
relative-url-styleEnforce consistent relative URL style.🔧💡
require-array-join-separatorEnforce using the separator argument with Array#join().🔧
require-number-to-fixed-digits-argumentEnforce using the digits argument with Number#toFixed().🔧
require-post-message-target-originEnforce using the targetOrigin argument with window.postMessage().💡
string-contentEnforce better string content.🔧💡
switch-case-bracesEnforce consistent brace style for case clauses.🔧
template-indentFix whitespace-insensitive template indentation.🔧
text-encoding-identifier-caseEnforce consistent case for text encoding identifiers.🔧💡
throw-new-errorRequire new when throwing an error.🔧

Deprecated Rules

See docs/deprecated-rules.md

Preset configs (eslint.config.js)

See the ESLint docs for more information about extending config files.

Note: Preset configs will also enable the correct language options.

Recommended config

This plugin exports a recommended config that enforces good practices.

ES Module (Recommended)

import eslintPluginUnicorn from 'eslint-plugin-unicorn';

export default [
		// …
		eslintPluginUnicorn.configs['flat/recommended'],
		{
			rules: {
				'unicorn/better-regex': 'warn',
			},
		},
];

CommonJS

'use strict';
const eslintPluginUnicorn = require('eslint-plugin-unicorn');

module.exports = [
		// …
		eslintPluginUnicorn.configs['flat/recommended'],
		{
			rules: {
				'unicorn/better-regex': 'warn',
			},
		},
];

All config

This plugin exports an all config that makes use of all rules (except for deprecated ones).

ES Module (Recommended)

import eslintPluginUnicorn from 'eslint-plugin-unicorn';

export default [
		// …
		eslintPluginUnicorn.configs['flat/all'],
		{
			rules: {
				'unicorn/better-regex': 'warn',
			},
		},
];

CommonJS

'use strict';
const eslintPluginUnicorn = require('eslint-plugin-unicorn');

module.exports = [
		// …
		eslintPluginUnicorn.configs['flat/all'],
		{
			rules: {
				'unicorn/better-regex': 'warn',
			},
		},
];

Preset configs (.eslintrc.* or package.json)

See the ESLint docs for more information about extending config files.

Note: Preset configs will also enable the correct parser options and environment.

Recommended config

This plugin exports a recommended config that enforces good practices.

{
	"name": "my-awesome-project",
	"eslintConfig": {
		"extends": "plugin:unicorn/recommended",
		"rules": {
			"unicorn/better-regex": "warn"
		}
	}
}

All config

This plugin exports an all config that makes use of all rules (except for deprecated ones).

{
	"name": "my-awesome-project",
	"eslintConfig": {
		"extends": "plugin:unicorn/all"
	}
}

Maintainers

Former

@yysmx/eslint-config@yysmx/eslint-config-basic@bridge-tools/config@d6stiny/eslint-config@lvyunlong/eslint-config@lvyunlong/eslint-config-basic@jcamp/eslint-config-basic@jbabin91/configs@jiqi/eslint-config@jiqi/eslint-config-basic@jiralite/eslint-config-neon@kaivanwong/eslint-config-base@rjqh/eslint-config-basic@rain-star/eslint-config-basic@cyenoch/eslint-config@sysdotini/eslint-config@asasinmode/eslint-config@hokify/eslint-config@ridedott/eslint-config@obvcloud/eslint-config-preset-basic@denverzh/eslint-config@denverzh/eslint-config-basetables-viewtable-maquantable-views@moka-test/test-confignoodles-normmobilelivedesignsystemreactreact-native-braveeslint-config-slickeslint-config-superstrictws-scriptseslint-config-quartz@martyncherry/eslint-configmetamo-eslint-configmetamo-lint-config@araclx/eslint@tapsellorg/eslint-angular-config@tribecamp/eslint@conten2/eslint-configform-viewsfilters-pack-test@sno2wman/eslint-config@psimk/porter-react-base-skeleton@psimk/porter-react-skeleton@psimk/porter-vue-skeletoneslint-config-sanches-testtaknepoidet-eslint-configeslint-config-refined@martynastell/build-configs@martynastell/eslint-configeslint-config-happyeslint-config-neaf@tomcarter17/eslint-config-typescript-react@nexhome/restrictionseslint-config-coobeet@darkobits/ts-unified@happ/eslint-config@happ/eslint-plugineslint-config-remedy@miszo/eslint-config@ywjt/mpa-builder@ywjt/spa-builder@ywjt/spa-m-buildereslint-config-matthis-libeslint-config-matthis-nodeeslint-config-matthis-webeslint-config-typical@praburangki/eslint-config-basic@beequeue/eslint-configeslint-plugin-ultimate-typescript-configeslint-config-imprintbreki-styleguides@vividcat/eslint-config-standard@leonzalion/eslint-config@leonzalion/eslintrcke-tools-lint@infrascript/config-eslint@zguolee/eslint-config-basic@ymkz/eslint-config@liuxy0551/eslint-config-dtstack-basic@nplus-cumt/eslint-config-basic@ventjs/eslint-config-basic@ixfe/eslint-config-basic@ts-terraform/config-eslint@configscript/config-eslint@silence94/eslint-config-basiceslint-config-jonyamo-baseeslint-config-martyncherryeslint-config-quark@jady/eslint-configopr-config@caryhu/eslint-config-basic@airbnb-config/eslint-config-base@kidwen/eslint-angularmichaelkohler-eslint-config-basegang-eslint-config@fellwork/eslint-config-core@fellwork/eslint-config-foreman@no_idea/eslint-config-basic
52.0.0

13 days ago

51.0.1

2 months ago

51.0.0

2 months ago

50.0.1

4 months ago

50.0.0

4 months ago

49.0.0

6 months ago

48.0.1

9 months ago

48.0.0

9 months ago

47.0.0

12 months ago

46.0.1

12 months ago

46.0.0

1 year ago

45.0.2

1 year ago

45.0.1

1 year ago

45.0.0

1 year ago

44.0.1

2 years ago

44.0.2

2 years ago

44.0.0

2 years ago

43.0.2

2 years ago

43.0.1

2 years ago

43.0.0

2 years ago

42.0.0

2 years ago

41.0.1

2 years ago

40.0.0

2 years ago

40.1.0

2 years ago

41.0.0

2 years ago

38.0.1

2 years ago

38.0.0

2 years ago

39.0.0

2 years ago

37.0.0

3 years ago

37.0.1

3 years ago

36.0.0

3 years ago

35.0.0

3 years ago

34.0.1

3 years ago

34.0.0

3 years ago

33.0.0

3 years ago

33.0.1

3 years ago

32.0.0

3 years ago

32.0.1

3 years ago

31.0.0

3 years ago

30.0.0

3 years ago

29.0.0

3 years ago

28.0.2

3 years ago

28.0.1

3 years ago

28.0.0

3 years ago

27.0.0

3 years ago

26.0.1

3 years ago

26.0.0

3 years ago

25.0.1

3 years ago

25.0.0

3 years ago

24.0.0

3 years ago

23.0.0

4 years ago

22.0.0

4 years ago

21.0.0

4 years ago

20.1.0

4 years ago

20.0.0

4 years ago

19.0.1

4 years ago

19.0.0

4 years ago

18.0.1

4 years ago

18.0.0

4 years ago

17.2.0

4 years ago

17.1.0

4 years ago

17.0.1

4 years ago

17.0.0

4 years ago

16.1.1

4 years ago

16.1.0

4 years ago

16.0.0

4 years ago

15.0.1

4 years ago

15.0.0

4 years ago

14.0.1

4 years ago

14.0.0

4 years ago

13.0.0

4 years ago

12.1.0

5 years ago

12.0.2

5 years ago

12.0.1

5 years ago

12.0.0

5 years ago

11.0.2

5 years ago

11.0.1

5 years ago

11.0.0

5 years ago

10.0.0

5 years ago

9.1.1

5 years ago

9.1.0

5 years ago

9.0.0

5 years ago

8.0.2

5 years ago

8.0.1

5 years ago

8.0.0

5 years ago

7.1.0

5 years ago

7.0.0

5 years ago

6.0.1

6 years ago

6.0.0

6 years ago

5.0.0

6 years ago

4.0.3

6 years ago

4.0.2

6 years ago

4.0.1

6 years ago

4.0.0

6 years ago

3.0.1

6 years ago

3.0.0

6 years ago

2.1.2

7 years ago

2.1.1

7 years ago

2.1.0

7 years ago

2.0.1

7 years ago

2.0.0

7 years ago

1.0.0

8 years ago