diff --git a/docs/src/_includes/partials/versions-list.html b/docs/src/_includes/partials/versions-list.html
index 4c01b52d81f..2e2fb2ff82a 100644
--- a/docs/src/_includes/partials/versions-list.html
+++ b/docs/src/_includes/partials/versions-list.html
@@ -1,5 +1,7 @@
diff --git a/docs/src/assets/css/components/accordion.css b/docs/src/assets/css/components/accordion.css
deleted file mode 100644
index 3b1c0758113..00000000000
--- a/docs/src/assets/css/components/accordion.css
+++ /dev/null
@@ -1,70 +0,0 @@
-.c-accordion__heading {
- font-size: var(--step-1);
- font-size: 1.125rem;
- font-weight: 600;
- font-family: var(--text-font);
- color: var(--headings-color); }
- .accordion-js .c-accordion__heading {
- margin: 0; }
- .c-accordion__heading > button {
- color: inherit;
- cursor: pointer;
- display: flex;
- align-items: baseline;
- justify-content: space-between;
- font: inherit;
- font-size: inherit;
- font-weight: 500;
- width: 100%;
- height: 100%;
- text-align: left;
- line-height: 1.5;
- padding: 0;
- border-radius: 0;
- position: relative;
- border: none;
- transition: outline 0.1s linear;
- margin-bottom: 2rem;
- margin-block-end: 2rem; }
- .c-accordion__heading > button[aria-expanded="true"] {
- margin-bottom: 0;
- margin-block-end: 0; }
- .c-accordion__heading > button svg {
- flex: none; }
-
-.c-accordion__panel {
- margin-bottom: 4rem;
- margin-block-end: 4rem; }
- .accordion-js .c-accordion__panel {
- margin-bottom: 0;
- margin-block-end: 0;
- padding: .5rem 0;
- padding-right: 3rem;
- padding-inline-end: 3rem; }
- .accordion-js .c-accordion__panel[aria-hidden="true"] {
- margin-bottom: 0;
- margin-block-end: 0; }
- .accordion-js .c-accordion__panel[aria-hidden="false"] {
- margin-bottom: 2rem;
- margin-block-end: 2rem; }
-
-/* Styles for the accordion icon */
-.c-accordion .accordion-icon {
- display: block !important;
- width: 0.75rem;
- height: 0.5rem;
- transform-origin: 50% 50%;
- margin-left: 3rem;
- margin-inline-start: 3rem;
- transition: all 0.1s linear;
- color: var(--color-neutral-400); }
-
-.c-accordion [aria-expanded="true"] .accordion-icon {
- -ms-transform: translateY(-50%) rotate(180deg);
- transform: translateY(-50%) rotate(180deg); }
-
-.c-accordion [aria-hidden="true"] {
- display: none; }
-
-.c-accordion [aria-hidden="false"] {
- display: block !important; }
diff --git a/docs/src/assets/css/components/alert.css b/docs/src/assets/css/components/alert.css
deleted file mode 100644
index 0fdff876347..00000000000
--- a/docs/src/assets/css/components/alert.css
+++ /dev/null
@@ -1,90 +0,0 @@
-.alert {
- position: relative;
- display: grid;
- grid-template-columns: auto 1fr;
- padding: 1rem;
- gap: .75rem;
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem;
- align-items: start;
- font-size: .875rem;
- background-color: var(--body-background-color);
- border-radius: var(--border-radius); }
- .alert.alert--warning {
- border: 1px solid var(--color-rose-300); }
- .alert.alert--important {
- border: 1px solid var(--color-warning-300); }
- .alert.alert--tip {
- border: 1px solid var(--color-success-300); }
-
-[data-theme="dark"] .alert.alert--warning {
- border: 1px solid var(--color-rose-300); }
-
-[data-theme="dark"] .alert.alert--important {
- border: 1px solid var(--color-warning-300); }
-
-[data-theme="dark"] .alert.alert--tip {
- border: 1px solid var(--color-success-300); }
-
-.alert__icon {
- color: inherit;
- position: relative;
- top: 2px;
- offset-block-start: 2px; }
-
-.alert__type {
- font-weight: 500;
- margin-bottom: .25rem;
- margin-block-end: .25rem; }
-
-.alert--warning {
- color: var(--color-rose-600); }
-
-.alert--important {
- color: var(--color-warning-600); }
-
-.alert--tip {
- color: var(--color-success-600); }
-
-[data-theme="dark"] .alert--warning {
- color: var(--color-rose-400); }
-
-[data-theme="dark"] .alert--important {
- color: var(--color-warning-400); }
-
-[data-theme="dark"] .alert--tip {
- color: var(--color-success-400); }
-
-.alert__type {
- font-weight: 500;
- margin-bottom: .25rem; }
- .alert--warning .alert__type {
- color: var(--color-rose-700); }
- [data-theme="dark"] .alert--warning .alert__type {
- color: var(--color-rose-300); }
- .alert--important .alert__type {
- color: var(--color-warning-700); }
- [data-theme="dark"] .alert--important .alert__type {
- color: var(--color-warning-300); }
- .alert--tip .alert__type {
- color: var(--color-success-700); }
- [data-theme="dark"] .alert--tip .alert__type {
- color: var(--color-success-300); }
-
-.alert__learn-more {
- display: block;
- font-weight: 500;
- margin-top: .75rem;
- margin-block-start: .75rem; }
- .alert--warning .alert__learn-more {
- color: var(--color-rose-700); }
- [data-theme="dark"] .alert--warning .alert__learn-more {
- color: var(--color-rose-300); }
- .alert--important .alert__learn-more {
- color: var(--color-warning-700); }
- [data-theme="dark"] .alert--important .alert__learn-more {
- color: var(--color-warning-300); }
- .alert--tip .alert__learn-more {
- color: var(--color-success-700); }
- [data-theme="dark"] .alert--tip .alert__learn-more {
- color: var(--color-success-300); }
diff --git a/docs/src/assets/css/components/breadcrumbs-min.css b/docs/src/assets/css/components/breadcrumbs-min.css
deleted file mode 100644
index 3cb0a60a70c..00000000000
--- a/docs/src/assets/css/components/breadcrumbs-min.css
+++ /dev/null
@@ -1,24 +0,0 @@
-nav.c-breadcrumbs ol {
- list-style: none;
- margin: 0;
- padding: 0; }
-
-nav.c-breadcrumbs li {
- display: inline-block;
- padding: 0.5em 0.25em;
- position: relative; }
- nav.c-breadcrumbs li::after {
- content: "/";
- color: inherit;
- display: inline-block;
- -webkit-margin-start: .5em;
- margin-inline-start: .5em; }
- nav.c-breadcrumbs li:last-of-type::after {
- display: none; }
- nav.c-breadcrumbs li a {
- font-weight: bold; }
- nav.c-breadcrumbs li a[aria-current] {
- color: inherit;
- text-decoration: none;
- background: none;
- font-weight: normal; }
diff --git a/docs/src/assets/css/components/breadcrumbs.css b/docs/src/assets/css/components/breadcrumbs.css
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/docs/src/assets/css/components/buttons.css b/docs/src/assets/css/components/buttons.css
deleted file mode 100644
index 5292111f095..00000000000
--- a/docs/src/assets/css/components/buttons.css
+++ /dev/null
@@ -1,61 +0,0 @@
-button {
- border: none;
- background: none;
- font: inherit;
- cursor: pointer;
- line-height: inherit;
- display: inline-flex;
- align-items: center;
- justify-content: center; }
-
-.c-btn {
- background: none;
- border: none;
- font: inherit;
- font-family: var(--text-font);
- cursor: pointer;
- line-height: inherit;
- font-weight: 500;
- font-size: var(--step-0);
- display: inline-flex;
- padding: .75em 1.125em;
- align-items: center;
- justify-content: center;
- border-radius: var(--border-radius);
- transition: background-color .2s linear, border-color .2s linear; }
- .c-btn svg {
- color: inherit; }
-
-.c-btn--large {
- font-size: 1.125rem;
- padding: .88em 1.5em; }
-
-.c-btn--block {
- display: flex;
- width: 100%; }
-
-a.c-btn {
- text-decoration: none;
- display: inline-flex;
- flex-wrap: wrap;
- gap: .5rem;
- align-items: center; }
-
-.c-btn--primary {
- background-color: var(--primary-button-background-color);
- color: var(--primary-button-text-color); }
- .c-btn--primary:hover {
- background-color: var(--primary-button-hover-color); }
-
-.c-btn--secondary {
- background-color: var(--secondary-button-background-color);
- color: var(--secondary-button-text-color);
- box-shadow: 0 1px 2px rgba(16, 24, 40, 0.1); }
- .c-btn--secondary:hover {
- background-color: var(--secondary-button-hover-color); }
-
-.c-btn--ghost {
- color: var(--body-text-color);
- border: 1px solid var(--border-color); }
- .c-btn--ghost:hover {
- border-color: var(--link-color); }
diff --git a/docs/src/assets/css/components/card.css b/docs/src/assets/css/components/card.css
deleted file mode 100644
index 40f0a6503a2..00000000000
--- a/docs/src/assets/css/components/card.css
+++ /dev/null
@@ -1,98 +0,0 @@
-.card {
- text-align: left;
- align-self: stretch;
- display: inline-flex;
- flex-direction: column;
- gap: 2rem;
- flex: none; }
-
-.blog-page .card:first-of-type,
-.card--featured {
- grid-column: 1 / -1;
- display: flex;
- flex-direction: row;
- flex-wrap: wrap; }
- @media all and (min-width: 1023px) {
- .blog-page .card:first-of-type,
- .card--featured {
- margin-bottom: var(--space-xl-2xl);
- margin-block-end: var(--space-xl-2xl); } }
- .blog-page .card:first-of-type .card__cover,
- .card--featured .card__cover {
- flex: 3 1 450px; }
- .blog-page .card:first-of-type .card__content,
- .card--featured .card__content {
- flex: 3 1 225px; }
-
-.card__cover {
- display: block; }
- .card__cover img {
- display: block;
- width: 100%;
- height: 100%;
- border-radius: var(--border-radius);
- object-fit: cover;
- aspect-ratio: 7 / 4; }
-
-.card__content {
- flex: 1;
- display: flex;
- flex-direction: column; }
-
-.card .card__title {
- margin-top: 0;
- margin-bottom: .5rem;
- margin-block-start: 0;
- margin-block-end: .5rem; }
- .card .card__title a {
- color: inherit;
- text-decoration: none; }
- .card .card__title a:hover {
- color: var(--link-color); }
-
-.card__teaser {
- margin-bottom: 2rem;
- margin-block-end: 2rem;
- font-size: var(--step-0); }
-
-.card__footer {
- justify-self: flex-end;
- display: grid;
- grid-template-columns: auto 1fr;
- grid-gap: .75rem; }
-
-.blog-post__author-photo {
- width: 2.5rem;
- height: 2.5rem;
- border-radius: 50%; }
-
-.blog-post__author-name {
- font-size: var(--step--1);
- line-height: 1.5;
- font-weight: 500;
- color: var(--headings-color); }
-
-.blog-post__publish-date {
- font-size: var(--step--1);
- line-height: 1.5; }
-
-.blog-post__category {
- background-color: var(--body-background-color);
- border-radius: 1rem; }
-
-.card .badge-group {
- margin-bottom: 1rem;
- margin-block-end: 1rem; }
-
-.badge-group {
- background-color: var(--lightest-background-color);
- color: var(--link-color);
- border-radius: 1rem;
- display: inline-flex;
- padding: .25rem;
- font-size: var(--step--1);
- flex: none;
- align-self: flex-start; }
- .badge-group span {
- display: inline-flex;
- padding: 0.125rem .5rem; }
diff --git a/docs/src/assets/css/components/docs-index.css b/docs/src/assets/css/components/docs-index.css
deleted file mode 100644
index 58fa7007634..00000000000
--- a/docs/src/assets/css/components/docs-index.css
+++ /dev/null
@@ -1,103 +0,0 @@
-.docs-index a {
- border-radius: var(--border-radius);
- text-decoration: none;
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: .5rem .75rem;
- margin-left: -.75rem;
- margin-inline-start: -.75rem;
- color: var(--headings-color); }
- .docs-index a:hover, .docs-index a[aria-current="true"] {
- background-color: var(--docs-lightest-background-color);
- color: var(--link-color); }
-
-.docs-index__item {
- margin: 0; }
- .docs-index__item ul ul {
- padding-left: .75rem; }
- .docs-index__item[data-has-children] {
- margin-bottom: .5rem; }
-
-.docs-index > ul > .docs-index__item {
- margin-top: 1.5rem;
- margin-block-start: 1.5rem; }
- .docs-index > ul > .docs-index__item > a {
- color: var(--icon-color);
- text-transform: uppercase;
- letter-spacing: 1px;
- font-size: .875rem;
- font-weight: 500; }
-
-/* Styles for the accordion icon */
-.index-js .index-icon {
- display: block !important;
- width: 0.75rem;
- height: 0.5rem;
- transform-origin: 50% 50%;
- transition: all 0.1s linear;
- color: inherit; }
-
-.index-js [aria-expanded="true"] .index-icon {
- -ms-transform: rotate(180deg);
- transform: rotate(180deg); }
-
-.index-js [aria-hidden="true"] {
- display: none; }
-
-.index-js [aria-hidden="false"] {
- display: block; }
-
-.docs-index__list[data-open="false"] {
- display: none; }
- @media all and (min-width: 1023px) {
- .docs-index__list[data-open="false"] {
- display: block; } }
-
-.docs-index__list[data-open="true"] {
- display: block; }
- @media all and (min-width: 1023px) {
- .docs-index__list[data-open="true"] {
- display: block; } }
-
-.docs-index-toggle {
- cursor: pointer;
- display: flex;
- width: 100%;
- padding: .75rem 1.125rem;
- align-items: center;
- justify-content: space-between;
- gap: .5rem;
- font-weight: 500;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- background-color: var(--secondary-button-background-color);
- color: var(--secondary-button-text-color);
- box-shadow: 0 1px 2px rgba(16, 24, 40, 0.1); }
- .docs-index-toggle:hover {
- background-color: var(--secondary-button-hover-color); }
- @media all and (min-width: 1023px) {
- .docs-index-toggle {
- display: none; } }
- .docs-index-toggle svg {
- width: 1.5em;
- height: 1.5em;
- color: inherit;
- fill: none;
- stroke-width: 4;
- stroke-linecap: round;
- stroke-linejoin: round; }
- .docs-index-toggle #ham-top,
- .docs-index-toggle #ham-middle,
- .docs-index-toggle #ham-bottom {
- transition: all .2s linear; }
- .docs-index-toggle #ham-top {
- transform-origin: 30px 37px; }
- .docs-index-toggle #ham-bottom {
- transform-origin: 30px 63px; }
- .docs-index-toggle[aria-expanded="true"] #ham-middle {
- opacity: 0; }
- .docs-index-toggle[aria-expanded="true"] #ham-top {
- transform: rotate(41deg); }
- .docs-index-toggle[aria-expanded="true"] #ham-bottom {
- transform: rotate(-41deg); }
diff --git a/docs/src/assets/css/components/docs-navigation.css b/docs/src/assets/css/components/docs-navigation.css
deleted file mode 100644
index f32aa044b2f..00000000000
--- a/docs/src/assets/css/components/docs-navigation.css
+++ /dev/null
@@ -1,102 +0,0 @@
-.docs-site-nav {
- display: flex;
- flex-direction: column;
- flex: 1;
- grid-column: 1 / -1;
- grid-row: 1; }
- .docs-site-nav ul {
- list-style: none;
- font-size: var(--step-1);
- margin-top: 1rem;
- margin-block-start: 1rem;
- margin-bottom: 2rem;
- margin-block-end: 2rem; }
- @media all and (min-width: 1023px) {
- .docs-site-nav ul {
- font-size: var(--step-0);
- margin-top: 0;
- margin-block-start: 0;
- margin-bottom: 0;
- margin-block-end: 0;
- align-items: center;
- display: flex; } }
- .docs-site-nav .flexer {
- display: flex;
- justify-self: flex-end;
- align-self: flex-end; }
- .docs-site-nav a:not(.c-btn) {
- text-decoration: none;
- color: inherit;
- transition: color .2s linear; }
- .docs-site-nav a:not(.c-btn):hover {
- color: var(--link-color); }
- .docs-site-nav a:not(.c-btn)[aria-current="page"],
- .docs-site-nav a:not(.c-btn)[aria-current="true"] {
- color: var(--link-color);
- text-decoration: none;
- font-weight: 500; }
-
-@media all and (min-width: 1023px) {
- .docs-nav-panel {
- display: flex;
- flex-direction: row;
- justify-content: center; } }
-
-.docs-nav-panel[data-open="false"] {
- display: none; }
-
-@media all and (min-width: 1023px) {
- .docs-nav-panel[data-open="true"] {
- display: flex;
- flex-direction: row;
- justify-content: center; } }
-
-@media all and (min-width: 1023px) {
- .docs-nav-panel .mobile-only {
- display: none; } }
-
-.docs-site-nav-toggle {
- cursor: pointer;
- display: inline-flex;
- align-items: center;
- margin-left: .5rem;
- margin-right: -10px;
- margin-inline-start: .5rem;
- margin-inline-end: -10px; }
- .docs-site-nav-toggle svg {
- width: 40px;
- height: 40px;
- color: var(--headings-color);
- fill: none;
- stroke-width: 4;
- stroke-linecap: round;
- stroke-linejoin: round; }
- .docs-site-nav-toggle #ham-top,
- .docs-site-nav-toggle #ham-middle,
- .docs-site-nav-toggle #ham-bottom {
- transition: all .2s linear; }
- .docs-site-nav-toggle #ham-top {
- transform-origin: 30px 37px; }
- .docs-site-nav-toggle #ham-bottom {
- transform-origin: 30px 63px; }
- .docs-site-nav-toggle[aria-expanded="true"] #ham-middle {
- opacity: 0; }
- .docs-site-nav-toggle[aria-expanded="true"] #ham-top {
- transform: rotate(41deg); }
- .docs-site-nav-toggle[aria-expanded="true"] #ham-bottom {
- transform: rotate(-41deg); }
-
-@media all and (min-width: 1023px) {
- .docs-site-nav {
- flex-direction: row;
- grid-column: auto;
- gap: 2rem; }
- .docs-site-nav ul {
- display: flex;
- gap: 2rem;
- font-size: var(--step-0); }
- .docs-site-nav ul li {
- margin-bottom: 0;
- margin-block-end: 0; }
- .docs-site-nav .flexer {
- order: 1; } }
diff --git a/docs/src/assets/css/components/docs-resources.css b/docs/src/assets/css/components/docs-resources.css
deleted file mode 100644
index dd8f8a41c0f..00000000000
--- a/docs/src/assets/css/components/docs-resources.css
+++ /dev/null
@@ -1,55 +0,0 @@
-.resource {
- display: flex;
- border-radius: var(--border-radius);
- border: 1px solid var(--divider-color);
- background-color: var(--lightest-background-color);
- align-items: stretch;
- overflow: hidden;
- margin-bottom: .5rem;
- margin-block-end: .5rem;
- position: relative;
- transition: all .2s linear; }
- .resource:hover {
- background-color: var(--lighter-background-color); }
-
-.resource__image {
- flex: 1 0 5.5rem;
- max-width: 5.5rem;
- overflow: hidden;
- padding: .25rem; }
- .resource__image img {
- display: block;
- height: 100%;
- width: 100%;
- object-fit: contain; }
-
-.resource__content {
- flex: 4;
- padding: .75rem;
- align-self: center; }
-
-.resource__title {
- text-decoration: none;
- color: var(--headings-color);
- font-weight: 500;
- margin-bottom: .125rem; }
- .resource__title::after {
- content: "";
- position: absolute;
- left: 0;
- offset-inline-start: 0;
- top: 0;
- block-inline-start: 0;
- width: 100%;
- height: 100%; }
-
-.resource__domain,
-.resource__domain a {
- text-decoration: none;
- color: var(--body-text-color);
- font-size: .875rem; }
-
-.resource__icon {
- color: var(--headings-color);
- margin: 1rem;
- align-self: center; }
diff --git a/docs/src/assets/css/components/donations.css b/docs/src/assets/css/components/donations.css
deleted file mode 100644
index 6273c1c97c1..00000000000
--- a/docs/src/assets/css/components/donations.css
+++ /dev/null
@@ -1,198 +0,0 @@
-.donations-title {
- font-size: inherit;
- color: inherit;
- font: inherit;
- text-align: center;
- margin-top: var(--space-l-2xl);
- margin-block-start: var(--space-l-2xl); }
-
-ul.donations-list {
- margin-top: var(--space-l-2xl);
- display: grid;
- grid-gap: 0 2rem;
- grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
- margin-bottom: 0;
- margin-block-end: 0;
- align-items: stretch; }
- ul.donations-list .donations-item {
- display: flex;
- margin-bottom: 2rem;
- margin-block-end: 2rem; }
-
-.donation {
- width: 100%;
- height: 100%;
- font-size: var(--step--1);
- flex: none;
- border-radius: var(--border-radius);
- padding: 1rem;
- background-color: var(--lightest-background-color);
- display: grid;
- grid-gap: 1.5rem 2rem;
- grid-template-columns: auto 1fr 0;
- grid-template-rows: auto 1fr 0;
- align-items: end; }
- @media all and (min-width: 1023px) {
- .donation {
- align-items: center;
- grid-template-columns: auto 1fr auto; } }
-
-.donation__sponsor-name {
- color: var(--headings-color);
- font-weight: 500; }
-
-.donation__content {
- grid-column: 1 / -1; }
-
-.donation__amount {
- grid-column: 3 / 4;
- grid-row: 1;
- justify-self: end;
- white-space: nowrap; }
-
-.donation__sponsor-name,
-.donation__date {
- margin-bottom: 0;
- margin-block-end: 0; }
-
-.donation__sponsor-logo {
- width: 2.5rem;
- height: 2.5rem;
- object-fit: cover;
- border-radius: var(--border-radius); }
-
-.donation-plan {
- border: 1px solid var(--divider-color);
- border-radius: var(--border-radius);
- margin-bottom: 2rem;
- box-shadow: var(--shadow-lg); }
-
-.donation-plan__header {
- display: grid;
- grid-template-columns: auto 1fr;
- align-items: start;
- grid-gap: 1.5rem;
- padding: 2rem 2rem 1.5rem; }
- @media all and (max-width: 640px) {
- .donation-plan__header img {
- width: 3rem; } }
-
-ul.donation-plan__features li {
- margin-bottom: 1rem;
- margin-block-start: 1rem;
- display: flex;
- align-items: start; }
- ul.donation-plan__features li .c-icon {
- width: 1.5rem;
- height: 1.5rem;
- margin-right: .75rem;
- margin-inline-end: .75rem; }
-
-.donation-plan__platform-name {
- margin-bottom: .25rem;
- margin-block-end: .25rem;
- font-size: var(--step-2); }
-
-.donation-plan__description {
- margin-bottom: 0;
- margin-block-end: 0; }
-
-.donation-plan__footer .c-btn {
- align-items: c; }
- .donation-plan__footer .c-btn svg {
- margin-top: -.1rem;
- margin-block-start: -.1rem; }
-
-ul.donation-plan__features,
-.donation-plan__footer {
- padding: 2rem; }
-
-.donation-plan__header {
- padding: 2rem 2rem 1.5rem; }
-
-@media all and (max-width: 640px) {
- ul.donation-plan__features,
- .donation-plan__footer {
- padding: 2rem 1rem; }
- .donation-plan__header {
- padding: 2rem 1rem 1.5rem; } }
-
-.donation-tiers {
- list-style: none;
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
- grid-gap: 2rem;
- margin: 0;
- padding: 0; }
-
-.donation-tiers__item {
- display: grid;
- grid-template-rows: auto 1fr auto;
- grid-gap: 2rem;
- padding: 2rem;
- margin-bottom: 2rem;
- margin-block-end: 2rem;
- box-shadow: var(--shadow-lg);
- border-radius: var(--border-radius);
- border: 1px solid var(--divider-color); }
- @media all and (max-width: 640px) {
- .donation-tiers__item {
- padding: 2rem 1rem; } }
- .donation-tiers__item .c-btn {
- text-align: center;
- font-size: .875rem; }
- .donation-tiers__item .c-btn--block:not(:last-of-type) {
- margin-bottom: 1rem;
- margin-block-end: 1rem; }
- .donation-tiers__item.all-others {
- all: inherit;
- display: block;
- grid-column: -1 / 1;
- text-align: center; }
-
-.donation-tiers__title {
- margin: 0;
- color: var(--link-color);
- font-size: var(--step-0);
- text-align: center;
- font-family: var(--text-font);
- font-weight: normal; }
- .donation-tiers__title span {
- display: block;
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
- .all-others .donation-tiers__title {
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
- .all-others .donation-tiers__title span {
- font-weight: 500;
- display: inline; }
-
-.donation-tiers__title__value {
- color: var(--headings-color);
- font-size: var(--step-3);
- font-family: var(--display-font); }
- .all-others .donation-tiers__title__value {
- all: inherit; }
-
-.donation-tiers__title__freq {
- color: var(--body-text-color);
- font-weight: 400; }
- .all-others .donation-tiers__title__freq {
- all: inherit; }
-
-.donation-tiers__item__description {
- justify-self: baseline;
- margin-bottom: 2rem;
- margin-block-end: 2rem; }
-
-.donation-tiers--others {
- text-align: center;
- margin-top: var(--space-l-2xl);
- margin-block-start: var(--space-l-2xl); }
- .donation-tiers--others p {
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
- .donation-tiers--others .c-btn {
- margin-top: 1rem;
- margin-block-start: 1rem; }
diff --git a/docs/src/assets/css/components/hero.css b/docs/src/assets/css/components/hero.css
deleted file mode 100644
index ecb27abf059..00000000000
--- a/docs/src/assets/css/components/hero.css
+++ /dev/null
@@ -1,43 +0,0 @@
-@media all and (min-width: 800px) {
- .hero .grid {
- display: grid;
- grid-template-columns: 2fr 1fr;
- grid-gap: 2rem;
- align-items: center; } }
-
-.hero .grid .span-1-7 {
- grid-column: 1 / 2; }
-
-.hero .grid .span-10-12 {
- grid-column: 2 / 3;
- justify-self: end; }
-
-.hero {
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color);
- background-color: var(--hero-background-color); }
- @media all and (min-width: 800px) {
- .hero {
- min-height: calc(285px + var(--space-xl-4xl)); } }
- .hero .content-container {
- padding: var(--space-xl-4xl) 0;
- margin: 0; }
- .hero > .content-container {
- margin: 0 auto;
- padding: 0 calc(1rem + 1vw);
- padding-bottom: 0;
- align-items: center; }
-
-.hero--homepage .section-title {
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem; }
-
-.hero--homepage .section-supporting-text {
- margin: 0;
- font-size: var(--step-1);
- text-align: left; }
-
-.hero--homepage .eslint-actions {
- font-size: var(--step-1);
- margin-top: 3rem;
- margin-block-start: 3rem; }
diff --git a/docs/src/assets/css/components/homepage-hero.css b/docs/src/assets/css/components/homepage-hero.css
deleted file mode 100644
index 815fd9e9f3c..00000000000
--- a/docs/src/assets/css/components/homepage-hero.css
+++ /dev/null
@@ -1,174 +0,0 @@
-.problems {
- display: inline-block;
- position: relative; }
-
-.eslint-actions {
- display: inline-flex;
- flex-wrap: wrap;
- flex-direction: column;
- width: 100%;
- gap: 1rem; }
- @media all and (min-width: 640px) {
- .eslint-actions {
- flex-direction: row; } }
-
-.eslint-install-code-wrapper {
- position: relative; }
-
-.eslint-install-code {
- display: inline-flex;
- align-items: center;
- gap: 1rem;
- background-color: var(--lightest-background-color);
- border-radius: var(--border-radius);
- border: 1px solid var(--divider-color);
- padding: .75rem 1.25rem .75rem 1rem;
- white-space: nowrap;
- margin-top: 1.5rem;
- margin-block-start: 1.5rem;
- overflow-x: auto;
- max-width: 100%;
- color: var(--headings-color); }
- [data-theme="dark"] .eslint-install-code {
- background-color: var(--color-neutral-700); }
- .eslint-install-code code {
- color: var(--headings-color); }
- .eslint-install-code input {
- all: unset;
- min-width: 30ch;
- color: inherit;
- font-family: var(--mono-font); }
- .eslint-install-code input::selection {
- background-color: #fff;
- color: var(--body-text-color); }
-
-.eslint-install-code__btn .c-icon {
- color: var(--body-text-color); }
-
-.eslint-install-code__btn:hover .c-icon, .eslint-install-code__btn:focus .c-icon, .eslint-install-code__btn:active .c-icon {
- color: var(--link-color); }
-
-.eslint-install-code__btn[data-copied="true"] .c-icon {
- color: var(--link-color); }
-
-.eslint-install-code__announcement {
- font-size: .875rem;
- padding: .25rem .75rem;
- font-size: var(--step--1);
- border-radius: var(--border-radius);
- display: block;
- position: absolute;
- top: calc(100% + .5rem);
- offset-block-start: calc(100% + .5rem);
- transition: opacity 1s linear 3s; }
- .eslint-install-code__announcement[data-fades-out] {
- opacity: 0; }
-
-.eslint-versions-col {
- display: flex;
- flex-direction: column; }
- @media all and (min-width: 1023px) {
- .eslint-versions-col {
- align-items: flex-end; } }
-
-.eslint-versions {
- margin-top: 3rem;
- margin-block-start: 3rem;
- display: inline-flex;
- flex-direction: column; }
- .eslint-versions dt {
- border-bottom: 1px solid var(--divider-color);
- padding: .25em 0;
- margin-bottom: .5em;
- padding-right: 1rem;
- border-block-end: 1px solid var(--divider-color);
- padding: .25em 0;
- margin-block-end: .5em;
- padding-inline-end: 1rem; }
- .eslint-versions dd {
- margin-left: 0;
- margin-bottom: 1rem;
- padding-right: 1rem;
- margin-inline-start: 0;
- margin-block-end: 1rem;
- padding-inline-end: 1rem; }
- .eslint-versions .c-icon {
- margin-right: .5rem;
- margin-inline-end: .5rem; }
-
-/* homepage metrics section */
-.metrics {
- background-color: var(--lightest-background-color);
- color: var(--link-color);
- font-size: 1.125rem;
- border-radius: var(--border-radius);
- padding: var(--space-l-2xl); }
- @media all and (min-width: 768px) {
- .metrics {
- display: flex; } }
-
-.metrics__item {
- flex: 1;
- display: block;
- flex-wrap: wrap;
- align-items: center;
- justify-content: center;
- padding: 1rem; }
-
-.metrics__value {
- display: block;
- font-size: var(--step-6);
- line-height: 1;
- font-family: var(--mono-font);
- flex: 9999;
- margin-bottom: .75rem;
- margin-block-end: .75rem; }
-
-/* Homepage Features Section */
-.features-wrapper.grid {
- align-items: center; }
-
-.features {
- border-left: 4px solid var(--lighter-background-color);
- padding-left: 1.5rem;
- border-inline-start: 4px solid var(--lighter-background-color);
- padding-inline-start: 1.5rem; }
-
-.feature {
- padding: 2rem 0; }
- .feature:not(:last-of-type) {
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color); }
- .donate-page .feature {
- border-bottom: none;
- border-block-end: none; }
-
-.feature__title {
- font-size: var(--step-1);
- font-family: var(--text-font);
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
-
-.feature__description {
- margin-bottom: 1.25rem;
- margin-block-end: 1.25rem; }
-
-.feature__details-link {
- display: flex;
- gap: .5rem;
- align-items: center;
- text-decoration: none; }
- .feature__details-link:hover {
- text-decoration: underline; }
-
-.features-image {
- display: none; }
- .features-image img {
- margin: 2rem auto; }
- .donate-page .features-image img {
- overflow: hidden;
- display: block;
- border-radius: var(--border-radius); }
- @media all and (min-width: 1023px) {
- .features-image {
- display: block; } }
diff --git a/docs/src/assets/css/components/homepage.css b/docs/src/assets/css/components/homepage.css
deleted file mode 100644
index 815fd9e9f3c..00000000000
--- a/docs/src/assets/css/components/homepage.css
+++ /dev/null
@@ -1,174 +0,0 @@
-.problems {
- display: inline-block;
- position: relative; }
-
-.eslint-actions {
- display: inline-flex;
- flex-wrap: wrap;
- flex-direction: column;
- width: 100%;
- gap: 1rem; }
- @media all and (min-width: 640px) {
- .eslint-actions {
- flex-direction: row; } }
-
-.eslint-install-code-wrapper {
- position: relative; }
-
-.eslint-install-code {
- display: inline-flex;
- align-items: center;
- gap: 1rem;
- background-color: var(--lightest-background-color);
- border-radius: var(--border-radius);
- border: 1px solid var(--divider-color);
- padding: .75rem 1.25rem .75rem 1rem;
- white-space: nowrap;
- margin-top: 1.5rem;
- margin-block-start: 1.5rem;
- overflow-x: auto;
- max-width: 100%;
- color: var(--headings-color); }
- [data-theme="dark"] .eslint-install-code {
- background-color: var(--color-neutral-700); }
- .eslint-install-code code {
- color: var(--headings-color); }
- .eslint-install-code input {
- all: unset;
- min-width: 30ch;
- color: inherit;
- font-family: var(--mono-font); }
- .eslint-install-code input::selection {
- background-color: #fff;
- color: var(--body-text-color); }
-
-.eslint-install-code__btn .c-icon {
- color: var(--body-text-color); }
-
-.eslint-install-code__btn:hover .c-icon, .eslint-install-code__btn:focus .c-icon, .eslint-install-code__btn:active .c-icon {
- color: var(--link-color); }
-
-.eslint-install-code__btn[data-copied="true"] .c-icon {
- color: var(--link-color); }
-
-.eslint-install-code__announcement {
- font-size: .875rem;
- padding: .25rem .75rem;
- font-size: var(--step--1);
- border-radius: var(--border-radius);
- display: block;
- position: absolute;
- top: calc(100% + .5rem);
- offset-block-start: calc(100% + .5rem);
- transition: opacity 1s linear 3s; }
- .eslint-install-code__announcement[data-fades-out] {
- opacity: 0; }
-
-.eslint-versions-col {
- display: flex;
- flex-direction: column; }
- @media all and (min-width: 1023px) {
- .eslint-versions-col {
- align-items: flex-end; } }
-
-.eslint-versions {
- margin-top: 3rem;
- margin-block-start: 3rem;
- display: inline-flex;
- flex-direction: column; }
- .eslint-versions dt {
- border-bottom: 1px solid var(--divider-color);
- padding: .25em 0;
- margin-bottom: .5em;
- padding-right: 1rem;
- border-block-end: 1px solid var(--divider-color);
- padding: .25em 0;
- margin-block-end: .5em;
- padding-inline-end: 1rem; }
- .eslint-versions dd {
- margin-left: 0;
- margin-bottom: 1rem;
- padding-right: 1rem;
- margin-inline-start: 0;
- margin-block-end: 1rem;
- padding-inline-end: 1rem; }
- .eslint-versions .c-icon {
- margin-right: .5rem;
- margin-inline-end: .5rem; }
-
-/* homepage metrics section */
-.metrics {
- background-color: var(--lightest-background-color);
- color: var(--link-color);
- font-size: 1.125rem;
- border-radius: var(--border-radius);
- padding: var(--space-l-2xl); }
- @media all and (min-width: 768px) {
- .metrics {
- display: flex; } }
-
-.metrics__item {
- flex: 1;
- display: block;
- flex-wrap: wrap;
- align-items: center;
- justify-content: center;
- padding: 1rem; }
-
-.metrics__value {
- display: block;
- font-size: var(--step-6);
- line-height: 1;
- font-family: var(--mono-font);
- flex: 9999;
- margin-bottom: .75rem;
- margin-block-end: .75rem; }
-
-/* Homepage Features Section */
-.features-wrapper.grid {
- align-items: center; }
-
-.features {
- border-left: 4px solid var(--lighter-background-color);
- padding-left: 1.5rem;
- border-inline-start: 4px solid var(--lighter-background-color);
- padding-inline-start: 1.5rem; }
-
-.feature {
- padding: 2rem 0; }
- .feature:not(:last-of-type) {
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color); }
- .donate-page .feature {
- border-bottom: none;
- border-block-end: none; }
-
-.feature__title {
- font-size: var(--step-1);
- font-family: var(--text-font);
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
-
-.feature__description {
- margin-bottom: 1.25rem;
- margin-block-end: 1.25rem; }
-
-.feature__details-link {
- display: flex;
- gap: .5rem;
- align-items: center;
- text-decoration: none; }
- .feature__details-link:hover {
- text-decoration: underline; }
-
-.features-image {
- display: none; }
- .features-image img {
- margin: 2rem auto; }
- .donate-page .features-image img {
- overflow: hidden;
- display: block;
- border-radius: var(--border-radius); }
- @media all and (min-width: 1023px) {
- .features-image {
- display: block; } }
diff --git a/docs/src/assets/css/components/index.css b/docs/src/assets/css/components/index.css
deleted file mode 100644
index 6c913882142..00000000000
--- a/docs/src/assets/css/components/index.css
+++ /dev/null
@@ -1,74 +0,0 @@
-.index {
- margin-bottom: 4rem;
- margin-block-end: 4rem; }
-
-.index__item {
- margin: 0; }
- .index__item a {
- display: block;
- color: inherit;
- text-decoration: none;
- padding: .625rem .875rem;
- font-size: var(--step-0);
- border-radius: var(--border-radius); }
- .index__item a:hover {
- color: var(--link-color); }
- .index__item a[aria-current="page"] {
- color: var(--link-color);
- background-color: var(--lightest-background-color);
- font-weight: 500; }
-
-.index__toggle {
- cursor: pointer;
- display: flex;
- width: 100%;
- padding: .75rem 1.125rem;
- align-items: center;
- justify-content: space-between;
- gap: .5rem;
- font-weight: 500;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- background-color: var(--secondary-button-background-color);
- color: var(--secondary-button-text-color);
- box-shadow: 0 1px 2px rgba(16, 24, 40, 0.1); }
- .index__toggle:hover {
- background-color: var(--secondary-button-hover-color); }
- @media all and (min-width: 1023px) {
- .index__toggle {
- display: none; } }
- .index__toggle svg {
- width: 1.5em;
- height: 1.5em;
- color: inherit;
- fill: none;
- stroke-width: 4;
- stroke-linecap: round;
- stroke-linejoin: round; }
- .index__toggle #ham-top,
- .index__toggle #ham-middle,
- .index__toggle #ham-bottom {
- transition: all .2s linear; }
- .index__toggle #ham-top {
- transform-origin: 30px 37px; }
- .index__toggle #ham-bottom {
- transform-origin: 30px 63px; }
- .index__toggle[aria-expanded="true"] #ham-middle {
- opacity: 0; }
- .index__toggle[aria-expanded="true"] #ham-top {
- transform: rotate(41deg); }
- .index__toggle[aria-expanded="true"] #ham-bottom {
- transform: rotate(-41deg); }
-
-.index__list {
- display: block; }
- .index__list[data-open="false"] {
- display: none; }
- @media all and (min-width: 1023px) {
- .index__list[data-open="false"] {
- display: block; } }
- .index__list[data-open="true"] {
- display: block; }
- @media all and (min-width: 1023px) {
- .index__list[data-open="true"] {
- display: block; } }
diff --git a/docs/src/assets/css/components/language-switcher.css b/docs/src/assets/css/components/language-switcher.css
deleted file mode 100644
index 0edff38e349..00000000000
--- a/docs/src/assets/css/components/language-switcher.css
+++ /dev/null
@@ -1,18 +0,0 @@
-.switcher--language {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: .25rem .5rem;
- position: relative;
- min-width: 15rem;
- padding: 0; }
-
-.switcher--language .label__text {
- flex: 1 0 10ch; }
-
-.switcher--language .switcher__select {
- min-width: 15rem;
- flex: 1 0 15rem; }
-
-.language-switcher {
- display: inline-flex; }
diff --git a/docs/src/assets/css/components/languages.css b/docs/src/assets/css/components/languages.css
deleted file mode 100644
index 6ab22050a85..00000000000
--- a/docs/src/assets/css/components/languages.css
+++ /dev/null
@@ -1,38 +0,0 @@
-@charset "UTF-8";
-.languages-list {
- margin: 0;
- padding: 0;
- font-size: var(--step-0); }
- .languages-list li {
- margin: 0; }
- .languages-list li:last-of-type a {
- border-bottom: 0; }
- .languages-list a {
- color: inherit;
- display: block;
- width: 100%;
- padding: .75rem .1rem;
- text-decoration: none;
- display: flex;
- align-items: center;
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color); }
- .languages-list a[aria-current="true"] {
- font-weight: 500;
- color: var(--link-color); }
- .languages-list a[aria-current="true"]::after {
- content: "✔️"; }
- .languages-list a:hover {
- color: var(--link-color); }
-
-.languages-section .flag {
- font-size: 2em;
- margin-right: .5rem;
- margin-inline-end: .5rem; }
-
-.languages-section .languages-list {
- font-size: var(--step-1);
- border-left: 4px solid var(--tab-border-color);
- padding-left: 1rem;
- border-inline-start: 4px solid var(--tab-border-color);
- padding-inline-start: 1rem; }
diff --git a/docs/src/assets/css/components/navigation-min.css b/docs/src/assets/css/components/navigation-min.css
deleted file mode 100644
index 98e6312736a..00000000000
--- a/docs/src/assets/css/components/navigation-min.css
+++ /dev/null
@@ -1,5 +0,0 @@
-.site-nav ul {
- display: -webkit-flex;
- display: flex;
- gap: 1em;
- list-style: none; }
diff --git a/docs/src/assets/css/components/navigation.css b/docs/src/assets/css/components/navigation.css
deleted file mode 100644
index 8d24c73d952..00000000000
--- a/docs/src/assets/css/components/navigation.css
+++ /dev/null
@@ -1,84 +0,0 @@
-.site-nav {
- display: flex;
- flex-direction: column;
- flex: 1;
- grid-column: 1 / -1;
- grid-row: 1; }
- .site-nav ul {
- list-style: none;
- font-size: var(--step-1);
- margin-top: 1rem;
- margin-block-start: 1rem; }
- @media all and (min-width: 680px) {
- .site-nav ul {
- font-size: var(--step-0);
- margin-top: 0;
- margin-block-start: 0;
- align-items: center;
- display: flex; } }
- .site-nav ul[data-open="false"] {
- display: none; }
- @media all and (min-width: 680px) {
- .site-nav ul[data-open="true"] {
- display: flex; } }
- .site-nav .flexer {
- display: flex;
- justify-self: flex-end;
- align-self: flex-end; }
- .site-nav a:not(.c-btn) {
- text-decoration: none;
- color: inherit;
- transition: color .2s linear; }
- .site-nav a:not(.c-btn):hover {
- color: var(--link-color); }
- .site-nav a:not(.c-btn)[data-current="page"],
- .site-nav a:not(.c-btn)[data-current="true"] {
- color: var(--link-color);
- text-decoration: none;
- font-weight: 500; }
-
-.site-nav-toggle {
- cursor: pointer;
- display: inline-flex;
- align-items: center;
- margin-left: .5rem;
- margin-right: -10px;
- margin-inline-start: .5rem;
- margin-inline-end: -10px; }
- .site-nav-toggle svg {
- width: 40px;
- height: 40px;
- color: var(--headings-color);
- fill: none;
- stroke-width: 4;
- stroke-linecap: round;
- stroke-linejoin: round; }
- .site-nav-toggle #ham-top,
- .site-nav-toggle #ham-middle,
- .site-nav-toggle #ham-bottom {
- transition: all .2s linear; }
- .site-nav-toggle #ham-top {
- transform-origin: 30px 37px; }
- .site-nav-toggle #ham-bottom {
- transform-origin: 30px 63px; }
- .site-nav-toggle[aria-expanded="true"] #ham-middle {
- opacity: 0; }
- .site-nav-toggle[aria-expanded="true"] #ham-top {
- transform: rotate(41deg); }
- .site-nav-toggle[aria-expanded="true"] #ham-bottom {
- transform: rotate(-41deg); }
-
-@media all and (min-width: 680px) {
- .site-nav {
- flex-direction: row;
- grid-column: auto;
- gap: 2rem; }
- .site-nav ul {
- display: flex;
- gap: 2rem;
- font-size: var(--step-0); }
- .site-nav ul li {
- margin-bottom: 0;
- margin-block-end: 0; }
- .site-nav .flexer {
- order: 1; } }
diff --git a/docs/src/assets/css/components/pagination-min.css b/docs/src/assets/css/components/pagination-min.css
deleted file mode 100644
index 7a083d8a54a..00000000000
--- a/docs/src/assets/css/components/pagination-min.css
+++ /dev/null
@@ -1,23 +0,0 @@
-/* Pagination within (and between) individual posts */
-.c-post-pagination ul {
- list-style: none;
- width: 100%;
- outline: 1px solid yellow;
- display: -webkit-flex;
- display: flex;
- -webkit-align-items: flex-start;
- align-items: flex-start; }
-
-.c-post-pagination li {
- -webkit-flex: 1;
- flex: 1;
- display: -webkit-flex;
- display: flex; }
-
-.c-post-pagination a {
- display: block;
- padding: .5em; }
-
-/* Pagination on collection pages */
-.c-collection-pagination {
- outline: 1px solid yellow; }
diff --git a/docs/src/assets/css/components/pagination.css b/docs/src/assets/css/components/pagination.css
deleted file mode 100644
index 981803e3a53..00000000000
--- a/docs/src/assets/css/components/pagination.css
+++ /dev/null
@@ -1,57 +0,0 @@
-nav.c-pagination {
- display: flex;
- justify-content: space-between;
- flex-wrap: wrap;
- gap: 1rem; }
- nav.c-pagination svg {
- color: inherit; }
- nav.c-pagination a {
- color: var(--headings-color);
- text-decoration: none; }
-
-.c-pagination__item {
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- padding: .5rem .875rem;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- line-height: 1;
- gap: .5rem;
- transition: all .1s linear; }
- .c-pagination__item:hover {
- border-color: var(--link-color); }
- .c-pagination__item[aria-disabled] {
- color: var(--body-text-color);
- border-color: var(--divider-color); }
- .c-pagination__item[aria-disabled]:hover {
- border-color: var(--divider-color); }
-
-.c-pagination__prev {
- order: 1;
- display: flex;
- gap: .5rem; }
-
-.c-pagination__next {
- order: 3;
- display: flex;
- gap: .5rem; }
-
-.c-pagination__current {
- border: none;
- order: 2;
- margin: auto; }
- @media all and (max-width: 480px) {
- .c-pagination__current {
- display: none; } }
-
-@media all and (max-width: 640px) {
- .c-pagination__item__text {
- /* visually-hide */
- clip: rect(0 0 0 0);
- clip-path: inset(100%);
- height: 1px;
- overflow: hidden;
- position: absolute;
- width: 1px;
- white-space: nowrap; } }
diff --git a/docs/src/assets/css/components/person.css b/docs/src/assets/css/components/person.css
deleted file mode 100644
index 4d3dd7247e7..00000000000
--- a/docs/src/assets/css/components/person.css
+++ /dev/null
@@ -1,98 +0,0 @@
-/* PERSON */
-.person {
- position: relative; }
-
-.person--contributor {
- display: grid;
- grid-template-columns: auto 1fr;
- align-items: start;
- gap: .75rem; }
-
-.person--author {
- margin-bottom: 3rem;
- margin-block-end: 3rem; }
- @media all and (min-width: 680px) {
- .person--author {
- display: grid;
- grid-template-columns: 1fr 2fr;
- grid-gap: 3rem; } }
-
-.person--author__details {
- display: grid;
- grid-template-columns: auto 1fr;
- align-items: start;
- gap: .75rem; }
-
-.person__photo {
- display: block;
- border-radius: 50%;
- object-fit: cover;
- flex: none;
- max-width: initial;
- margin-bottom: .875rem;
- margin-block-end: .875rem;
- /* contributor in the post sidebar */ }
- .person__photo.person__photo--large {
- width: 5rem;
- height: 5rem;
- margin-bottom: 1.25rem;
- margin-block-end: 1.25rem; }
- .person__photo.person__photo--medium {
- width: 3.5rem;
- height: 3.5rem; }
- .person__photo.person__photo--small {
- width: 3rem;
- height: 3rem; }
- .post__sidebar-module .person__photo {
- width: 3rem;
- height: 3rem; }
-
-.person__bio a:hover {
- color: var(--link-color); }
-
-.person__name {
- font-weight: 500;
- color: var(--headings-color);
- font-size: 1.125rem; }
- .post .person__name {
- font-size: var(--step-0); }
-
-.person__handle {
- text-decoration: none;
- color: var(--link-color);
- display: block;
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
- .post .person__handle {
- color: inherit; }
- .post .person__handle:hover {
- color: var(--link-color); }
- .post__sidebar-module .person__handle::after {
- content: "";
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- offset-block-start: 0;
- offset-block-end: 0;
- offset-inline-start: 0;
- offset-inline-end: 0; }
-
-.person__title {
- display: block;
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
-
-.person__social-links ul {
- margin: 0;
- padding: 0;
- list-style: none;
- display: flex;
- gap: 1rem; }
-
-/* team page */
-.people-list {
- display: grid;
- grid-gap: 3rem 2rem;
- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
diff --git a/docs/src/assets/css/components/post-share.css b/docs/src/assets/css/components/post-share.css
deleted file mode 100644
index ee40eccea8f..00000000000
--- a/docs/src/assets/css/components/post-share.css
+++ /dev/null
@@ -1,37 +0,0 @@
-.c-share {
- display: flex;
- flex-wrap: wrap;
- gap: .75rem;
- position: relative; }
-
-.c-share__btn {
- border-radius: var(--border-radius);
- box-shadow: var(--shadow-xs);
- border: 1px solid var(--border-color);
- padding: .75rem;
- display: inline-flex;
- align-items: center;
- color: var(--icon-color); }
- .c-share__btn:hover, .c-share__btn:focus {
- color: var(--headings-color); }
- .c-share__btn svg {
- color: inherit; }
-
-button.c-share__btn {
- color: var(--dark-icon-color); }
- button.c-share__btn[data-copied="true"] {
- color: var(--link-color); }
-
-.ctc-announcement {
- flex: 1 1 999px;
- font-size: .875rem;
- font-size: var(--step--1);
- padding: .25rem;
- border-radius: var(--border-radius);
- display: block;
- position: absolute;
- top: 100%;
- offset-block-start: 100%;
- transition: opacity 1s linear 3s; }
- .ctc-announcement[data-fades-out] {
- opacity: 0; }
diff --git a/docs/src/assets/css/components/rules.css b/docs/src/assets/css/components/rules.css
deleted file mode 100644
index 73b8c3097b7..00000000000
--- a/docs/src/assets/css/components/rules.css
+++ /dev/null
@@ -1,121 +0,0 @@
-.rule-categories {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
- gap: 2rem 1rem;
- margin-bottom: 3rem; }
- .rule-categories .rule-category {
- margin: 0;
- padding: 0;
- background: none;
- border: none; }
- .rule-categories .rule-category__description {
- flex: 1 1 45ch; }
-
-.rule-category {
- font-size: var(--step--1);
- display: flex;
- flex-wrap: wrap;
- align-items: flex-start;
- gap: 1rem;
- padding: 1rem;
- margin: 1.5rem 0;
- border-radius: var(--border-radius);
- border: 1px solid var(--divider-color);
- background-color: var(--lightest-background-color); }
- .rule-category p {
- margin: 0; }
- .rule-category .rule-category__description {
- flex: 1 1 30ch; }
-
-.rule {
- border-radius: var(--border-radius);
- background-color: var(--lightest-background-color);
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 1rem;
- padding: 1rem;
- margin: .5rem 0;
- position: relative; }
- .rule p:last-of-type {
- margin: 0; }
-
-.rule__content {
- flex: 1 1 35ch; }
-
-.rule__name {
- font-weight: 500;
- font-size: .875rem;
- margin-bottom: .25rem;
- margin-block-end: .25rem; }
- .rule__name::after {
- position: absolute;
- content: "";
- width: 100%;
- height: 100%;
- top: 0;
- offset-block-start: 0;
- left: 0;
- offset-inline-start: 0; }
-
-a.rule__name {
- text-decoration: none; }
- a.rule__name:hover {
- text-decoration: underline; }
-
-.rule__description {
- font-size: var(--step--1); }
-
-.rule__categories {
- font-size: .875rem;
- display: flex;
- align-items: center;
- gap: 1rem;
- border-radius: var(--border-radius);
- padding: 2px 4px; }
- .rule__categories p {
- display: inline-flex;
- margin: 0;
- align-items: center; }
- [data-theme="dark"] .rule__categories {
- background: var(--body-background-color); }
-
-.rule__status {
- color: var(--color-rose-500);
- background: var(--color-rose-50);
- border-radius: var(--border-radius);
- display: inline-block;
- font-weight: normal;
- margin-left: .5rem;
- margin-inline-start: .5rem;
- font-size: var(--step--1);
- padding: 0 .5rem; }
- [data-theme="dark"] .rule__status {
- background: var(--body-background-color); }
-
-.rule__categories__type[aria-hidden="true"] {
- opacity: .25; }
-
-/* related rules */
-.related-rules__list {
- display: flex;
- gap: .5rem;
- flex-wrap: wrap;
- justify-content: start; }
-
-.related-rules__list__item svg {
- color: inherit; }
-
-.related-rules__list__item a {
- text-decoration: none;
- color: var(--headings-color);
- padding: .625rem;
- display: inline-flex;
- gap: .5rem;
- align-items: center;
- border: 1px solid var(--divider-color);
- border-radius: var(--border-radius);
- background-color: var(--lightest-background-color); }
- .related-rules__list__item a:hover {
- color: var(--link-color);
- background-color: var(--lighter-background-color); }
diff --git a/docs/src/assets/css/components/search-ui.css b/docs/src/assets/css/components/search-ui.css
deleted file mode 100644
index 4b699ee5b70..00000000000
--- a/docs/src/assets/css/components/search-ui.css
+++ /dev/null
@@ -1,16 +0,0 @@
-.search__input-wrapper {
- position: relative; }
-
-.search__input {
- padding-left: 2.5rem;
- padding-inline-start: 2.5rem;
- outline-offset: 1px; }
-
-.search__icon {
- color: var(--body-text-color);
- position: absolute;
- top: 50%;
- offset-block-start: 50%;
- transform: translateY(-50%);
- left: .75rem;
- offset-inline-start: .75rem; }
diff --git a/docs/src/assets/css/components/search.css b/docs/src/assets/css/components/search.css
deleted file mode 100644
index 72e52a3a73f..00000000000
--- a/docs/src/assets/css/components/search.css
+++ /dev/null
@@ -1,23 +0,0 @@
-.search {
- margin-bottom: 1.5rem; }
-
-.search__input-wrapper {
- position: relative; }
-
-.search__input {
- padding-left: 2.5rem;
- padding-inline-start: 2.5rem;
- outline-offset: 1px;
- width: 100%; }
-
-.search__icon {
- color: var(--body-text-color);
- position: absolute;
- top: 50%;
- offset-block-start: 50%;
- transform: translateY(-50%);
- left: .75rem;
- offset-inline-start: .75rem; }
-
-.algolia-docsearch-suggestion--highlight {
- background-color: var(--color-warning-300); }
diff --git a/docs/src/assets/css/components/slider.css b/docs/src/assets/css/components/slider.css
deleted file mode 100644
index 8c7233eb67d..00000000000
--- a/docs/src/assets/css/components/slider.css
+++ /dev/null
@@ -1,146 +0,0 @@
-.c-slider[data-slider] {
- position: relative;
- padding: 0; }
-
-@media all and (min-width: 1023px) {
- .c-slider__paddleNav {
- margin-top: -4rem;
- margin-block-start: -4rem;
- position: relative;
- z-index: 2; } }
-
-.c-slider__paddleNav .c-slider__paddleNav__prev,
-.c-slider__paddleNav .c-slider__paddleNav__next {
- width: 3.5rem;
- height: 3.5rem;
- border: 2px solid transparent;
- border-radius: 50%;
- border-color: var(--divider-color);
- line-height: 0;
- background-color: var(--lighter-background-color); }
- .c-slider__paddleNav .c-slider__paddleNav__prev svg,
- .c-slider__paddleNav .c-slider__paddleNav__next svg {
- display: block;
- width: 100%;
- transition: color .1s linear;
- color: var(--dark-icon-color); }
- .c-slider__paddleNav .c-slider__paddleNav__prev[aria-disabled="true"] svg,
- .c-slider__paddleNav .c-slider__paddleNav__next[aria-disabled="true"] svg {
- color: var(--color-neutral-400); }
- .c-slider__paddleNav .c-slider__paddleNav__prev:hover svg,
- .c-slider__paddleNav .c-slider__paddleNav__next:hover svg {
- color: var(--link-color); }
- .c-slider__paddleNav .c-slider__paddleNav__prev[aria-disabled="true"]:hover svg,
- .c-slider__paddleNav .c-slider__paddleNav__next[aria-disabled="true"]:hover svg {
- color: var(--color-neutral-400); }
- .c-slider__paddleNav .c-slider__paddleNav__prev[aria-disabled="true"]:hover:focus,
- .c-slider__paddleNav .c-slider__paddleNav__next[aria-disabled="true"]:hover:focus {
- border-color: transparent; }
- .c-slider__paddleNav .c-slider__paddleNav__prev:focus, .c-slider__paddleNav .c-slider__paddleNav__prev:active,
- .c-slider__paddleNav .c-slider__paddleNav__next:focus,
- .c-slider__paddleNav .c-slider__paddleNav__next:active {
- border-color: var(--link-color); }
- .c-slider__paddleNav .c-slider__paddleNav__prev[aria-disabled="true"]:focus,
- .c-slider__paddleNav .c-slider__paddleNav__next[aria-disabled="true"]:focus {
- border-color: transparent; }
- .c-slider__paddleNav .c-slider__paddleNav__prev:focus:not(:focus-visible),
- .c-slider__paddleNav .c-slider__paddleNav__next:focus:not(:focus-visible) {
- border-color: transparent; }
- .js-focus-visible .c-slider__paddleNav .c-slider__paddleNav__prev:focus:not(.focus-visible), .js-focus-visible
- .c-slider__paddleNav .c-slider__paddleNav__next:focus:not(.focus-visible) {
- border-color: transparent; }
-
-.c-slider__slides-container {
- display: flex; }
-
-@media all and (min-width: 1023px) {
- .c-slider__slides-wrapper {
- display: grid;
- grid-template-columns: 1fr 1fr;
- grid-gap: 0 2rem; } }
-
-.c-slider__slide {
- width: 100%;
- color: var(--headings-color);
- flex-shrink: 0;
- margin-bottom: 4rem;
- margin-block-end: 4rem;
- transition: opacity 0.5s cubic-bezier(0.39, 0.03, 0.56, 0.57), visibility 1s cubic-bezier(0.39, 0.03, 0.56, 0.57); }
- .c-slider__slide[data-hidden="true"] {
- visibility: hidden;
- opacity: 0; }
- .c-slider__slide[data-hidden="false"] {
- visibility: visible;
- opacity: 1;
- transition: opacity 0.2s cubic-bezier(0.39, 0.03, 0.56, 0.57), visibility 0.2s cubic-bezier(0.39, 0.03, 0.56, 0.57); }
-
-.c-slider--testimonials .c-slider__testimonial {
- margin: 0; }
-
-.c-slider--testimonials .c-slider__testimonial__img {
- display: none; }
-
-.c-slider--testimonials .c-slider__testimonial__content {
- font-size: var(--step-1);
- margin: 0 auto; }
- .c-slider--testimonials .c-slider__testimonial__content p:last-of-type {
- margin-bottom: 0;
- margin-block-end: 0; }
-
-.c-slider--testimonials .c-slider__testimonial__footer {
- margin-top: var(--space-l-xl);
- margin-bottom: 3rem;
- margin-block-start: var(--space-l-xl);
- margin-block-end: 3rem; }
-
-.c-slider--testimonials .c-slider__testimonial__footer cite {
- font-style: normal;
- font-size: 1.125rem; }
-
-.c-slider--testimonials .c-slider__testimonial__author {
- font-weight: 500; }
-
-.c-slider--testimonials .c-slider__testimonial__author-role {
- color: var(--body-text-color); }
-
-.c-slider--testimonials .c-slider__testimonial__author,
-.c-slider--testimonials .c-slider__testimonial__author-role {
- display: block;
- margin-bottom: 0;
- margin-block-end: 0; }
-
-.js-slider .c-slider__slides-container {
- overflow: hidden; }
-
-@media all and (min-width: 1023px) {
- .js-slider .person__photo {
- display: none; } }
-
-.js-slider .c-slider__slides-wrapper {
- width: 100%;
- grid-gap: 0;
- display: flex;
- align-items: center;
- transition: transform 0.4s cubic-bezier(0.39, 0.03, 0.56, 0.57); }
-
-.js-slider .c-slider__slide {
- margin: 0;
- flex-shrink: 0;
- width: 100%; }
- @media all and (min-width: 1023px) {
- .js-slider .c-slider__slide {
- display: grid;
- grid-template-columns: repeat(12, 1fr);
- grid-gap: 2rem;
- align-items: center; } }
-
-.js-slider .c-slider__testimonial__img {
- display: block;
- border-radius: var(--border-radius);
- max-height: 550px;
- overflow: hidden; }
- @media all and (max-width: 1023px) {
- .js-slider .c-slider__testimonial__img {
- display: none; } }
- .js-slider .c-slider__testimonial__img img {
- object-fit: cover; }
diff --git a/docs/src/assets/css/components/social-icons.css b/docs/src/assets/css/components/social-icons.css
deleted file mode 100644
index 6003c73e13e..00000000000
--- a/docs/src/assets/css/components/social-icons.css
+++ /dev/null
@@ -1,16 +0,0 @@
-.eslint-social-icons {
- margin-bottom: -1rem;
- margin-block-end: -1rem; }
- .eslint-social-icons ul {
- margin: 0;
- padding: 0;
- margin-left: -1rem;
- margin-inline-start: -1rem;
- display: inline-flex; }
- .eslint-social-icons ul li {
- margin: 0;
- display: inline-flex;
- align-items: center; }
- .eslint-social-icons ul li a {
- display: flex;
- padding: 1rem; }
diff --git a/docs/src/assets/css/components/sponsors.css b/docs/src/assets/css/components/sponsors.css
deleted file mode 100644
index 23d4881898a..00000000000
--- a/docs/src/assets/css/components/sponsors.css
+++ /dev/null
@@ -1,38 +0,0 @@
-/* sponsors lists */
-.sponsors.sponsors {
- text-align: center;
- margin-bottom: var(--space-m-l);
- margin-block-end: var(--space-m-l);
- display: flex;
- flex-wrap: wrap;
- justify-content: center; }
- @media all and (max-width: 1023px) {
- .sponsors.sponsors {
- margin-top: 2.5rem;
- margin-block-start: 2.5rem; } }
- .sponsors.sponsors li {
- display: inline-block;
- margin: 0 .75rem 1.5rem; }
- .sponsors.sponsors li a {
- display: block; }
- .sponsors.sponsors picture, .sponsors.sponsors img {
- display: block;
- height: auto;
- max-height: 3rem; }
-
-.sponsors.sponsors--backers picture, .sponsors.sponsors--backers img {
- border-radius: 50%; }
-
-.sponsors.sponsors--platinum picture, .sponsors.sponsors--platinum img {
- max-height: 8rem; }
-
-.sponsors.sponsors--gold picture, .sponsors.sponsors--gold img {
- max-height: 6rem; }
-
-.sponsors.sponsors--silver picture, .sponsors.sponsors--silver img {
- max-height: 8rem; }
-
-.sponsors.sponsors--bronze picture, .sponsors.sponsors--bronze img,
-.sponsors.sponsors--technology picture,
-.sponsors.sponsors--technology img {
- max-height: 3rem; }
diff --git a/docs/src/assets/css/components/swatches.css b/docs/src/assets/css/components/swatches.css
deleted file mode 100644
index 55731f7235b..00000000000
--- a/docs/src/assets/css/components/swatches.css
+++ /dev/null
@@ -1,40 +0,0 @@
-.swatches {
- margin: 0;
- padding: 0;
- margin-top: var(--space-l-2xl);
- margin-block-start: var(--space-l-2xl);
- list-style: none;
- display: flex;
- flex-wrap: wrap; }
- @media all and (min-width: 1023px) {
- .swatches {
- display: grid;
- margin: 0;
- overflow: initial;
- grid-template-columns: repeat(auto-fit, minmax(104px, 1fr));
- grid-gap: 2rem .5rem; } }
-
-.swatch {
- min-width: 105px;
- margin: 0;
- border-radius: var(--border-radius);
- box-shadow: var(--shadow-lg);
- display: inline-flex;
- flex-direction: column-reverse;
- margin-right: 1rem;
- margin-inline-end: 1rem;
- overflow: hidden; }
- .swatch svg {
- display: block;
- max-width: 100%;
- width: 124px;
- height: 80px; }
- .swatch figcaption {
- display: block;
- padding: .75rem; }
- .swatch figcaption span {
- display: block; }
-
-.swatch__description {
- color: var(--headings-color);
- font-weight: 500; }
diff --git a/docs/src/assets/css/components/tabs.css b/docs/src/assets/css/components/tabs.css
deleted file mode 100644
index 0830a08ce10..00000000000
--- a/docs/src/assets/css/components/tabs.css
+++ /dev/null
@@ -1,45 +0,0 @@
-.c-tabs pre {
- margin-top: 0;
- margin-block-start: 0; }
-
-.js-tabs .c-tabs__tablist {
- display: flex;
- justify-content: start; }
-
-.c-tabs__tab {
- background: none;
- border: none;
- margin: 0;
- color: inherit;
- font: inherit;
- cursor: pointer;
- line-height: inherit;
- font-weight: 500;
- font-size: var(--step-0);
- display: inline-flex;
- padding: .75rem 1.125rem;
- align-items: center;
- justify-content: center;
- border-radius: var(--border-radius) var(--border-radius) 0 0;
- transition: background-color .2s linear, border-color .2s linear; }
- .c-tabs__tab:hover {
- color: var(--link-color); }
- .c-tabs__tab[aria-selected="true"] {
- color: var(--link-color);
- background-color: var(--lightest-background-color); }
-
-.c-tabs__tabpanel {
- margin-bottom: 2rem;
- margin-block-end: 2rem;
- background-color: var(--lightest-background-color);
- border-radius: 0 var(--border-radius) var(--border-radius) var(--border-radius); }
- .js-tabs .c-tabs__tabpanel {
- margin-bottom: 0;
- margin-block-end: 0; }
-
-.c-tabs__tabpanel__title {
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem; }
-
-.js-tabs .c-tabs__tabpanel__title {
- display: none; }
diff --git a/docs/src/assets/css/components/theme-switcher.css b/docs/src/assets/css/components/theme-switcher.css
deleted file mode 100644
index 5f3fb3ba097..00000000000
--- a/docs/src/assets/css/components/theme-switcher.css
+++ /dev/null
@@ -1,53 +0,0 @@
-.theme-switcher {
- display: inline-flex;
- align-items: center;
- gap: .5rem;
- position: relative; }
-
-.theme-switcher-label.theme-switcher-label {
- font-size: inherit;
- color: inherit;
- font: inherit;
- font-family: var(--text-font);
- margin: 0; }
-
-.theme-switcher__buttons {
- display: flex;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- background-color: var(--body-background-color); }
-
-.theme-switcher__button {
- flex: 0;
- box-shadow: var(--shadow-xs);
- padding: .625rem .875rem;
- display: inline-flex;
- align-items: center;
- margin: 0;
- width: 40px;
- height: 40px; }
- .theme-switcher__button:first-of-type {
- border-right: 0.5px solid var(--border-color);
- border-inline-end: 0.5px solid var(--border-color); }
- .theme-switcher__button:last-of-type {
- border-left: 0.5px solid var(--border-color);
- border-inline-start: 0.5px solid var(--border-color); }
- .theme-switcher__button .theme-switcher__icon {
- color: var(--icon-color); }
- .theme-switcher__button:hover .theme-switcher__icon {
- color: var(--link-color); }
-
-.theme-switcher__button[aria-pressed="true"] .theme-switcher__icon {
- color: var(--link-color); }
-
-.theme-switcher__button[aria-pressed="true"]:hover .theme-switcher__icon {
- color: var(--link-color); }
-
-.theme-switcher__button[aria-pressed="false"] .theme-switcher__icon {
- color: var(--icon-color); }
-
-.theme-switcher__button[aria-pressed="false"]:hover .theme-switcher__icon {
- color: var(--link-color); }
-
-.theme-switcher__button:hover .theme-switcher__icon {
- color: var(--link-color); }
diff --git a/docs/src/assets/css/components/toc-min.css b/docs/src/assets/css/components/toc-min.css
deleted file mode 100644
index 2d96bb862d5..00000000000
--- a/docs/src/assets/css/components/toc-min.css
+++ /dev/null
@@ -1,6 +0,0 @@
-.c-toc ol {
- list-style: decimal-leading-zero; }
-
-.c-toc--main a {
- font-weight: 500;
- font-size: 1.5rem; }
diff --git a/docs/src/assets/css/components/toc.css b/docs/src/assets/css/components/toc.css
deleted file mode 100644
index 7c842456d58..00000000000
--- a/docs/src/assets/css/components/toc.css
+++ /dev/null
@@ -1,76 +0,0 @@
-@charset "UTF-8";
-.docs-toc {
- margin: 2rem 0; }
-
-.c-toc ol {
- margin: 0; }
- .c-toc ol li {
- position: relative;
- margin-bottom: .25rem;
- margin-block-end: .25rem;
- padding-left: 1rem;
- padding-inline-start: 1rem; }
- .c-toc ol li > ol {
- margin-top: .25rem; }
- .c-toc ol li::before {
- content: "└";
- color: var(--icon-color);
- position: absolute;
- left: -.4rem;
- offset-inline-start: -.4rem; }
-
-.c-toc a {
- text-decoration: none;
- color: var(--headings-color); }
- .c-toc a:hover {
- color: var(--link-color); }
-
-.c-toc__label.c-toc__label {
- font-size: var(--step-0);
- color: var(--body-text-color);
- font-family: var(--text-font);
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
-
-.c-toc__label {
- width: fit-content; }
- .c-toc__label button {
- color: var(--link-color);
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: space-between;
- font: inherit;
- font-size: inherit;
- font-weight: 500;
- width: 100%;
- height: 100%;
- text-align: left;
- line-height: 1.5;
- padding: 0;
- border-radius: 0;
- position: relative;
- border: none;
- transition: outline 0.1s linear; }
- .c-toc__label button svg {
- flex: none; }
-
-/* Styles for the accordion icon */
-.toc-trigger-icon {
- display: block !important;
- width: 0.75rem;
- height: 0.5rem;
- transform-origin: 50% 50%;
- margin-left: 3rem;
- margin-inline-start: 3rem;
- transition: all 0.1s linear;
- color: var(--color-neutral-400); }
- [aria-expanded="true"] .toc-trigger-icon {
- -ms-transform: translateY(-50%) rotate(180deg);
- transform: translateY(-50%) rotate(180deg); }
-
-.c-toc__panel[data-open="false"] {
- display: none; }
-
-.c-toc__panel[data-open="true"] {
- display: block; }
diff --git a/docs/src/assets/css/components/tweet-min.css b/docs/src/assets/css/components/tweet-min.css
deleted file mode 100644
index b9516e2a629..00000000000
--- a/docs/src/assets/css/components/tweet-min.css
+++ /dev/null
@@ -1,14 +0,0 @@
-blockquote.tweet {
- padding: 1em 1em 1em 4em;
- margin: 2rem 0;
- position: relative;
- font-size: 1.1rem; }
- blockquote.tweet cite {
- font-size: 1rem; }
-
-.tweet__icon {
- width: 2.5em;
- height: 2.5em;
- position: absolute;
- left: .5em;
- top: .5em; }
diff --git a/docs/src/assets/css/components/tweet.css b/docs/src/assets/css/components/tweet.css
deleted file mode 100644
index b9516e2a629..00000000000
--- a/docs/src/assets/css/components/tweet.css
+++ /dev/null
@@ -1,14 +0,0 @@
-blockquote.tweet {
- padding: 1em 1em 1em 4em;
- margin: 2rem 0;
- position: relative;
- font-size: 1.1rem; }
- blockquote.tweet cite {
- font-size: 1rem; }
-
-.tweet__icon {
- width: 2.5em;
- height: 2.5em;
- position: absolute;
- left: .5em;
- top: .5em; }
diff --git a/docs/src/assets/css/components/version-switcher.css b/docs/src/assets/css/components/version-switcher.css
deleted file mode 100644
index a1984328c02..00000000000
--- a/docs/src/assets/css/components/version-switcher.css
+++ /dev/null
@@ -1,3 +0,0 @@
-.version-switcher {
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem; }
diff --git a/docs/src/assets/css/components/versions.css b/docs/src/assets/css/components/versions.css
deleted file mode 100644
index 6a9d607b8ac..00000000000
--- a/docs/src/assets/css/components/versions.css
+++ /dev/null
@@ -1,34 +0,0 @@
-@charset "UTF-8";
-.versions-list {
- margin: 0;
- padding: 0;
- font-size: var(--step-1); }
- .versions-list li {
- margin: 0; }
- .versions-list li:last-of-type a {
- border-bottom: 0;
- border-block-end: 0; }
- .versions-list a {
- color: var(--link-color);
- display: block;
- width: 100%;
- padding: 1rem .5rem;
- text-decoration: none;
- display: flex;
- align-items: center;
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color); }
- .versions-list a[data-current="true"] {
- font-weight: 500;
- color: var(--link-color); }
- .versions-list a[data-current="true"]::after {
- content: "✔️"; }
- .versions-list a:hover {
- background-color: var(--lightest-background-color); }
-
-.versions-section .versions-list {
- font-size: var(--step-1);
- border-left: 4px solid var(--tab-border-color);
- padding-left: 1rem;
- border-inline-start: 4px solid var(--tab-border-color);
- padding-inline-start: 1rem; }
diff --git a/docs/src/assets/css/print.css b/docs/src/assets/css/print.css
deleted file mode 100644
index 40e8d3dcc49..00000000000
--- a/docs/src/assets/css/print.css
+++ /dev/null
@@ -1,161 +0,0 @@
-*,
-*:before,
-*:after,
-*:first-letter,
-p:first-line,
-div:first-line,
-blockquote:first-line,
-li:first-line {
- background: transparent !important;
- color: #000 !important;
- box-shadow: none !important;
- text-shadow: none !important; }
-
-body {
- width: 100% !important;
- margin: 0 !important;
- padding: 0 !important;
- line-height: 1.45;
- font-family: Helvetica, sans-serif;
- color: #000;
- background: none;
- font-size: 14pt; }
-
-.grid {
- display: block; }
-
-main,
-.docs-content,
-.docs-wrapper {
- display: block;
- width: 100%;
- max-width: 75ch;
- margin: 1cm auto; }
-
-/* Headings */
-h1,
-h2,
-h3,
-h4,
-h5,
-h6 {
- page-break-after: avoid; }
-
-h1 {
- font-size: 19pt; }
-
-h2 {
- font-size: 17pt; }
-
-h3 {
- font-size: 15pt; }
-
-h4,
-h5,
-h6 {
- font-size: 14pt; }
-
-p,
-h2,
-h3 {
- orphans: 3;
- widows: 3; }
-
-code {
- font: 12pt Courier, monospace; }
-
-blockquote {
- margin: 1.2em;
- padding: 1em;
- font-size: 12pt; }
-
-hr {
- background-color: #ccc; }
-
-/* Images */
-img {
- max-width: 100% !important; }
-
-a img {
- border: none; }
-
-/* Links */
-a:link,
-a:visited {
- background: transparent;
- font-weight: 700;
- text-decoration: underline;
- color: #333; }
-
-abbr[title]:after {
- content: " (" attr(title) ")"; }
-
-/* Don't show linked images */
-a[href^="http://"] {
- color: #000; }
-
-a[href$=".jpg"]:after,
-a[href$=".jpeg"]:after,
-a[href$=".gif"]:after,
-a[href$=".png"]:after {
- content: " (" attr(href) ") ";
- display: none; }
-
-/* Don't show links that are fragment identifiers, or use the `javascript:` pseudo protocol .. taken from html5boilerplate */
-a[href^="#"]:after,
-a[href^="javascript:"]:after {
- content: ""; }
-
-/* Table */
-table {
- margin: 1px;
- text-align: left; }
-
-th {
- border-bottom: 1px solid #333;
- font-weight: bold; }
-
-td {
- border-bottom: 1px solid #333; }
-
-th,
-td {
- padding: 4px 10px 4px 0; }
-
-tfoot {
- font-style: italic; }
-
-caption {
- background: #fff;
- margin-bottom: 2em;
- text-align: left; }
-
-thead {
- display: table-header-group; }
-
-img,
-tr {
- page-break-inside: avoid; }
-
-body > *:not(main),
-aside,
-*[class*="sidebar"] {
- display: none; }
-
-button,
-.c-btn.c-btn--playground,
-.docs-edit-link {
- display: none; }
-
-a[href^='http']:not([href*='mywebsite.com'])::after {
- content: " (" attr(href) ")"; }
-
-.resource a::after {
- display: none; }
-
-ul {
- page-break-inside: avoid; }
-
-@media print {
- @page {
- margin: 1cm; } }
diff --git a/docs/src/assets/css/styles-min.css b/docs/src/assets/css/styles-min.css
deleted file mode 100644
index e9697082773..00000000000
--- a/docs/src/assets/css/styles-min.css
+++ /dev/null
@@ -1,376 +0,0 @@
-html {
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
- background-color: var(--bg-color);
- color: var(--text-color);
- height: 100%; }
-
-body {
- background-color: inherit;
- margin: 0;
- line-height: 1.5;
- display: -webkit-flex;
- display: flex;
- -webkit-flex-direction: column;
- flex-direction: column;
- min-height: 100%; }
- body.wall {
- background-image: url(../../assets/images/patterns/ignasi_pattern_s.png); }
-
-main {
- -webkit-flex: 1;
- flex: 1;
- margin: 0 auto;
- width: 90%;
- max-width: 70ch; }
-
-.theatre {
- background-color: #111;
- color: #eee; }
-
-html {
- --color-brand: hsl(258, 50%, 57%);
- --grey: #888;
- --color-highlight: #F8D204;
- --color-accent: var(--color-brand);
- --bg-color: #fff;
- --text-color: #111;
- --link-color: var(--color-brand);
- --font-family: "Atkinson Hyperlegible"; }
-
-/* Visually hide text while keeping it accessible */
-/* Support includes IE9+ */
-.visually-hidden {
- clip: rect(0 0 0 0);
- -webkit-clip-path: inset(100%);
- clip-path: inset(100%);
- height: 1px;
- overflow: hidden;
- position: absolute;
- width: 1px;
- white-space: nowrap;
- /* Why we need this rule: https://medium.com/@jessebeach/beware-smushed-off-screen-accessible-text-5952a4c2cbfe */ }
-
-[hidden] {
- display: none; }
-
-/* @link https://utopia.fyi/type/calculator?c=320,16,1.125,1400,20,1.2,5,2,&s=0.75|0.5|0.25,1.5|2|3|4|6,s-l */
-:root {
- --fluid-min-width: 320;
- --fluid-max-width: 1400;
- --fluid-screen: 100vw;
- --fluid-bp: calc((var(--fluid-screen) - var(--fluid-min-width) / 16 * 1rem) / (var(--fluid-max-width) - var(--fluid-min-width))); }
-
-@media screen and (min-width: 1400px) {
- :root {
- --fluid-screen: calc(var(--fluid-max-width) * 1px); } }
-
-:root {
- --f--2-min: 12.64;
- --f--2-max: 13.89;
- --step--2: calc(((var(--f--2-min) / 16) * 1rem) + (var(--f--2-max) - var(--f--2-min)) * var(--fluid-bp));
- --f--1-min: 14.22;
- --f--1-max: 16.67;
- --step--1: calc(((var(--f--1-min) / 16) * 1rem) + (var(--f--1-max) - var(--f--1-min)) * var(--fluid-bp));
- --f-0-min: 16.00;
- --f-0-max: 20.00;
- --step-0: calc(((var(--f-0-min) / 16) * 1rem) + (var(--f-0-max) - var(--f-0-min)) * var(--fluid-bp));
- --f-1-min: 18.00;
- --f-1-max: 24.00;
- --step-1: calc(((var(--f-1-min) / 16) * 1rem) + (var(--f-1-max) - var(--f-1-min)) * var(--fluid-bp));
- --f-2-min: 20.25;
- --f-2-max: 28.80;
- --step-2: calc(((var(--f-2-min) / 16) * 1rem) + (var(--f-2-max) - var(--f-2-min)) * var(--fluid-bp));
- --f-3-min: 22.78;
- --f-3-max: 34.56;
- --step-3: calc(((var(--f-3-min) / 16) * 1rem) + (var(--f-3-max) - var(--f-3-min)) * var(--fluid-bp));
- --f-4-min: 25.63;
- --f-4-max: 41.47;
- --step-4: calc(((var(--f-4-min) / 16) * 1rem) + (var(--f-4-max) - var(--f-4-min)) * var(--fluid-bp));
- --f-5-min: 28.83;
- --f-5-max: 49.77;
- --step-5: calc(((var(--f-5-min) / 16) * 1rem) + (var(--f-5-max) - var(--f-5-min)) * var(--fluid-bp));
- --f-6-min: 32.44;
- --f-6-max: 59.72;
- --step-6: calc(((var(--f-6-min) / 16) * 1rem) + (var(--f-6-max) - var(--f-6-min)) * var(--fluid-bp)); }
-
-body {
- font-size: var(--step-0);
- line-height: 1.5; }
-
-h5,
-.h5 {
- font-size: var(--step-1); }
-
-h4,
-.h4 {
- font-size: var(--step-2); }
-
-h3,
-.h3 {
- font-size: var(--step-3);
- line-height: 1.2; }
-
-h2,
-.h2 {
- font-size: var(--step-4);
- letter-spacing: -.5px;
- line-height: 1.2; }
-
-h1,
-.h1 {
- font-size: var(--step-5);
- letter-spacing: -.5px;
- line-height: 1.2; }
-
-.h0 {
- font-size: var(--step-6);
- letter-spacing: -.5px;
- line-height: 1.2; }
-
-small, caption, cite, figcaption {
- font-size: var(--step--1); }
-
-::marker {
- color: var(--color-accent); }
-
-::-moz-selection {
- background-color: var(--color-highlight);
- color: #000; }
-
-::selection {
- background-color: var(--color-highlight);
- color: #000; }
-
-*, *::before, *::after {
- box-sizing: border-box; }
-
-html {
- accent-color: var(--color-accent);
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; }
-
-#skip-link {
- position: fixed;
- top: -30em;
- left: 0;
- right: auto;
- z-index: 999;
- background-color: var(--color-highlight);
- color: #000;
- padding: 1em 1.5em;
- font-size: 1em;
- text-align: center;
- transition: top .1s linear;
- text-decoration: none; }
- #skip-link:focus, #skip-link:focus-visible {
- outline: 2px solid transparent;
- top: 2px;
- color: #000;
- box-shadow: inset 0 0 0 2px, inset 0 0 0 3px currentColor; }
-
-#back-to-top {
- display: -webkit-inline-flex;
- display: inline-flex;
- color: var(--color-brand);
- transition: all .2s linear; }
- #back-to-top:hover, #back-to-top:focus {
- color: var(--color-accent); }
- #back-to-top svg {
- color: inherit; }
-
-a {
- color: var(--link-color); }
- :where(.site-header, .site-footer) a {
- color: inherit;
- text-decoration: none; }
-
-a[aria-current="true"] {
- font-weight: bold; }
-
-p {
- margin: 0 0 1.5em; }
- :matches(nav, .posts-collection) p {
- margin-bottom: .75em; }
-
-ul,
-ol {
- margin-top: 0; }
- ul li,
- ol li {
- margin: 0 0 .75em; }
-
-figure {
- margin-bottom: 4rem; }
- figure img {
- margin-bottom: 1rem; }
- figure figcaption {
- color: var(--grey); }
-
-img {
- display: block;
- position: relative;
- max-width: 100%; }
-
-img:after {
- content: "Broken image:" " " attr(alt);
- font-size: 1rem;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
- text-align: center;
- color: #777;
- position: absolute;
- left: 0;
- z-index: 2;
- top: 50%;
- -webkit-transform: translateY(-50%);
- transform: translateY(-50%);
- visibility: visible;
- width: 100%;
- padding: .6em .3em;
- background-color: #fff;
- border: 1px dashed currentColor;
- border-radius: 4px;
- background-color: #eee; }
-
-nav {
- /* rarely do we display bullets for lists in navigation */ }
- nav ol,
- nav ul {
- list-style: none;
- margin: 0;
- padding: 0; }
- nav.c-toc ul, nav.c-toc ol {
- padding-left: 2rem; }
-
-ol {
- list-style: decimal-leading-zero;
- font-feature-settings: "tnum"; }
-
-.video {
- width: 90%;
- max-width: 1400px;
- margin: 2em auto; }
- .video iframe {
- aspect-ratio: 16 / 9;
- width: 100%;
- height: auto; }
-
-@media (prefers-reduced-motion: no-preference) {
- html {
- scroll-behavior: smooth; }
- *:focus {
- transition: outline-offset .15s linear;
- outline-offset: 4px; } }
-
-.chapter .main-wrapper {
- display: grid;
- grid-template-columns: 25% 1fr;
- grid-template-areas: "toc content";
- grid-gap: 2rem; }
- .chapter .main-wrapper main {
- grid-area: content; }
- .chapter .main-wrapper aside {
- grid-area: toc; }
-
-.site-header {
- display: -webkit-flex;
- display: flex;
- -webkit-justify-content: space-between;
- justify-content: space-between;
- -webkit-align-items: center;
- align-items: center;
- padding: 2em 0; }
-
-.logo-link {
- display: block;
- width: 150px; }
-
-.logo {
- display: block;
- width: 100%;
- height: auto; }
-
-.site-nav ul {
- display: -webkit-flex;
- display: flex;
- gap: 1em;
- list-style: none; }
-
-.site-footer {
- background-color: #dedfe3; }
-
-.c-toc ol {
- list-style: decimal-leading-zero; }
-
-.c-toc--main a {
- font-weight: 500;
- font-size: 1.5rem; }
-
-nav.c-breadcrumbs ol {
- list-style: none;
- margin: 0;
- padding: 0; }
-
-nav.c-breadcrumbs li {
- display: inline-block;
- padding: 0.5em 0.25em;
- position: relative; }
- nav.c-breadcrumbs li::after {
- content: "/";
- color: inherit;
- display: inline-block;
- -webkit-margin-start: .5em;
- margin-inline-start: .5em; }
- nav.c-breadcrumbs li:last-of-type::after {
- display: none; }
- nav.c-breadcrumbs li a {
- font-weight: bold; }
- nav.c-breadcrumbs li a[aria-current] {
- color: inherit;
- text-decoration: none;
- background: none;
- font-weight: normal; }
-
-/* Pagination within (and between) individual posts */
-.c-post-pagination ul {
- list-style: none;
- width: 100%;
- outline: 1px solid yellow;
- display: -webkit-flex;
- display: flex;
- -webkit-align-items: flex-start;
- align-items: flex-start; }
-
-.c-post-pagination li {
- -webkit-flex: 1;
- flex: 1;
- display: -webkit-flex;
- display: flex; }
-
-.c-post-pagination a {
- display: block;
- padding: .5em; }
-
-/* Pagination on collection pages */
-.c-collection-pagination {
- outline: 1px solid yellow; }
-
-blockquote.tweet {
- padding: 1em 1em 1em 4em;
- margin: 2rem 0;
- position: relative;
- font-size: 1.1rem; }
- blockquote.tweet cite {
- font-size: 1rem; }
-
-.tweet__icon {
- width: 2.5em;
- height: 2.5em;
- position: absolute;
- left: .5em;
- top: .5em; }
-
-input, textarea {
- font: inherit;
- line-height: 1.3;
- padding: .25em .75em;
- border-radius: 4px;
- border: 1px solid #777; }
diff --git a/docs/src/assets/css/styles.css b/docs/src/assets/css/styles.css
deleted file mode 100644
index ff3d95c282e..00000000000
--- a/docs/src/assets/css/styles.css
+++ /dev/null
@@ -1,2203 +0,0 @@
-@charset "UTF-8";
-:root {
- /* Tier 1 variables */
- --color-neutral-25: #FCFCFD;
- --color-neutral-50: #F9FAFB;
- --color-neutral-100: #F2F4F7;
- --color-neutral-200: #E4E7EC;
- --color-neutral-300: #D0D5DD;
- --color-neutral-400: #98A2B3;
- --color-neutral-500: #667085;
- --color-neutral-600: #475467;
- --color-neutral-700: #344054;
- --color-neutral-800: #1D2939;
- --color-neutral-900: #101828;
- --color-primary-25: #FBFBFF;
- --color-primary-50: #F6F6FE;
- --color-primary-100: #ECECFD;
- --color-primary-200: #DEDEFF;
- --color-primary-300: #CCCCFA;
- --color-primary-400: #B7B7FF;
- --color-primary-500: #A0A0F5;
- --color-primary-600: #8080F2;
- --color-primary-700: #6358D4;
- --color-primary-800: #4B32C3;
- --color-primary-900: #341BAB;
- --color-warning-25: #FFFCF5;
- --color-warning-50: #FFFAEB;
- --color-warning-100: #FEF0C7;
- --color-warning-200: #FEDF89;
- --color-warning-300: #FEC84B;
- --color-warning-400: #FDB022;
- --color-warning-500: #F79009;
- --color-warning-600: #DC6803;
- --color-warning-700: #B54708;
- --color-warning-800: #93370D;
- --color-warning-900: #7A2E0E;
- --color-success-25: #F6FEF9;
- --color-success-50: #ECFDF3;
- --color-success-100: #D1FADF;
- --color-success-200: #A6F4C5;
- --color-success-300: #6CE9A6;
- --color-success-400: #32D583;
- --color-success-500: #12B76A;
- --color-success-600: #039855;
- --color-success-700: #027A48;
- --color-success-800: #05603A;
- --color-success-900: #054F31;
- --color-rose-25: #FFF5F6;
- --color-rose-50: #FFF1F3;
- --color-rose-100: #FFE4E8;
- --color-rose-200: #FECDD6;
- --color-rose-300: #FEA3B4;
- --color-rose-400: #FD6F8E;
- --color-rose-500: #F63D68;
- --color-rose-600: #E31B54;
- --color-rose-700: #C01048;
- --color-rose-800: #A11043;
- --color-rose-900: #89123E;
- /* Tier 2 variables */
- --primary-button-background-color: var(--color-primary-800);
- --primary-button-hover-color: var(--color-primary-900);
- --primary-button-text-color: #fff;
- --secondary-button-background-color: var(--color-primary-50);
- --secondary-button-hover-color: var(--color-primary-100);
- --secondary-button-text-color: var(--color-brand);
- --ghost-button-background-color: var(--color-primary-50);
- --ghost-button-text-color: var(--color-brand);
- --color-brand: var(--color-primary-800);
- --body-background-color: #fff;
- --body-text-color: var(--color-neutral-500);
- --headings-color: var(--color-neutral-900);
- --border-color: var(--color-neutral-300);
- --divider-color: var(--color-neutral-200);
- --icon-color: var(--color-neutral-400);
- --dark-icon-color: var(--color-neutral-500);
- --link-color: var(--color-primary-800);
- --lighter-background-color: var(--color-neutral-100);
- --lightest-background-color: var(--color-neutral-50);
- --docs-lightest-background-color: var(--color-primary-50);
- --hero-background-color: var(--color-neutral-25);
- --footer-background-color: var(--color-neutral-25);
- --outline-color: var(--color-brand); }
-
-@media (prefers-color-scheme: dark) {
- --secondary-button-background-color: var(--color-neutral-700);
- --secondary-button-hover-color: var(--color-neutral-800);
- --secondary-button-text-color: var(--body-text-color);
- --body-background-color: var(--color-neutral-900);
- --body-text-color: var(--color-neutral-300);
- --headings-color: #fff;
- --divider-color: var(--color-neutral-600);
- --border-color: var(--color-neutral-500);
- --icon-color: var(--body-text-color);
- --dark-icon-color: #fff;
- --link-color: var(--color-primary-400);
- --lighter-background-color: var(--color-neutral-800);
- --lightest-background-color: var(--color-neutral-800);
- --hero-background-color: var(--color-neutral-800);
- --footer-background-color: var(--color-neutral-800);
- --outline-color: #fff; }
-
-html[data-theme="light"] {
- --body-background-color: #fff;
- --body-text-color: var(--color-neutral-500);
- --headings-color: var(--color-neutral-900);
- --border-color: var(--color-neutral-300);
- --divider-color: var(--color-neutral-200);
- --icon-color: var(--color-neutral-400);
- --dark-icon-color: var(--color-neutral-500);
- --link-color: var(--color-primary-800);
- --lighter-background-color: var(--color-neutral-100);
- --lightest-background-color: var(--color-neutral-50);
- --docs-lightest-background-color: var(--color-primary-50);
- --hero-background-color: var(--color-neutral-25);
- --footer-background-color: var(--color-neutral-25);
- --outline-color: var(--color-brand); }
-
-html[data-theme="dark"] {
- --body-background-color: var(--color-neutral-900);
- --body-text-color: var(--color-neutral-300);
- --headings-color: #fff;
- --divider-color: var(--color-neutral-600);
- --border-color: var(--color-neutral-500);
- --icon-color: var(--body-text-color);
- --dark-icon-color: #fff;
- --link-color: var(--color-primary-400);
- --lighter-background-color: var(--color-neutral-800);
- --lightest-background-color: var(--color-neutral-800);
- --docs-lightest-background-color: var(--color-neutral-800);
- --hero-background-color: var(--color-neutral-800);
- --footer-background-color: var(--color-neutral-800);
- --outline-color: #fff; }
-
-/* @link https://utopia.fyi/space/calculator?c=320,16,1.125,1440,16,1.25,6,2,&s=0.75|0.5|0.25,1.5|2|3|4|6|8,l-2xl|xl-3xl|xl-4xl */
-:root {
- --fc-3xs-min: (var(--fc-s-min) * 0.25);
- --fc-3xs-max: (var(--fc-s-max) * 0.25);
- --fc-2xs-min: (var(--fc-s-min) * 0.5);
- --fc-2xs-max: (var(--fc-s-max) * 0.5);
- --fc-xs-min: (var(--fc-s-min) * 0.75);
- --fc-xs-max: (var(--fc-s-max) * 0.75);
- --fc-s-min: (var(--f-0-min));
- --fc-s-max: (var(--f-0-max));
- --fc-m-min: (var(--fc-s-min) * 1.5);
- --fc-m-max: (var(--fc-s-max) * 1.5);
- --fc-l-min: (var(--fc-s-min) * 2);
- --fc-l-max: (var(--fc-s-max) * 2);
- --fc-xl-min: (var(--fc-s-min) * 3);
- --fc-xl-max: (var(--fc-s-max) * 3);
- --fc-2xl-min: (var(--fc-s-min) * 4);
- --fc-2xl-max: (var(--fc-s-max) * 4);
- --fc-3xl-min: (var(--fc-s-min) * 6);
- --fc-3xl-max: (var(--fc-s-max) * 6);
- --fc-4xl-min: (var(--fc-s-min) * 8);
- --fc-4xl-max: (var(--fc-s-max) * 8);
- /* T-shirt sizes */
- --space-3xs: calc(((var(--fc-3xs-min) / 16) * 1rem) + (var(--fc-3xs-max) - var(--fc-3xs-min)) * var(--fluid-bp));
- --space-2xs: calc(((var(--fc-2xs-min) / 16) * 1rem) + (var(--fc-2xs-max) - var(--fc-2xs-min)) * var(--fluid-bp));
- --space-xs: calc(((var(--fc-xs-min) / 16) * 1rem) + (var(--fc-xs-max) - var(--fc-xs-min)) * var(--fluid-bp));
- --space-s: calc(((var(--fc-s-min) / 16) * 1rem) + (var(--fc-s-max) - var(--fc-s-min)) * var(--fluid-bp));
- --space-m: calc(((var(--fc-m-min) / 16) * 1rem) + (var(--fc-m-max) - var(--fc-m-min)) * var(--fluid-bp));
- --space-l: calc(((var(--fc-l-min) / 16) * 1rem) + (var(--fc-l-max) - var(--fc-l-min)) * var(--fluid-bp));
- --space-xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
- --space-2xl: calc(((var(--fc-2xl-min) / 16) * 1rem) + (var(--fc-2xl-max) - var(--fc-2xl-min)) * var(--fluid-bp));
- --space-3xl: calc(((var(--fc-3xl-min) / 16) * 1rem) + (var(--fc-3xl-max) - var(--fc-3xl-min)) * var(--fluid-bp));
- --space-4xl: calc(((var(--fc-4xl-min) / 16) * 1rem) + (var(--fc-4xl-max) - var(--fc-4xl-min)) * var(--fluid-bp));
- /* One-up pairs */
- --space-3xs-2xs: calc(((var(--fc-3xs-min) / 16) * 1rem) + (var(--fc-2xs-max) - var(--fc-3xs-min)) * var(--fluid-bp));
- --space-2xs-xs: calc(((var(--fc-2xs-min) / 16) * 1rem) + (var(--fc-xs-max) - var(--fc-2xs-min)) * var(--fluid-bp));
- --space-xs-s: calc(((var(--fc-xs-min) / 16) * 1rem) + (var(--fc-s-max) - var(--fc-xs-min)) * var(--fluid-bp));
- --space-s-m: calc(((var(--fc-s-min) / 16) * 1rem) + (var(--fc-m-max) - var(--fc-s-min)) * var(--fluid-bp));
- --space-m-l: calc(((var(--fc-m-min) / 16) * 1rem) + (var(--fc-l-max) - var(--fc-m-min)) * var(--fluid-bp));
- --space-l-xl: calc(((var(--fc-l-min) / 16) * 1rem) + (var(--fc-xl-max) - var(--fc-l-min)) * var(--fluid-bp));
- --space-xl-2xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-2xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
- --space-2xl-3xl: calc(((var(--fc-2xl-min) / 16) * 1rem) + (var(--fc-3xl-max) - var(--fc-2xl-min)) * var(--fluid-bp));
- --space-3xl-4xl: calc(((var(--fc-3xl-min) / 16) * 1rem) + (var(--fc-4xl-max) - var(--fc-3xl-min)) * var(--fluid-bp));
- /* Custom pairs */
- --space-l-2xl: calc(((var(--fc-l-min) / 16) * 1rem) + (var(--fc-2xl-max) - var(--fc-l-min)) * var(--fluid-bp));
- --space-xl-3xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-3xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
- --space-xl-4xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-4xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
- --spacer-2x: 2rem;
- --spacer-3x: 3rem;
- --spacer-4x: 4rem;
- --spacer-6x: 6rem;
- --spacer-8x: 8rem; }
-
-/* @link https://utopia.fyi/type/calculator?c=320,16,1.125,1280,16,1.25,6,2,&s=0.75|0.5|0.25,1.5|2|3|4|6,s-l */
-:root {
- --fluid-min-width: 320;
- --fluid-max-width: 1280;
- --fluid-screen: 100vw;
- --fluid-bp: calc((var(--fluid-screen) - var(--fluid-min-width) / 16 * 1rem) / (var(--fluid-max-width) - var(--fluid-min-width))); }
-
-@media screen and (min-width: 1280px) {
- :root {
- --fluid-screen: calc(var(--fluid-max-width) * 1px); } }
-
-:root {
- --f--2-min: 12.64;
- --f--2-max: 10.24;
- --step--2: calc(((var(--f--2-min) / 16) * 1rem) + (var(--f--2-max) - var(--f--2-min)) * var(--fluid-bp));
- --f--1-min: 14.22;
- --f--1-max: 12.80;
- --step--1: calc(((var(--f--1-min) / 16) * 1rem) + (var(--f--1-max) - var(--f--1-min)) * var(--fluid-bp));
- --f-0-min: 16.00;
- --f-0-max: 16.00;
- --step-0: calc(((var(--f-0-min) / 16) * 1rem) + (var(--f-0-max) - var(--f-0-min)) * var(--fluid-bp));
- --f-1-min: 18.00;
- --f-1-max: 20.00;
- --step-1: calc(((var(--f-1-min) / 16) * 1rem) + (var(--f-1-max) - var(--f-1-min)) * var(--fluid-bp));
- --f-2-min: 20.25;
- --f-2-max: 25.00;
- --step-2: calc(((var(--f-2-min) / 16) * 1rem) + (var(--f-2-max) - var(--f-2-min)) * var(--fluid-bp));
- --f-3-min: 22.78;
- --f-3-max: 31.25;
- --step-3: calc(((var(--f-3-min) / 16) * 1rem) + (var(--f-3-max) - var(--f-3-min)) * var(--fluid-bp));
- --f-4-min: 25.63;
- --f-4-max: 39.06;
- --step-4: calc(((var(--f-4-min) / 16) * 1rem) + (var(--f-4-max) - var(--f-4-min)) * var(--fluid-bp));
- --f-5-min: 28.83;
- --f-5-max: 48.83;
- --step-5: calc(((var(--f-5-min) / 16) * 1rem) + (var(--f-5-max) - var(--f-5-min)) * var(--fluid-bp));
- --f-6-min: 32.44;
- --f-6-max: 61.04;
- --step-6: calc(((var(--f-6-min) / 16) * 1rem) + (var(--f-6-max) - var(--f-6-min)) * var(--fluid-bp)); }
-
-:root {
- --mono-font: "Space Mono", monospace;
- --text-font: "Inter",
- -apple-system,
- BlinkMacSystemFont,
- "Segoe UI",
- Roboto,
- Helvetica,
- Arial,
- sans-serif,
- "Apple Color Emoji",
- "Segoe UI Emoji",
- "Segoe UI Symbol";
- --display-font: "Space Grotesk",
- -apple-system,
- BlinkMacSystemFont,
- "Segoe UI",
- Roboto,
- Helvetica,
- Arial,
- sans-serif,
- "Apple Color Emoji",
- "Segoe UI Emoji",
- "Segoe UI Symbol"; }
-
-:root {
- --shadow-lg: 0px 12px 16px -4px rgba(16, 24, 40, 0.1),
- 0px 4px 6px -2px rgba(16, 24, 40, 0.05);
- --shadow-xs: 0px 1px 2px rgba(16, 24, 40, 0.05);
- --border-radius: .5rem; }
-
-body {
- font-size: var(--step-0);
- line-height: 1.5; }
-
-.eyebrow {
- color: var(--link-color);
- font-size: 1rem;
- font-weight: 500;
- display: block;
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem; }
-
-h1,
-h2,
-h3,
-h4,
-h5,
-h6 {
- font-family: var(--display-font);
- color: var(--headings-color);
- font-weight: 500;
- margin-top: 0;
- margin-block-start: 0; }
-
-.post-main h2,
-.docs-main h2,
-.components-main h2, .post-main
-h3,
-.docs-main
-h3,
-.components-main
-h3, .post-main
-h4,
-.docs-main
-h4,
-.components-main
-h4, .post-main
-h5,
-.docs-main
-h5,
-.components-main
-h5, .post-main
-h6,
-.docs-main
-h6,
-.components-main
-h6 {
- margin-top: 3rem;
- margin-bottom: 1.5rem;
- margin-block-start: 3rem;
- margin-block-end: 1.5rem; }
- .post-main h2:first-child,
- .docs-main h2:first-child,
- .components-main h2:first-child, .post-main
- h3:first-child,
- .docs-main
- h3:first-child,
- .components-main
- h3:first-child, .post-main
- h4:first-child,
- .docs-main
- h4:first-child,
- .components-main
- h4:first-child, .post-main
- h5:first-child,
- .docs-main
- h5:first-child,
- .components-main
- h5:first-child, .post-main
- h6:first-child,
- .docs-main
- h6:first-child,
- .components-main
- h6:first-child {
- margin-top: 0;
- margin-block-start: 0; }
-
-h6,
-.h6 {
- font-size: var(--step-0); }
-
-h5,
-.h5 {
- font-size: var(--step-1); }
-
-h4,
-.h4 {
- font-size: var(--step-2); }
-
-h3,
-.h3 {
- font-size: var(--step-3);
- line-height: 1.2; }
-
-h2,
-.h2 {
- font-size: var(--step-4);
- line-height: 1.2; }
-
-h1,
-.h1 {
- font-size: var(--step-5);
- line-height: 1.2; }
-
-.h0 {
- font-size: var(--step-6);
- line-height: 1.2; }
-
-small,
-caption,
-cite,
-figcaption {
- font-size: var(--step--1); }
-
-.docs-main h6,
-.docs-main .h6 {
- font-size: var(--step-0); }
-
-.docs-main h5,
-.docs-main .h5 {
- font-size: var(--step-0); }
-
-.docs-main h4,
-.docs-main .h4 {
- font-size: var(--step-1); }
-
-.docs-main h3,
-.docs-main .h3 {
- font-size: var(--step-2);
- line-height: 1.2; }
-
-.docs-main h2,
-.docs-main .h2 {
- font-size: var(--step-3);
- line-height: 1.2; }
-
-.docs-main h1,
-.docs-main .h1 {
- font-size: var(--step-4);
- line-height: 1.2; }
-
-::selection {
- background-color: var(--color-brand);
- color: #fff; }
-
-h1:target,
-h2:target,
-h3:target,
-h4:target,
-h5:target,
-h6:target {
- background-color: var(--lighter-background-color); }
-
-*:focus {
- outline: none; }
-
-*:focus-visible {
- outline: 2px solid var(--outline-color);
- outline-offset: 3px; }
-
-*.focus-visible {
- outline: 2px solid var(--outline-color);
- outline-offset: 3px; }
-
-*:focus:not(:focus-visible) {
- outline: 1px solid transparent;
- box-shadow: none; }
-
-.js-focus-visible *:focus:not(.focus-visible) {
- outline: 1px solid transparent;
- box-shadow: none; }
-
-*,
-*::before,
-*::after {
- box-sizing: border-box; }
-
-html {
- accent-color: var(--link-color);
- background-color: var(--body-background-color);
- height: 100%;
- font-family: var(--text-font);
- overflow-x: hidden;
- caret-color: var(--link-color); }
-
-body {
- position: relative;
- margin: 0 auto;
- line-height: 1.5;
- display: flex;
- flex-direction: column;
- min-height: 100%;
- background-color: var(--body-background-color);
- color: var(--body-text-color); }
-
-#skip-link {
- position: fixed;
- top: -30em;
- left: 0;
- right: auto;
- offset-block-start: -30em;
- offset-inline-start: 0;
- offset-inline-end: auto;
- z-index: 999;
- transition: top .1s linear; }
- #skip-link:focus {
- outline: 2px solid transparent;
- top: 2px;
- offset-block-start: 2px; }
- #skip-link:focus-visible {
- outline: 2px solid transparent;
- top: 2px;
- offset-block-start: 2px; }
-
-main {
- flex: 1; }
- main:focus {
- outline: none; }
- main:target {
- outline: none; }
-
-hr {
- border: none;
- border-top: 1px solid var(--divider-color);
- border-block-start: 1px solid var(--divider-color);
- background: none;
- height: 0;
- margin: 2rem 0; }
-
-.content-container {
- width: 100%;
- margin: 0 auto;
- padding: var(--space-xl-3xl) calc(1rem + 1vw); }
-
-.section-head .section-supporting-text {
- text-align: center;
- max-width: 768px;
- margin: 0 auto var(--space-l-2xl); }
-
-.section-foot {
- margin-top: var(--space-l-2xl);
- margin-block-start: var(--space-l-2xl); }
- .section-foot .section-supporting-text {
- text-align: center;
- font-size: var(--step--1);
- max-width: 768px;
- margin: 0 auto; }
-
-.section-title {
- margin-bottom: 1rem;
- margin-block-end: 1rem; }
-
-.section-supporting-text {
- font-size: var(--step-1); }
-
-code,
-pre {
- font-family: var(--mono-font); }
-
-code {
- color: var(--link-color); }
- pre code {
- color: unset; }
-
-p:empty {
- display: none;
- margin: 0; }
-
-.c-icon {
- color: var(--icon-color);
- flex: none;
- transition: all .2s linear; }
- @media (-ms-high-contrast: active) {
- .c-icon {
- color: windowText; } }
- @media (forced-colors: active) {
- .c-icon {
- color: canvasText; } }
-
-table {
- width: 100%;
- margin: 2.5rem 0;
- border-collapse: collapse;
- border: 1px solid var(--divider-color); }
- table td {
- padding: .25rem .5rem;
- border: 1px solid var(--divider-color); }
- table th {
- background-color: var(--lightest-background-color);
- padding: .25rem .5rem; }
-
-.c-btn .c-icon:hover,
-button .c-icon:hover,
-a .c-icon:hover {
- color: var(--link-color); }
-
-a {
- color: var(--link-color);
- transition: color .1s linear; }
- .side-header a {
- color: inherit;
- text-decoration: none; }
-
-svg {
- flex: none;
- transition: color .1s linear; }
-
-p {
- margin: 0 0 1.5em; }
- :matches(nav, .posts-collection) p {
- margin-bottom: .75em;
- margin-block-end: .75em; }
-
-p,
-h1,
-h2,
-h3,
-h4,
-h5,
-h6 {
- overflow-wrap: break-word; }
-
-ul,
-ol {
- margin-top: 0;
- margin-block-start: 0; }
- ul li,
- ol li {
- margin: 0 0 .75em; }
- .person__bio ul, .person__bio
- ol {
- padding-left: 1.5rem;
- padding-inline-start: 1.5rem; }
-
-.docs-main ul,
-.post-main ul,
-.docs-main ol,
-.post-main ol {
- margin: 1rem 0; }
-
-ul[role="list"] {
- list-style: none;
- margin: 0;
- padding: 0; }
- ul[role="list"] li {
- margin: 0; }
-
-ol {
- list-style: decimal; }
- ol li::marker {
- color: var(--link-color); }
-
-p:empty {
- margin: 0;
- display: none; }
-
-figure {
- margin-bottom: 4rem;
- margin-block-end: 4rem; }
- figure img {
- margin-bottom: 1rem;
- margin-block-end: 1rem; }
- figure figcaption {
- color: var(--grey); }
-
-img {
- display: block;
- position: relative;
- max-width: 100%;
- height: auto; }
-
-nav {
- /* rarely do we display bullets for lists in navigation */ }
- nav ol,
- nav ul {
- list-style: none;
- margin: 0;
- padding: 0; }
-
-.video {
- width: 90%;
- max-width: 1400px;
- margin: 2em auto; }
- .video iframe {
- aspect-ratio: 16 / 9;
- width: 100%;
- height: auto; }
-
-@media (prefers-reduced-motion: no-preference) {
- *:focus-visible,
- *.focus-visible {
- transition: outline-offset .15s linear;
- outline-offset: 3px; } }
-
-code[class*="language-"],
-pre[class*="language-"] {
- font-family: var(--mono-font), Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
- font-size: 1em;
- text-align: left;
- white-space: pre;
- word-spacing: normal;
- word-break: normal;
- word-wrap: normal;
- line-height: 1.5;
- -moz-tab-size: 4;
- -o-tab-size: 4;
- tab-size: 4;
- -webkit-hyphens: none;
- -moz-hyphens: none;
- -ms-hyphens: none;
- hyphens: none; }
-
-@media print {
- code[class*="language-"],
- pre[class*="language-"] {
- text-shadow: none; } }
-
-/* Code blocks */
-pre[class*="language-"] {
- padding: 1.5rem;
- margin: 1.5rem 0;
- overflow: auto;
- background-color: var(--color-neutral-50);
- border-radius: var(--border-radius);
- background-color: var(--lightest-background-color);
- color: var(--color-neutral-900); }
- [data-theme="dark"] pre[class*="language-"] {
- color: var(--color-neutral-100); }
-
-:not(pre) > code[class*="language-"],
-pre[class*="language-"] {
- background-color: var(--lightest-background-color); }
-
-/* Inline code */
-:not(pre) > code[class*="language-"] {
- padding: .1em;
- border-radius: .3em;
- white-space: normal; }
-
-.token.comment,
-.token.prolog,
-.token.doctype,
-.token.cdata {
- color: #6E7F8E; }
- [data-theme="dark"] .token.comment, [data-theme="dark"]
- .token.prolog, [data-theme="dark"]
- .token.doctype, [data-theme="dark"]
- .token.cdata {
- color: #8E9FAE; }
-
-.token.namespace {
- opacity: .7; }
-
-.token.selector,
-.token.attr-name,
-.token.string,
-.token.char,
-.token.builtin,
-.token.inserted {
- color: var(--link-color); }
-
-.token.atrule,
-.token.attr-value,
-.token.keyword {
- color: var(--link-color); }
-
-.token.important,
-.token.bold {
- font-weight: bold; }
-
-.token.italic {
- font-style: italic; }
-
-.token.entity {
- cursor: help; }
-
-pre {
- counter-reset: lineNumber; }
-
-code .highlight-line:before {
- -webkit-user-select: none;
- color: var(--icon-color);
- content: counter(lineNumber);
- counter-increment: lineNumber;
- display: inline-block;
- font-variant-numeric: tabular-nums;
- margin-right: 1.2em;
- padding-right: 1.2em;
- margin-inline-end: 1.2em;
- padding-inline-end: 1.2em;
- text-align: right;
- width: 2.4em; }
-
-.site-header {
- padding: .75rem 0;
- border-top: 4px solid var(--link-color);
- border-bottom: 1px solid var(--divider-color);
- border-block-start: 4px solid var(--link-color);
- border-block-end: 1px solid var(--divider-color); }
- .site-header .docs-wrapper {
- display: grid;
- align-items: start;
- padding-top: 0;
- padding-bottom: 0;
- padding-block-start: 0;
- padding-block-end: 0; }
- @media all and (min-width: 1024px) {
- .site-header .docs-wrapper {
- justify-content: space-between; } }
-
-.logo-link {
- display: inline-flex;
- justify-self: start;
- flex: none;
- place-content: center;
- grid-column: 1 / -1;
- grid-row: 1;
- padding: .5rem 0; }
-
-.logo svg {
- display: inline-block;
- margin-bottom: -4px;
- margin-block-end: -4px;
- width: 100%;
- max-width: 100px;
- height: auto; }
-
-.docs-footer {
- display: flex;
- flex-direction: column;
- gap: 2rem;
- justify-content: space-between;
- align-items: baseline; }
- @media all and (max-width: 800px) {
- .docs-footer {
- padding: 1.5rem 0 4rem; } }
-
-.copyright p {
- margin: 0; }
-
-.docs-socials-and-legal {
- display: flex;
- flex-direction: column;
- gap: 1rem; }
- @media all and (max-width: 800px) {
- .docs-socials-and-legal {
- text-align: center; } }
-
-.docs-switchers {
- display: flex;
- flex-wrap: wrap;
- gap: 1.5rem; }
- .docs-switchers .theme-switcher,
- .docs-switchers .language-switcher {
- flex: 1 1 240px; }
- @media all and (max-width: 800px) {
- .docs-switchers .theme-switcher {
- justify-content: center; } }
- @media all and (max-width: 800px) {
- .docs-switchers .language-switcher {
- justify-content: center; } }
-
-.site-footer {
- text-align: center;
- background-color: var(--footer-background-color);
- border-top: 1px solid var(--divider-color);
- border-block-start: 1px solid var(--divider-color); }
-
-.footer-cta .logo {
- margin-bottom: 2.5rem;
- margin-block-end: 2.5rem; }
-
-.footer-cta .section-supporting-text {
- margin-bottom: 2.5rem;
- margin-block-end: 2.5rem; }
-
-.footer-cta .eslint-actions {
- justify-content: center; }
-
-.footer-legal-links ul li {
- display: inline-block;
- margin-right: .5rem;
- margin-inline-end: .5rem; }
- .footer-legal-links ul li:not(:last-of-type)::after {
- content: "|";
- margin-left: .5rem;
- margin-inline-start: .5rem; }
-
-.footer-legal-section {
- font-size: var(--step--1);
- padding: 2rem 1rem; }
-
-.copyright {
- max-width: 1100px;
- margin: 0 auto; }
-
-.footer-middle {
- padding-top: 2rem;
- padding-bottom: 2rem;
- padding-block-start: 2rem;
- padding-block-end: 2rem;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 2rem; }
- @media all and (min-width: 768px) {
- .footer-middle {
- flex-direction: row;
- justify-content: space-between; } }
-
-.c-custom-select {
- -moz-appearance: none;
- -webkit-appearance: none;
- appearance: none;
- box-sizing: border-box;
- display: block;
- width: 100%;
- max-width: 100%;
- min-width: 0px;
- padding: .625rem .875rem;
- padding-right: calc(.875rem * 3);
- padding-inline-end: calc(.875rem * 3);
- font: inherit;
- color: var(--body-text-color);
- color: inherit;
- line-height: 1.3;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- box-shadow: var(--shadow-xs);
- background-color: var(--body-background-color);
- background-image: url("data:image/svg+xml,%3Csvg width='20' height='21' viewBox='0 0 20 21' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M5 7.60938L10 12.6094L15 7.60938' stroke='%23667085' stroke-width='1.66667' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E%0A"), linear-gradient(to bottom, var(--body-background-color) 0%, var(--body-background-color) 100%);
- background-repeat: no-repeat, repeat;
- background-position: right calc(.875rem * 1.5) top 50%, 0 0;
- background-size: 1em auto, 100%; }
-
-.label__text.label__text {
- display: block;
- display: flex;
- font-size: .875rem;
- color: inherit;
- align-items: center;
- gap: .5rem;
- font-size: .875rem;
- font-family: var(--text-font);
- color: inherit;
- font-weight: 400;
- line-height: 1.5;
- margin-bottom: .25rem;
- margin-block-end: .25rem; }
-
-input {
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- padding: .625rem .875rem;
- font: inherit;
- font-size: 1rem;
- display: block;
- min-width: 0;
- max-width: 100%;
- background-color: var(--body-background-color);
- color: inherit; }
-
-.docs {
- max-width: 1700px;
- margin: 0 auto; }
-
-.docs-ad {
- flex: 1; }
-
-.docs-wrapper {
- padding: 0 calc(1rem + 1vw);
- flex: 1; }
- @media all and (min-width: 1023px) {
- .docs-wrapper {
- display: grid;
- grid-template-columns: minmax(250px, 1fr) minmax(0, 3.5fr);
- grid-gap: 0rem;
- align-items: stretch; } }
-
-.docs-left-sidebar {
- grid-column: 1 / 2;
- grid-row: 1 / 2;
- padding: calc(1rem + 1vw) 0;
- font-size: .875rem;
- display: grid;
- grid-auto-rows: max-content;
- align-items: start; }
- @media all and (min-width: 1023px) {
- .docs-left-sidebar {
- border-right: 1px solid var(--divider-color);
- border-right: 1px solid var(--divider-color);
- padding-right: calc(1rem + 1vw);
- padding-inline-end: calc(1rem + 1vw); } }
-
-.docs-content {
- grid-column: 2 / 3; }
- @media all and (min-width: 800px) {
- .docs-content {
- display: grid;
- grid-template-columns: minmax(0, 3fr) minmax(230px, 1fr);
- grid-gap: 2rem; } }
- @media all and (min-width: 1023px) {
- .docs-content {
- padding: calc(2rem + 1vw) 0; } }
-
-.docs-main {
- flex: 1 1 65ch; }
- @media all and (min-width: 1023px) {
- .docs-main {
- padding: 0 2rem; } }
-
-.docs-right-sidebar {
- grid-column: 2 / 3;
- display: flex;
- flex-direction: column;
- flex: 1 1 200px; }
-
-.docs-toc {
- flex: 1;
- align-self: center; }
-
-.docs-edit-link {
- border-top: 1px solid var(--divider-color);
- padding-top: 1.5rem;
- padding-block-start: 1.5rem;
- margin: 3rem 0; }
-
-div[data-correct-code],
-div[data-incorrect-code] {
- position: relative; }
- div[data-correct-code]::after,
- div[data-incorrect-code]::after {
- position: absolute;
- top: -22px;
- right: -22px;
- offset-inline-end: -22px;
- offset-block-start: -22px; }
-
-div[data-correct-code]::after {
- content: url("data:image/svg+xml,%3Csvg width='45' height='44' viewBox='0 0 45 44' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='1.5' y='1' width='42' height='42' rx='21' fill='%23ECFDF3'/%3E%3Cpath d='M30.5 16L19.5 27L14.5 22' stroke='%2312B76A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Crect x='1.5' y='1' width='42' height='42' rx='21' stroke='white' stroke-width='2'/%3E%3C/svg%3E%0A"); }
-
-div[data-incorrect-code]::after {
- content: url("data:image/svg+xml,%3Csvg width='45' height='44' viewBox='0 0 45 44' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='1.5' y='1' width='42' height='42' rx='21' fill='%23FFF1F3'/%3E%3Cpath d='M28.5 16L16.5 28M16.5 16L28.5 28' stroke='%23F63D68' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Crect x='1.5' y='1' width='42' height='42' rx='21' stroke='white' stroke-width='2'/%3E%3C/svg%3E%0A"); }
-
-pre[class*="language-"] {
- position: relative; }
-
-.c-btn.c-btn--playground {
- position: absolute;
- font-size: var(--step--1);
- bottom: .5rem;
- right: .5rem;
- offset-block-end: .5rem;
- offset-inline-end: .5rem; }
- @media all and (max-width: 768px) {
- .c-btn.c-btn--playground {
- display: none; } }
-
-button {
- border: none;
- background: none;
- font: inherit;
- cursor: pointer;
- line-height: inherit;
- display: inline-flex;
- align-items: center;
- justify-content: center; }
-
-.c-btn {
- background: none;
- border: none;
- font: inherit;
- font-family: var(--text-font);
- cursor: pointer;
- line-height: inherit;
- font-weight: 500;
- font-size: var(--step-0);
- display: inline-flex;
- padding: .75em 1.125em;
- align-items: center;
- justify-content: center;
- border-radius: var(--border-radius);
- transition: background-color .2s linear, border-color .2s linear; }
- .c-btn svg {
- color: inherit; }
-
-.c-btn--large {
- font-size: 1.125rem;
- padding: .88em 1.5em; }
-
-.c-btn--block {
- display: flex;
- width: 100%; }
-
-a.c-btn {
- text-decoration: none;
- display: inline-flex;
- flex-wrap: wrap;
- gap: .5rem;
- align-items: center; }
-
-.c-btn--primary {
- background-color: var(--primary-button-background-color);
- color: var(--primary-button-text-color); }
- .c-btn--primary:hover {
- background-color: var(--primary-button-hover-color); }
-
-.c-btn--secondary {
- background-color: var(--secondary-button-background-color);
- color: var(--secondary-button-text-color);
- box-shadow: 0 1px 2px rgba(16, 24, 40, 0.1); }
- .c-btn--secondary:hover {
- background-color: var(--secondary-button-hover-color); }
-
-.c-btn--ghost {
- color: var(--body-text-color);
- border: 1px solid var(--border-color); }
- .c-btn--ghost:hover {
- border-color: var(--link-color); }
-
-.docs-site-nav {
- display: flex;
- flex-direction: column;
- flex: 1;
- grid-column: 1 / -1;
- grid-row: 1; }
- .docs-site-nav ul {
- list-style: none;
- font-size: var(--step-1);
- margin-top: 1rem;
- margin-block-start: 1rem;
- margin-bottom: 2rem;
- margin-block-end: 2rem; }
- @media all and (min-width: 1023px) {
- .docs-site-nav ul {
- font-size: var(--step-0);
- margin-top: 0;
- margin-block-start: 0;
- margin-bottom: 0;
- margin-block-end: 0;
- align-items: center;
- display: flex; } }
- .docs-site-nav .flexer {
- display: flex;
- justify-self: flex-end;
- align-self: flex-end; }
- .docs-site-nav a:not(.c-btn) {
- text-decoration: none;
- color: inherit;
- transition: color .2s linear; }
- .docs-site-nav a:not(.c-btn):hover {
- color: var(--link-color); }
- .docs-site-nav a:not(.c-btn)[aria-current="page"],
- .docs-site-nav a:not(.c-btn)[aria-current="true"] {
- color: var(--link-color);
- text-decoration: none;
- font-weight: 500; }
-
-@media all and (min-width: 1023px) {
- .docs-nav-panel {
- display: flex;
- flex-direction: row;
- justify-content: center; } }
-
-.docs-nav-panel[data-open="false"] {
- display: none; }
-
-@media all and (min-width: 1023px) {
- .docs-nav-panel[data-open="true"] {
- display: flex;
- flex-direction: row;
- justify-content: center; } }
-
-@media all and (min-width: 1023px) {
- .docs-nav-panel .mobile-only {
- display: none; } }
-
-.docs-site-nav-toggle {
- cursor: pointer;
- display: inline-flex;
- align-items: center;
- margin-left: .5rem;
- margin-right: -10px;
- margin-inline-start: .5rem;
- margin-inline-end: -10px; }
- .docs-site-nav-toggle svg {
- width: 40px;
- height: 40px;
- color: var(--headings-color);
- fill: none;
- stroke-width: 4;
- stroke-linecap: round;
- stroke-linejoin: round; }
- .docs-site-nav-toggle #ham-top,
- .docs-site-nav-toggle #ham-middle,
- .docs-site-nav-toggle #ham-bottom {
- transition: all .2s linear; }
- .docs-site-nav-toggle #ham-top {
- transform-origin: 30px 37px; }
- .docs-site-nav-toggle #ham-bottom {
- transform-origin: 30px 63px; }
- .docs-site-nav-toggle[aria-expanded="true"] #ham-middle {
- opacity: 0; }
- .docs-site-nav-toggle[aria-expanded="true"] #ham-top {
- transform: rotate(41deg); }
- .docs-site-nav-toggle[aria-expanded="true"] #ham-bottom {
- transform: rotate(-41deg); }
-
-@media all and (min-width: 1023px) {
- .docs-site-nav {
- flex-direction: row;
- grid-column: auto;
- gap: 2rem; }
- .docs-site-nav ul {
- display: flex;
- gap: 2rem;
- font-size: var(--step-0); }
- .docs-site-nav ul li {
- margin-bottom: 0;
- margin-block-end: 0; }
- .docs-site-nav .flexer {
- order: 1; } }
-
-.docs-toc {
- margin: 2rem 0; }
-
-.c-toc ol {
- margin: 0; }
- .c-toc ol li {
- position: relative;
- margin-bottom: .25rem;
- margin-block-end: .25rem;
- padding-left: 1rem;
- padding-inline-start: 1rem; }
- .c-toc ol li > ol {
- margin-top: .25rem; }
- .c-toc ol li::before {
- content: "└";
- color: var(--icon-color);
- position: absolute;
- left: -.4rem;
- offset-inline-start: -.4rem; }
-
-.c-toc a {
- text-decoration: none;
- color: var(--headings-color); }
- .c-toc a:hover {
- color: var(--link-color); }
-
-.c-toc__label.c-toc__label {
- font-size: var(--step-0);
- color: var(--body-text-color);
- font-family: var(--text-font);
- margin-bottom: .5rem;
- margin-block-end: .5rem; }
-
-.c-toc__label {
- width: fit-content; }
- .c-toc__label button {
- color: var(--link-color);
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: space-between;
- font: inherit;
- font-size: inherit;
- font-weight: 500;
- width: 100%;
- height: 100%;
- text-align: left;
- line-height: 1.5;
- padding: 0;
- border-radius: 0;
- position: relative;
- border: none;
- transition: outline 0.1s linear; }
- .c-toc__label button svg {
- flex: none; }
-
-/* Styles for the accordion icon */
-.toc-trigger-icon {
- display: block !important;
- width: 0.75rem;
- height: 0.5rem;
- transform-origin: 50% 50%;
- margin-left: 3rem;
- margin-inline-start: 3rem;
- transition: all 0.1s linear;
- color: var(--color-neutral-400); }
- [aria-expanded="true"] .toc-trigger-icon {
- -ms-transform: translateY(-50%) rotate(180deg);
- transform: translateY(-50%) rotate(180deg); }
-
-.c-toc__panel[data-open="false"] {
- display: none; }
-
-.c-toc__panel[data-open="true"] {
- display: block; }
-
-.search {
- margin-bottom: 1.5rem; }
-
-.search__input-wrapper {
- position: relative; }
-
-.search__input {
- padding-left: 2.5rem;
- padding-inline-start: 2.5rem;
- outline-offset: 1px;
- width: 100%; }
-
-.search__icon {
- color: var(--body-text-color);
- position: absolute;
- top: 50%;
- offset-block-start: 50%;
- transform: translateY(-50%);
- left: .75rem;
- offset-inline-start: .75rem; }
-
-.algolia-docsearch-suggestion--highlight {
- background-color: var(--color-warning-300); }
-
-.alert {
- position: relative;
- display: grid;
- grid-template-columns: auto 1fr;
- padding: 1rem;
- gap: .75rem;
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem;
- align-items: start;
- font-size: .875rem;
- background-color: var(--body-background-color);
- border-radius: var(--border-radius); }
- .alert.alert--warning {
- border: 1px solid var(--color-rose-300); }
- .alert.alert--important {
- border: 1px solid var(--color-warning-300); }
- .alert.alert--tip {
- border: 1px solid var(--color-success-300); }
-
-[data-theme="dark"] .alert.alert--warning {
- border: 1px solid var(--color-rose-300); }
-
-[data-theme="dark"] .alert.alert--important {
- border: 1px solid var(--color-warning-300); }
-
-[data-theme="dark"] .alert.alert--tip {
- border: 1px solid var(--color-success-300); }
-
-.alert__icon {
- color: inherit;
- position: relative;
- top: 2px;
- offset-block-start: 2px; }
-
-.alert__type {
- font-weight: 500;
- margin-bottom: .25rem;
- margin-block-end: .25rem; }
-
-.alert--warning {
- color: var(--color-rose-600); }
-
-.alert--important {
- color: var(--color-warning-600); }
-
-.alert--tip {
- color: var(--color-success-600); }
-
-[data-theme="dark"] .alert--warning {
- color: var(--color-rose-400); }
-
-[data-theme="dark"] .alert--important {
- color: var(--color-warning-400); }
-
-[data-theme="dark"] .alert--tip {
- color: var(--color-success-400); }
-
-.alert__type {
- font-weight: 500;
- margin-bottom: .25rem; }
- .alert--warning .alert__type {
- color: var(--color-rose-700); }
- [data-theme="dark"] .alert--warning .alert__type {
- color: var(--color-rose-300); }
- .alert--important .alert__type {
- color: var(--color-warning-700); }
- [data-theme="dark"] .alert--important .alert__type {
- color: var(--color-warning-300); }
- .alert--tip .alert__type {
- color: var(--color-success-700); }
- [data-theme="dark"] .alert--tip .alert__type {
- color: var(--color-success-300); }
-
-.alert__learn-more {
- display: block;
- font-weight: 500;
- margin-top: .75rem;
- margin-block-start: .75rem; }
- .alert--warning .alert__learn-more {
- color: var(--color-rose-700); }
- [data-theme="dark"] .alert--warning .alert__learn-more {
- color: var(--color-rose-300); }
- .alert--important .alert__learn-more {
- color: var(--color-warning-700); }
- [data-theme="dark"] .alert--important .alert__learn-more {
- color: var(--color-warning-300); }
- .alert--tip .alert__learn-more {
- color: var(--color-success-700); }
- [data-theme="dark"] .alert--tip .alert__learn-more {
- color: var(--color-success-300); }
-
-.rule-categories {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
- gap: 2rem 1rem;
- margin-bottom: 3rem; }
- .rule-categories .rule-category {
- margin: 0;
- padding: 0;
- background: none;
- border: none; }
- .rule-categories .rule-category__description {
- flex: 1 1 45ch; }
-
-.rule-category {
- font-size: var(--step--1);
- display: flex;
- flex-wrap: wrap;
- align-items: flex-start;
- gap: 1rem;
- padding: 1rem;
- margin: 1.5rem 0;
- border-radius: var(--border-radius);
- border: 1px solid var(--divider-color);
- background-color: var(--lightest-background-color); }
- .rule-category p {
- margin: 0; }
- .rule-category .rule-category__description {
- flex: 1 1 30ch; }
-
-.rule {
- border-radius: var(--border-radius);
- background-color: var(--lightest-background-color);
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 1rem;
- padding: 1rem;
- margin: .5rem 0;
- position: relative; }
- .rule p:last-of-type {
- margin: 0; }
-
-.rule__content {
- flex: 1 1 35ch; }
-
-.rule__name {
- font-weight: 500;
- font-size: .875rem;
- margin-bottom: .25rem;
- margin-block-end: .25rem; }
- .rule__name::after {
- position: absolute;
- content: "";
- width: 100%;
- height: 100%;
- top: 0;
- offset-block-start: 0;
- left: 0;
- offset-inline-start: 0; }
-
-a.rule__name {
- text-decoration: none; }
- a.rule__name:hover {
- text-decoration: underline; }
-
-.rule__description {
- font-size: var(--step--1); }
-
-.rule__categories {
- font-size: .875rem;
- display: flex;
- align-items: center;
- gap: 1rem;
- border-radius: var(--border-radius);
- padding: 2px 4px; }
- .rule__categories p {
- display: inline-flex;
- margin: 0;
- align-items: center; }
- [data-theme="dark"] .rule__categories {
- background: var(--body-background-color); }
-
-.rule__status {
- color: var(--color-rose-500);
- background: var(--color-rose-50);
- border-radius: var(--border-radius);
- display: inline-block;
- font-weight: normal;
- margin-left: .5rem;
- margin-inline-start: .5rem;
- font-size: var(--step--1);
- padding: 0 .5rem; }
- [data-theme="dark"] .rule__status {
- background: var(--body-background-color); }
-
-.rule__categories__type[aria-hidden="true"] {
- opacity: .25; }
-
-/* related rules */
-.related-rules__list {
- display: flex;
- gap: .5rem;
- flex-wrap: wrap;
- justify-content: start; }
-
-.related-rules__list__item svg {
- color: inherit; }
-
-.related-rules__list__item a {
- text-decoration: none;
- color: var(--headings-color);
- padding: .625rem;
- display: inline-flex;
- gap: .5rem;
- align-items: center;
- border: 1px solid var(--divider-color);
- border-radius: var(--border-radius);
- background-color: var(--lightest-background-color); }
- .related-rules__list__item a:hover {
- color: var(--link-color);
- background-color: var(--lighter-background-color); }
-
-.languages-list {
- margin: 0;
- padding: 0;
- font-size: var(--step-0); }
- .languages-list li {
- margin: 0; }
- .languages-list li:last-of-type a {
- border-bottom: 0; }
- .languages-list a {
- color: inherit;
- display: block;
- width: 100%;
- padding: .75rem .1rem;
- text-decoration: none;
- display: flex;
- align-items: center;
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color); }
- .languages-list a[aria-current="true"] {
- font-weight: 500;
- color: var(--link-color); }
- .languages-list a[aria-current="true"]::after {
- content: "✔️"; }
- .languages-list a:hover {
- color: var(--link-color); }
-
-.languages-section .flag {
- font-size: 2em;
- margin-right: .5rem;
- margin-inline-end: .5rem; }
-
-.languages-section .languages-list {
- font-size: var(--step-1);
- border-left: 4px solid var(--tab-border-color);
- padding-left: 1rem;
- border-inline-start: 4px solid var(--tab-border-color);
- padding-inline-start: 1rem; }
-
-.versions-list {
- margin: 0;
- padding: 0;
- font-size: var(--step-1); }
- .versions-list li {
- margin: 0; }
- .versions-list li:last-of-type a {
- border-bottom: 0;
- border-block-end: 0; }
- .versions-list a {
- color: var(--link-color);
- display: block;
- width: 100%;
- padding: 1rem .5rem;
- text-decoration: none;
- display: flex;
- align-items: center;
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color); }
- .versions-list a[data-current="true"] {
- font-weight: 500;
- color: var(--link-color); }
- .versions-list a[data-current="true"]::after {
- content: "✔️"; }
- .versions-list a:hover {
- background-color: var(--lightest-background-color); }
-
-.versions-section .versions-list {
- font-size: var(--step-1);
- border-left: 4px solid var(--tab-border-color);
- padding-left: 1rem;
- border-inline-start: 4px solid var(--tab-border-color);
- padding-inline-start: 1rem; }
-
-.eslint-social-icons {
- margin-bottom: -1rem;
- margin-block-end: -1rem; }
- .eslint-social-icons ul {
- margin: 0;
- padding: 0;
- margin-left: -1rem;
- margin-inline-start: -1rem;
- display: inline-flex; }
- .eslint-social-icons ul li {
- margin: 0;
- display: inline-flex;
- align-items: center; }
- .eslint-social-icons ul li a {
- display: flex;
- padding: 1rem; }
-
-@media all and (min-width: 800px) {
- .hero .grid {
- display: grid;
- grid-template-columns: 2fr 1fr;
- grid-gap: 2rem;
- align-items: center; } }
-
-.hero .grid .span-1-7 {
- grid-column: 1 / 2; }
-
-.hero .grid .span-10-12 {
- grid-column: 2 / 3;
- justify-self: end; }
-
-.hero {
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color);
- background-color: var(--hero-background-color); }
- @media all and (min-width: 800px) {
- .hero {
- min-height: calc(285px + var(--space-xl-4xl)); } }
- .hero .content-container {
- padding: var(--space-xl-4xl) 0;
- margin: 0; }
- .hero > .content-container {
- margin: 0 auto;
- padding: 0 calc(1rem + 1vw);
- padding-bottom: 0;
- align-items: center; }
-
-.hero--homepage .section-title {
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem; }
-
-.hero--homepage .section-supporting-text {
- margin: 0;
- font-size: var(--step-1);
- text-align: left; }
-
-.hero--homepage .eslint-actions {
- font-size: var(--step-1);
- margin-top: 3rem;
- margin-block-start: 3rem; }
-
-.theme-switcher {
- display: inline-flex;
- align-items: center;
- gap: .5rem;
- position: relative; }
-
-.theme-switcher-label.theme-switcher-label {
- font-size: inherit;
- color: inherit;
- font: inherit;
- font-family: var(--text-font);
- margin: 0; }
-
-.theme-switcher__buttons {
- display: flex;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- background-color: var(--body-background-color); }
-
-.theme-switcher__button {
- flex: 0;
- box-shadow: var(--shadow-xs);
- padding: .625rem .875rem;
- display: inline-flex;
- align-items: center;
- margin: 0;
- width: 40px;
- height: 40px; }
- .theme-switcher__button:first-of-type {
- border-right: 0.5px solid var(--border-color);
- border-inline-end: 0.5px solid var(--border-color); }
- .theme-switcher__button:last-of-type {
- border-left: 0.5px solid var(--border-color);
- border-inline-start: 0.5px solid var(--border-color); }
- .theme-switcher__button .theme-switcher__icon {
- color: var(--icon-color); }
- .theme-switcher__button:hover .theme-switcher__icon {
- color: var(--link-color); }
-
-.theme-switcher__button[aria-pressed="true"] .theme-switcher__icon {
- color: var(--link-color); }
-
-.theme-switcher__button[aria-pressed="true"]:hover .theme-switcher__icon {
- color: var(--link-color); }
-
-.theme-switcher__button[aria-pressed="false"] .theme-switcher__icon {
- color: var(--icon-color); }
-
-.theme-switcher__button[aria-pressed="false"]:hover .theme-switcher__icon {
- color: var(--link-color); }
-
-.theme-switcher__button:hover .theme-switcher__icon {
- color: var(--link-color); }
-
-.version-switcher {
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem; }
-
-.switcher--language {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: .25rem .5rem;
- position: relative;
- min-width: 15rem;
- padding: 0; }
-
-.switcher--language .label__text {
- flex: 1 0 10ch; }
-
-.switcher--language .switcher__select {
- min-width: 15rem;
- flex: 1 0 15rem; }
-
-.language-switcher {
- display: inline-flex; }
-
-.docs-index a {
- border-radius: var(--border-radius);
- text-decoration: none;
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: .5rem .75rem;
- margin-left: -.75rem;
- margin-inline-start: -.75rem;
- color: var(--headings-color); }
- .docs-index a:hover, .docs-index a[aria-current="true"] {
- background-color: var(--docs-lightest-background-color);
- color: var(--link-color); }
-
-.docs-index__item {
- margin: 0; }
- .docs-index__item ul ul {
- padding-left: .75rem; }
- .docs-index__item[data-has-children] {
- margin-bottom: .5rem; }
-
-.docs-index > ul > .docs-index__item {
- margin-top: 1.5rem;
- margin-block-start: 1.5rem; }
- .docs-index > ul > .docs-index__item > a {
- color: var(--icon-color);
- text-transform: uppercase;
- letter-spacing: 1px;
- font-size: .875rem;
- font-weight: 500; }
-
-/* Styles for the accordion icon */
-.index-js .index-icon {
- display: block !important;
- width: 0.75rem;
- height: 0.5rem;
- transform-origin: 50% 50%;
- transition: all 0.1s linear;
- color: inherit; }
-
-.index-js [aria-expanded="true"] .index-icon {
- -ms-transform: rotate(180deg);
- transform: rotate(180deg); }
-
-.index-js [aria-hidden="true"] {
- display: none; }
-
-.index-js [aria-hidden="false"] {
- display: block; }
-
-.docs-index__list[data-open="false"] {
- display: none; }
- @media all and (min-width: 1023px) {
- .docs-index__list[data-open="false"] {
- display: block; } }
-
-.docs-index__list[data-open="true"] {
- display: block; }
- @media all and (min-width: 1023px) {
- .docs-index__list[data-open="true"] {
- display: block; } }
-
-.docs-index-toggle {
- cursor: pointer;
- display: flex;
- width: 100%;
- padding: .75rem 1.125rem;
- align-items: center;
- justify-content: space-between;
- gap: .5rem;
- font-weight: 500;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- background-color: var(--secondary-button-background-color);
- color: var(--secondary-button-text-color);
- box-shadow: 0 1px 2px rgba(16, 24, 40, 0.1); }
- .docs-index-toggle:hover {
- background-color: var(--secondary-button-hover-color); }
- @media all and (min-width: 1023px) {
- .docs-index-toggle {
- display: none; } }
- .docs-index-toggle svg {
- width: 1.5em;
- height: 1.5em;
- color: inherit;
- fill: none;
- stroke-width: 4;
- stroke-linecap: round;
- stroke-linejoin: round; }
- .docs-index-toggle #ham-top,
- .docs-index-toggle #ham-middle,
- .docs-index-toggle #ham-bottom {
- transition: all .2s linear; }
- .docs-index-toggle #ham-top {
- transform-origin: 30px 37px; }
- .docs-index-toggle #ham-bottom {
- transform-origin: 30px 63px; }
- .docs-index-toggle[aria-expanded="true"] #ham-middle {
- opacity: 0; }
- .docs-index-toggle[aria-expanded="true"] #ham-top {
- transform: rotate(41deg); }
- .docs-index-toggle[aria-expanded="true"] #ham-bottom {
- transform: rotate(-41deg); }
-
-.c-tabs pre {
- margin-top: 0;
- margin-block-start: 0; }
-
-.js-tabs .c-tabs__tablist {
- display: flex;
- justify-content: start; }
-
-.c-tabs__tab {
- background: none;
- border: none;
- margin: 0;
- color: inherit;
- font: inherit;
- cursor: pointer;
- line-height: inherit;
- font-weight: 500;
- font-size: var(--step-0);
- display: inline-flex;
- padding: .75rem 1.125rem;
- align-items: center;
- justify-content: center;
- border-radius: var(--border-radius) var(--border-radius) 0 0;
- transition: background-color .2s linear, border-color .2s linear; }
- .c-tabs__tab:hover {
- color: var(--link-color); }
- .c-tabs__tab[aria-selected="true"] {
- color: var(--link-color);
- background-color: var(--lightest-background-color); }
-
-.c-tabs__tabpanel {
- margin-bottom: 2rem;
- margin-block-end: 2rem;
- background-color: var(--lightest-background-color);
- border-radius: 0 var(--border-radius) var(--border-radius) var(--border-radius); }
- .js-tabs .c-tabs__tabpanel {
- margin-bottom: 0;
- margin-block-end: 0; }
-
-.c-tabs__tabpanel__title {
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem; }
-
-.js-tabs .c-tabs__tabpanel__title {
- display: none; }
-
-.resource {
- display: flex;
- border-radius: var(--border-radius);
- border: 1px solid var(--divider-color);
- background-color: var(--lightest-background-color);
- align-items: stretch;
- overflow: hidden;
- margin-bottom: .5rem;
- margin-block-end: .5rem;
- position: relative;
- transition: all .2s linear; }
- .resource:hover {
- background-color: var(--lighter-background-color); }
-
-.resource__image {
- flex: 1 0 5.5rem;
- max-width: 5.5rem;
- overflow: hidden;
- padding: .25rem; }
- .resource__image img {
- display: block;
- height: 100%;
- width: 100%;
- object-fit: contain; }
-
-.resource__content {
- flex: 4;
- padding: .75rem;
- align-self: center; }
-
-.resource__title {
- text-decoration: none;
- color: var(--headings-color);
- font-weight: 500;
- margin-bottom: .125rem; }
- .resource__title::after {
- content: "";
- position: absolute;
- left: 0;
- offset-inline-start: 0;
- top: 0;
- block-inline-start: 0;
- width: 100%;
- height: 100%; }
-
-.resource__domain,
-.resource__domain a {
- text-decoration: none;
- color: var(--body-text-color);
- font-size: .875rem; }
-
-.resource__icon {
- color: var(--headings-color);
- margin: 1rem;
- align-self: center; }
-
-.index {
- margin-bottom: 4rem;
- margin-block-end: 4rem; }
-
-.index__item {
- margin: 0; }
- .index__item a {
- display: block;
- color: inherit;
- text-decoration: none;
- padding: .625rem .875rem;
- font-size: var(--step-0);
- border-radius: var(--border-radius); }
- .index__item a:hover {
- color: var(--link-color); }
- .index__item a[aria-current="page"] {
- color: var(--link-color);
- background-color: var(--lightest-background-color);
- font-weight: 500; }
-
-.index__toggle {
- cursor: pointer;
- display: flex;
- width: 100%;
- padding: .75rem 1.125rem;
- align-items: center;
- justify-content: space-between;
- gap: .5rem;
- font-weight: 500;
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- background-color: var(--secondary-button-background-color);
- color: var(--secondary-button-text-color);
- box-shadow: 0 1px 2px rgba(16, 24, 40, 0.1); }
- .index__toggle:hover {
- background-color: var(--secondary-button-hover-color); }
- @media all and (min-width: 1023px) {
- .index__toggle {
- display: none; } }
- .index__toggle svg {
- width: 1.5em;
- height: 1.5em;
- color: inherit;
- fill: none;
- stroke-width: 4;
- stroke-linecap: round;
- stroke-linejoin: round; }
- .index__toggle #ham-top,
- .index__toggle #ham-middle,
- .index__toggle #ham-bottom {
- transition: all .2s linear; }
- .index__toggle #ham-top {
- transform-origin: 30px 37px; }
- .index__toggle #ham-bottom {
- transform-origin: 30px 63px; }
- .index__toggle[aria-expanded="true"] #ham-middle {
- opacity: 0; }
- .index__toggle[aria-expanded="true"] #ham-top {
- transform: rotate(41deg); }
- .index__toggle[aria-expanded="true"] #ham-bottom {
- transform: rotate(-41deg); }
-
-.index__list {
- display: block; }
- .index__list[data-open="false"] {
- display: none; }
- @media all and (min-width: 1023px) {
- .index__list[data-open="false"] {
- display: block; } }
- .index__list[data-open="true"] {
- display: block; }
- @media all and (min-width: 1023px) {
- .index__list[data-open="true"] {
- display: block; } }
-
-@media all and (max-width: 800px) {
- .hero-ad {
- display: none; } }
-
-#carbonads * {
- margin: initial;
- padding: initial; }
-
-#carbonads {
- display: inline-block;
- margin: 2rem 0;
- padding: .6em;
- font-size: 16px;
- line-height: 1.35;
- overflow: hidden;
- border-radius: 4px;
- background-color: var(--body-background-color);
- border: 1px solid var(--border-color);
- border-radius: var(--border-radius);
- box-shadow: 0 1px 4px 1px rgba(0, 0, 0, 0.1); }
- .docs-main #carbonads {
- margin: 0 0 2rem; }
- @media all and (max-width: 800px) {
- #carbonads {
- display: none !important; } }
-
-.jumbotron #carbonads {
- border: solid 1px rgba(111, 102, 153, 0.6);
- background-color: rgba(179, 179, 179, 0.15); }
-
-#carbonads a {
- font-weight: 500;
- color: inherit; }
-
-#carbonads a:hover {
- text-decoration: none;
- color: inherit; }
-
-.jumbotron #carbonads a {
- color: #eee; }
-
-.jumbotron #carbonads a:hover {
- color: #ccc; }
-
-#carbonads span {
- display: block;
- position: relative;
- overflow: hidden; }
-
-#carbonads .carbon-wrap {
- display: flex;
- flex-direction: column;
- max-width: 130px; }
-
-#carbonads .carbon-img img {
- display: block; }
-
-#carbonads .carbon-text {
- margin-top: 10px;
- font-size: 14px;
- text-align: left; }
-
-#carbonads .carbon-poweredby {
- display: block;
- margin-top: 10px;
- font-size: 10px;
- line-height: 1;
- letter-spacing: 1px;
- text-transform: uppercase; }
-
-@media only screen and (min-width: 320px) and (max-width: 759px) {
- #carbonads {
- margin-top: 0;
- font-size: 12px; }
- #carbonads .carbon-wrap {
- display: flex;
- flex-direction: row;
- max-width: 330px; }
- #carbonads .carbon-text {
- margin: 0 0 14px 10px;
- font-size: 14px;
- text-align: left; }
- #carbonads .carbon-poweredby {
- position: absolute;
- bottom: 0;
- left: 142px;
- font-size: 8px; } }
-
-@media all and (min-width: 1023px) {
- .grid {
- display: grid;
- grid-template-columns: repeat(12, 1fr);
- grid-gap: 2rem;
- align-items: start; } }
-
-.visually-hidden {
- clip: rect(0 0 0 0);
- clip-path: inset(100%);
- height: 1px;
- overflow: hidden;
- position: absolute;
- width: 1px;
- white-space: nowrap; }
-
-[hidden] {
- display: none !important; }
-
-@media all and (min-width: 1023px) {
- .mobile-only {
- display: none; } }
-
-@media all and (max-width: 1023px) {
- .desktop-only {
- display: none; } }
-
-.text.text {
- font-size: inherit;
- color: inherit;
- font: inherit;
- font-family: var(--text-font);
- margin: 0; }
-
-.color-brand {
- color: var(--link-color); }
-
-.font-weight-medium {
- font-weight: 500; }
-
-.center-text {
- text-align: center;
- grid-column: 1 / -1; }
-
-.text-dark {
- color: var(--headings-color); }
-
-.divider {
- border-bottom: 1px solid var(--divider-color);
- border-block-end: 1px solid var(--divider-color); }
-
-.fs-step--1 {
- font-size: .875rem; }
-
-.fs-step-0 {
- font-size: var(--step-0); }
-
-.fs-step-1 {
- font-size: var(--step-1); }
-
-.fs-step-2 {
- font-size: var(--step-2); }
-
-.fs-step-3 {
- font-size: var(--step-3); }
-
-.fs-step-4 {
- font-size: var(--step-4); }
-
-.fs-step-5 {
- font-size: var(--step-5); }
-
-.fs-step-6 {
- font-size: var(--step-6); }
-
-.grid--center-items {
- align-items: center; }
-
-.span-1-3 {
- grid-column: 1 / 4; }
-
-.span-1-4 {
- grid-column: 1 / 5; }
-
-.span-1-5 {
- grid-column: 1 / 6; }
-
-.span-1-6 {
- grid-column: 1 / 7; }
-
-.span-1-7 {
- grid-column: 1 / 8; }
-
-.span-1-12 {
- grid-column: 1 / -1; }
-
-.span-4-12 {
- grid-column: 4 / 13; }
-
-.span-6-12 {
- grid-column: 6 / 13; }
-
-.span-7-12 {
- grid-column: 7 / 13; }
-
-.span-8-12 {
- grid-column: 8 / 13; }
-
-.span-10-12 {
- grid-column: 10 / 13; }
-
-.span-11-12 {
- grid-column: 11 / 13; }
-
-.span-4-9 {
- grid-column: 4 / 10; }
-
-.span-4-11 {
- grid-column: 4 / 11; }
-
-.span-5-12 {
- grid-column: 5 / 12; }
-
-.span-3-10 {
- grid-column: 3 / 11; }
-
-.span-6-7 {
- grid-column: 6 / 8; }
-
-.span-5-8 {
- grid-column: 5 / 9; }
diff --git a/docs/src/assets/css/tokens/spacing.css b/docs/src/assets/css/tokens/spacing.css
deleted file mode 100644
index f15a0705ef6..00000000000
--- a/docs/src/assets/css/tokens/spacing.css
+++ /dev/null
@@ -1,52 +0,0 @@
-/* @link https://utopia.fyi/space/calculator?c=320,16,1.125,1440,16,1.25,6,2,&s=0.75|0.5|0.25,1.5|2|3|4|6|8,l-2xl|xl-3xl|xl-4xl */
-:root {
- --fc-3xs-min: (var(--fc-s-min) * 0.25);
- --fc-3xs-max: (var(--fc-s-max) * 0.25);
- --fc-2xs-min: (var(--fc-s-min) * 0.5);
- --fc-2xs-max: (var(--fc-s-max) * 0.5);
- --fc-xs-min: (var(--fc-s-min) * 0.75);
- --fc-xs-max: (var(--fc-s-max) * 0.75);
- --fc-s-min: (var(--f-0-min));
- --fc-s-max: (var(--f-0-max));
- --fc-m-min: (var(--fc-s-min) * 1.5);
- --fc-m-max: (var(--fc-s-max) * 1.5);
- --fc-l-min: (var(--fc-s-min) * 2);
- --fc-l-max: (var(--fc-s-max) * 2);
- --fc-xl-min: (var(--fc-s-min) * 3);
- --fc-xl-max: (var(--fc-s-max) * 3);
- --fc-2xl-min: (var(--fc-s-min) * 4);
- --fc-2xl-max: (var(--fc-s-max) * 4);
- --fc-3xl-min: (var(--fc-s-min) * 6);
- --fc-3xl-max: (var(--fc-s-max) * 6);
- --fc-4xl-min: (var(--fc-s-min) * 8);
- --fc-4xl-max: (var(--fc-s-max) * 8);
- /* T-shirt sizes */
- --space-3xs: calc(((var(--fc-3xs-min) / 16) * 1rem) + (var(--fc-3xs-max) - var(--fc-3xs-min)) * var(--fluid-bp));
- --space-2xs: calc(((var(--fc-2xs-min) / 16) * 1rem) + (var(--fc-2xs-max) - var(--fc-2xs-min)) * var(--fluid-bp));
- --space-xs: calc(((var(--fc-xs-min) / 16) * 1rem) + (var(--fc-xs-max) - var(--fc-xs-min)) * var(--fluid-bp));
- --space-s: calc(((var(--fc-s-min) / 16) * 1rem) + (var(--fc-s-max) - var(--fc-s-min)) * var(--fluid-bp));
- --space-m: calc(((var(--fc-m-min) / 16) * 1rem) + (var(--fc-m-max) - var(--fc-m-min)) * var(--fluid-bp));
- --space-l: calc(((var(--fc-l-min) / 16) * 1rem) + (var(--fc-l-max) - var(--fc-l-min)) * var(--fluid-bp));
- --space-xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
- --space-2xl: calc(((var(--fc-2xl-min) / 16) * 1rem) + (var(--fc-2xl-max) - var(--fc-2xl-min)) * var(--fluid-bp));
- --space-3xl: calc(((var(--fc-3xl-min) / 16) * 1rem) + (var(--fc-3xl-max) - var(--fc-3xl-min)) * var(--fluid-bp));
- --space-4xl: calc(((var(--fc-4xl-min) / 16) * 1rem) + (var(--fc-4xl-max) - var(--fc-4xl-min)) * var(--fluid-bp));
- /* One-up pairs */
- --space-3xs-2xs: calc(((var(--fc-3xs-min) / 16) * 1rem) + (var(--fc-2xs-max) - var(--fc-3xs-min)) * var(--fluid-bp));
- --space-2xs-xs: calc(((var(--fc-2xs-min) / 16) * 1rem) + (var(--fc-xs-max) - var(--fc-2xs-min)) * var(--fluid-bp));
- --space-xs-s: calc(((var(--fc-xs-min) / 16) * 1rem) + (var(--fc-s-max) - var(--fc-xs-min)) * var(--fluid-bp));
- --space-s-m: calc(((var(--fc-s-min) / 16) * 1rem) + (var(--fc-m-max) - var(--fc-s-min)) * var(--fluid-bp));
- --space-m-l: calc(((var(--fc-m-min) / 16) * 1rem) + (var(--fc-l-max) - var(--fc-m-min)) * var(--fluid-bp));
- --space-l-xl: calc(((var(--fc-l-min) / 16) * 1rem) + (var(--fc-xl-max) - var(--fc-l-min)) * var(--fluid-bp));
- --space-xl-2xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-2xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
- --space-2xl-3xl: calc(((var(--fc-2xl-min) / 16) * 1rem) + (var(--fc-3xl-max) - var(--fc-2xl-min)) * var(--fluid-bp));
- --space-3xl-4xl: calc(((var(--fc-3xl-min) / 16) * 1rem) + (var(--fc-4xl-max) - var(--fc-3xl-min)) * var(--fluid-bp));
- /* Custom pairs */
- --space-l-2xl: calc(((var(--fc-l-min) / 16) * 1rem) + (var(--fc-2xl-max) - var(--fc-l-min)) * var(--fluid-bp));
- --space-xl-3xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-3xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
- --space-xl-4xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-4xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
- --spacer-2x: 2rem;
- --spacer-3x: 3rem;
- --spacer-4x: 4rem;
- --spacer-6x: 6rem;
- --spacer-8x: 8rem; }
diff --git a/docs/src/assets/css/tokens/themes.css b/docs/src/assets/css/tokens/themes.css
deleted file mode 100644
index a0967bd75f1..00000000000
--- a/docs/src/assets/css/tokens/themes.css
+++ /dev/null
@@ -1,131 +0,0 @@
-:root {
- /* Tier 1 variables */
- --color-neutral-25: #FCFCFD;
- --color-neutral-50: #F9FAFB;
- --color-neutral-100: #F2F4F7;
- --color-neutral-200: #E4E7EC;
- --color-neutral-300: #D0D5DD;
- --color-neutral-400: #98A2B3;
- --color-neutral-500: #667085;
- --color-neutral-600: #475467;
- --color-neutral-700: #344054;
- --color-neutral-800: #1D2939;
- --color-neutral-900: #101828;
- --color-primary-25: #FBFBFF;
- --color-primary-50: #F6F6FE;
- --color-primary-100: #ECECFD;
- --color-primary-200: #DEDEFF;
- --color-primary-300: #CCCCFA;
- --color-primary-400: #B7B7FF;
- --color-primary-500: #A0A0F5;
- --color-primary-600: #8080F2;
- --color-primary-700: #6358D4;
- --color-primary-800: #4B32C3;
- --color-primary-900: #341BAB;
- --color-warning-25: #FFFCF5;
- --color-warning-50: #FFFAEB;
- --color-warning-100: #FEF0C7;
- --color-warning-200: #FEDF89;
- --color-warning-300: #FEC84B;
- --color-warning-400: #FDB022;
- --color-warning-500: #F79009;
- --color-warning-600: #DC6803;
- --color-warning-700: #B54708;
- --color-warning-800: #93370D;
- --color-warning-900: #7A2E0E;
- --color-success-25: #F6FEF9;
- --color-success-50: #ECFDF3;
- --color-success-100: #D1FADF;
- --color-success-200: #A6F4C5;
- --color-success-300: #6CE9A6;
- --color-success-400: #32D583;
- --color-success-500: #12B76A;
- --color-success-600: #039855;
- --color-success-700: #027A48;
- --color-success-800: #05603A;
- --color-success-900: #054F31;
- --color-rose-25: #FFF5F6;
- --color-rose-50: #FFF1F3;
- --color-rose-100: #FFE4E8;
- --color-rose-200: #FECDD6;
- --color-rose-300: #FEA3B4;
- --color-rose-400: #FD6F8E;
- --color-rose-500: #F63D68;
- --color-rose-600: #E31B54;
- --color-rose-700: #C01048;
- --color-rose-800: #A11043;
- --color-rose-900: #89123E;
- /* Tier 2 variables */
- --primary-button-background-color: var(--color-primary-800);
- --primary-button-hover-color: var(--color-primary-900);
- --primary-button-text-color: #fff;
- --secondary-button-background-color: var(--color-primary-50);
- --secondary-button-hover-color: var(--color-primary-100);
- --secondary-button-text-color: var(--color-brand);
- --ghost-button-background-color: var(--color-primary-50);
- --ghost-button-text-color: var(--color-brand);
- --color-brand: var(--color-primary-800);
- --body-background-color: #fff;
- --body-text-color: var(--color-neutral-500);
- --headings-color: var(--color-neutral-900);
- --border-color: var(--color-neutral-300);
- --divider-color: var(--color-neutral-200);
- --icon-color: var(--color-neutral-400);
- --dark-icon-color: var(--color-neutral-500);
- --link-color: var(--color-primary-800);
- --lighter-background-color: var(--color-neutral-100);
- --lightest-background-color: var(--color-neutral-50);
- --docs-lightest-background-color: var(--color-primary-50);
- --hero-background-color: var(--color-neutral-25);
- --footer-background-color: var(--color-neutral-25);
- --outline-color: var(--color-brand); }
-
-@media (prefers-color-scheme: dark) {
- --secondary-button-background-color: var(--color-neutral-700);
- --secondary-button-hover-color: var(--color-neutral-800);
- --secondary-button-text-color: var(--body-text-color);
- --body-background-color: var(--color-neutral-900);
- --body-text-color: var(--color-neutral-300);
- --headings-color: #fff;
- --divider-color: var(--color-neutral-600);
- --border-color: var(--color-neutral-500);
- --icon-color: var(--body-text-color);
- --dark-icon-color: #fff;
- --link-color: var(--color-primary-400);
- --lighter-background-color: var(--color-neutral-800);
- --lightest-background-color: var(--color-neutral-800);
- --hero-background-color: var(--color-neutral-800);
- --footer-background-color: var(--color-neutral-800);
- --outline-color: #fff; }
-
-html[data-theme="light"] {
- --body-background-color: #fff;
- --body-text-color: var(--color-neutral-500);
- --headings-color: var(--color-neutral-900);
- --border-color: var(--color-neutral-300);
- --divider-color: var(--color-neutral-200);
- --icon-color: var(--color-neutral-400);
- --dark-icon-color: var(--color-neutral-500);
- --link-color: var(--color-primary-800);
- --lighter-background-color: var(--color-neutral-100);
- --lightest-background-color: var(--color-neutral-50);
- --docs-lightest-background-color: var(--color-primary-50);
- --hero-background-color: var(--color-neutral-25);
- --footer-background-color: var(--color-neutral-25);
- --outline-color: var(--color-brand); }
-
-html[data-theme="dark"] {
- --body-background-color: var(--color-neutral-900);
- --body-text-color: var(--color-neutral-300);
- --headings-color: #fff;
- --divider-color: var(--color-neutral-600);
- --border-color: var(--color-neutral-500);
- --icon-color: var(--body-text-color);
- --dark-icon-color: #fff;
- --link-color: var(--color-primary-400);
- --lighter-background-color: var(--color-neutral-800);
- --lightest-background-color: var(--color-neutral-800);
- --docs-lightest-background-color: var(--color-neutral-800);
- --hero-background-color: var(--color-neutral-800);
- --footer-background-color: var(--color-neutral-800);
- --outline-color: #fff; }
diff --git a/docs/src/assets/css/tokens/typography.css b/docs/src/assets/css/tokens/typography.css
deleted file mode 100644
index 2dcc9f89ccb..00000000000
--- a/docs/src/assets/css/tokens/typography.css
+++ /dev/null
@@ -1,64 +0,0 @@
-/* @link https://utopia.fyi/type/calculator?c=320,16,1.125,1280,16,1.25,6,2,&s=0.75|0.5|0.25,1.5|2|3|4|6,s-l */
-:root {
- --fluid-min-width: 320;
- --fluid-max-width: 1280;
- --fluid-screen: 100vw;
- --fluid-bp: calc((var(--fluid-screen) - var(--fluid-min-width) / 16 * 1rem) / (var(--fluid-max-width) - var(--fluid-min-width))); }
-
-@media screen and (min-width: 1280px) {
- :root {
- --fluid-screen: calc(var(--fluid-max-width) * 1px); } }
-
-:root {
- --f--2-min: 12.64;
- --f--2-max: 10.24;
- --step--2: calc(((var(--f--2-min) / 16) * 1rem) + (var(--f--2-max) - var(--f--2-min)) * var(--fluid-bp));
- --f--1-min: 14.22;
- --f--1-max: 12.80;
- --step--1: calc(((var(--f--1-min) / 16) * 1rem) + (var(--f--1-max) - var(--f--1-min)) * var(--fluid-bp));
- --f-0-min: 16.00;
- --f-0-max: 16.00;
- --step-0: calc(((var(--f-0-min) / 16) * 1rem) + (var(--f-0-max) - var(--f-0-min)) * var(--fluid-bp));
- --f-1-min: 18.00;
- --f-1-max: 20.00;
- --step-1: calc(((var(--f-1-min) / 16) * 1rem) + (var(--f-1-max) - var(--f-1-min)) * var(--fluid-bp));
- --f-2-min: 20.25;
- --f-2-max: 25.00;
- --step-2: calc(((var(--f-2-min) / 16) * 1rem) + (var(--f-2-max) - var(--f-2-min)) * var(--fluid-bp));
- --f-3-min: 22.78;
- --f-3-max: 31.25;
- --step-3: calc(((var(--f-3-min) / 16) * 1rem) + (var(--f-3-max) - var(--f-3-min)) * var(--fluid-bp));
- --f-4-min: 25.63;
- --f-4-max: 39.06;
- --step-4: calc(((var(--f-4-min) / 16) * 1rem) + (var(--f-4-max) - var(--f-4-min)) * var(--fluid-bp));
- --f-5-min: 28.83;
- --f-5-max: 48.83;
- --step-5: calc(((var(--f-5-min) / 16) * 1rem) + (var(--f-5-max) - var(--f-5-min)) * var(--fluid-bp));
- --f-6-min: 32.44;
- --f-6-max: 61.04;
- --step-6: calc(((var(--f-6-min) / 16) * 1rem) + (var(--f-6-max) - var(--f-6-min)) * var(--fluid-bp)); }
-
-:root {
- --mono-font: "Space Mono", monospace;
- --text-font: "Inter",
- -apple-system,
- BlinkMacSystemFont,
- "Segoe UI",
- Roboto,
- Helvetica,
- Arial,
- sans-serif,
- "Apple Color Emoji",
- "Segoe UI Emoji",
- "Segoe UI Symbol";
- --display-font: "Space Grotesk",
- -apple-system,
- BlinkMacSystemFont,
- "Segoe UI",
- Roboto,
- Helvetica,
- Arial,
- sans-serif,
- "Apple Color Emoji",
- "Segoe UI Emoji",
- "Segoe UI Symbol"; }
diff --git a/docs/src/assets/css/tokens/ui.css b/docs/src/assets/css/tokens/ui.css
deleted file mode 100644
index 175480d1cee..00000000000
--- a/docs/src/assets/css/tokens/ui.css
+++ /dev/null
@@ -1,5 +0,0 @@
-:root {
- --shadow-lg: 0px 12px 16px -4px rgba(16, 24, 40, 0.1),
- 0px 4px 6px -2px rgba(16, 24, 40, 0.05);
- --shadow-xs: 0px 1px 2px rgba(16, 24, 40, 0.05);
- --border-radius: .5rem; }
diff --git a/docs/src/assets/images/architecture/dependency.svg b/docs/src/assets/images/architecture/dependency.svg
new file mode 100644
index 00000000000..1609b53e1d9
--- /dev/null
+++ b/docs/src/assets/images/architecture/dependency.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-dowhilestatement.svg b/docs/src/assets/images/code-path-analysis/example-dowhilestatement.svg
new file mode 100644
index 00000000000..f81d36123c4
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-dowhilestatement.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-forinstatement.svg b/docs/src/assets/images/code-path-analysis/example-forinstatement.svg
new file mode 100644
index 00000000000..a6bc754b1be
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-forinstatement.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-forstatement-for-ever.svg b/docs/src/assets/images/code-path-analysis/example-forstatement-for-ever.svg
new file mode 100644
index 00000000000..4d334ca62d9
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-forstatement-for-ever.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-forstatement.svg b/docs/src/assets/images/code-path-analysis/example-forstatement.svg
new file mode 100644
index 00000000000..aa0ccf0d82f
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-forstatement.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-hello-world.svg b/docs/src/assets/images/code-path-analysis/example-hello-world.svg
new file mode 100644
index 00000000000..fc28d1fdaf9
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-hello-world.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-ifstatement-chain.svg b/docs/src/assets/images/code-path-analysis/example-ifstatement-chain.svg
new file mode 100644
index 00000000000..0944c3bcf59
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-ifstatement-chain.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-ifstatement.svg b/docs/src/assets/images/code-path-analysis/example-ifstatement.svg
new file mode 100644
index 00000000000..b83c67b5106
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-ifstatement.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-switchstatement-has-default.svg b/docs/src/assets/images/code-path-analysis/example-switchstatement-has-default.svg
new file mode 100644
index 00000000000..5d6d73998b3
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-switchstatement-has-default.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-switchstatement.svg b/docs/src/assets/images/code-path-analysis/example-switchstatement.svg
new file mode 100644
index 00000000000..e43e5e11190
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-switchstatement.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-trystatement-try-catch-finally.svg b/docs/src/assets/images/code-path-analysis/example-trystatement-try-catch-finally.svg
new file mode 100644
index 00000000000..60ec1cdf69b
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-trystatement-try-catch-finally.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-trystatement-try-catch.svg b/docs/src/assets/images/code-path-analysis/example-trystatement-try-catch.svg
new file mode 100644
index 00000000000..a2a0c8af250
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-trystatement-try-catch.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-trystatement-try-finally.svg b/docs/src/assets/images/code-path-analysis/example-trystatement-try-finally.svg
new file mode 100644
index 00000000000..68c7801b7cd
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-trystatement-try-finally.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-when-there-is-a-function-f.svg b/docs/src/assets/images/code-path-analysis/example-when-there-is-a-function-f.svg
new file mode 100644
index 00000000000..53bb946cf16
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-when-there-is-a-function-f.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-when-there-is-a-function-g.svg b/docs/src/assets/images/code-path-analysis/example-when-there-is-a-function-g.svg
new file mode 100644
index 00000000000..4d3fe12b4a8
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-when-there-is-a-function-g.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/example-whilestatement.svg b/docs/src/assets/images/code-path-analysis/example-whilestatement.svg
new file mode 100644
index 00000000000..f03944389cd
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/example-whilestatement.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/helo.svg b/docs/src/assets/images/code-path-analysis/helo.svg
new file mode 100644
index 00000000000..cd72a37d9af
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/helo.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/loop-event-example-for-1.svg b/docs/src/assets/images/code-path-analysis/loop-event-example-for-1.svg
new file mode 100644
index 00000000000..727ec12b132
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/loop-event-example-for-1.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/loop-event-example-for-2.svg b/docs/src/assets/images/code-path-analysis/loop-event-example-for-2.svg
new file mode 100644
index 00000000000..70d762f38bc
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/loop-event-example-for-2.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/loop-event-example-for-3.svg b/docs/src/assets/images/code-path-analysis/loop-event-example-for-3.svg
new file mode 100644
index 00000000000..5adea136b40
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/loop-event-example-for-3.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/loop-event-example-for-4.svg b/docs/src/assets/images/code-path-analysis/loop-event-example-for-4.svg
new file mode 100644
index 00000000000..99389751f34
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/loop-event-example-for-4.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/loop-event-example-for-5.svg b/docs/src/assets/images/code-path-analysis/loop-event-example-for-5.svg
new file mode 100644
index 00000000000..070decb1292
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/loop-event-example-for-5.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/loop-event-example-while-1.svg b/docs/src/assets/images/code-path-analysis/loop-event-example-while-1.svg
new file mode 100644
index 00000000000..7d0c1a02d68
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/loop-event-example-while-1.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/loop-event-example-while-2.svg b/docs/src/assets/images/code-path-analysis/loop-event-example-while-2.svg
new file mode 100644
index 00000000000..d5c31e276ca
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/loop-event-example-while-2.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/code-path-analysis/loop-event-example-while-3.svg b/docs/src/assets/images/code-path-analysis/loop-event-example-while-3.svg
new file mode 100644
index 00000000000..3f4e02c17db
--- /dev/null
+++ b/docs/src/assets/images/code-path-analysis/loop-event-example-while-3.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/arrow-left.svg b/docs/src/assets/images/icons/arrow-left.svg
index 26dc029137b..83483a7f256 100644
--- a/docs/src/assets/images/icons/arrow-left.svg
+++ b/docs/src/assets/images/icons/arrow-left.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/arrow-right.svg b/docs/src/assets/images/icons/arrow-right.svg
index 2d71ef09d38..22bb24fc3d4 100644
--- a/docs/src/assets/images/icons/arrow-right.svg
+++ b/docs/src/assets/images/icons/arrow-right.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/arrow-top-right.svg b/docs/src/assets/images/icons/arrow-top-right.svg
index 511f454600c..58bbed85264 100644
--- a/docs/src/assets/images/icons/arrow-top-right.svg
+++ b/docs/src/assets/images/icons/arrow-top-right.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/chevron-down.svg b/docs/src/assets/images/icons/chevron-down.svg
index 8a83c957d17..b09f7f73216 100644
--- a/docs/src/assets/images/icons/chevron-down.svg
+++ b/docs/src/assets/images/icons/chevron-down.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/copy.svg b/docs/src/assets/images/icons/copy.svg
index 2d67ceb5a9e..24fc6afae9c 100644
--- a/docs/src/assets/images/icons/copy.svg
+++ b/docs/src/assets/images/icons/copy.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/correct.svg b/docs/src/assets/images/icons/correct.svg
index eb95b879c02..4f589241cb2 100644
--- a/docs/src/assets/images/icons/correct.svg
+++ b/docs/src/assets/images/icons/correct.svg
@@ -1,5 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/discord.svg b/docs/src/assets/images/icons/discord.svg
index ed238b18e51..16bae7b3c46 100644
--- a/docs/src/assets/images/icons/discord.svg
+++ b/docs/src/assets/images/icons/discord.svg
@@ -1,11 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/facebook.svg b/docs/src/assets/images/icons/facebook.svg
index 685449eedbb..194c8348502 100644
--- a/docs/src/assets/images/icons/facebook.svg
+++ b/docs/src/assets/images/icons/facebook.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/features-list-icon.svg b/docs/src/assets/images/icons/features-list-icon.svg
index f86c388b41c..2e576cff9fd 100644
--- a/docs/src/assets/images/icons/features-list-icon.svg
+++ b/docs/src/assets/images/icons/features-list-icon.svg
@@ -1,4 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/github-icon-mono.svg b/docs/src/assets/images/icons/github-icon-mono.svg
index 6a945577bf2..f73b88b55b4 100644
--- a/docs/src/assets/images/icons/github-icon-mono.svg
+++ b/docs/src/assets/images/icons/github-icon-mono.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/github-img.svg b/docs/src/assets/images/icons/github-img.svg
index 9912529161c..51ad25a46eb 100644
--- a/docs/src/assets/images/icons/github-img.svg
+++ b/docs/src/assets/images/icons/github-img.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/github-large.svg b/docs/src/assets/images/icons/github-large.svg
index 50c1fd015aa..c540e36168f 100644
--- a/docs/src/assets/images/icons/github-large.svg
+++ b/docs/src/assets/images/icons/github-large.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/github-small.svg b/docs/src/assets/images/icons/github-small.svg
index 199cd41bd97..b410d3adcdf 100644
--- a/docs/src/assets/images/icons/github-small.svg
+++ b/docs/src/assets/images/icons/github-small.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/github.svg b/docs/src/assets/images/icons/github.svg
index eb3e9d70769..0f3149634b9 100644
--- a/docs/src/assets/images/icons/github.svg
+++ b/docs/src/assets/images/icons/github.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/google.svg b/docs/src/assets/images/icons/google.svg
index a45c2a3d94b..8b149df54a9 100644
--- a/docs/src/assets/images/icons/google.svg
+++ b/docs/src/assets/images/icons/google.svg
@@ -1,10 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/incorrect.svg b/docs/src/assets/images/icons/incorrect.svg
index b226bdddff4..666811ebe47 100644
--- a/docs/src/assets/images/icons/incorrect.svg
+++ b/docs/src/assets/images/icons/incorrect.svg
@@ -1,5 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/languages.svg b/docs/src/assets/images/icons/languages.svg
index fc10dc90559..2653515fe68 100644
--- a/docs/src/assets/images/icons/languages.svg
+++ b/docs/src/assets/images/icons/languages.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/learn-more-arrow.svg b/docs/src/assets/images/icons/learn-more-arrow.svg
index a3a66802d5e..8aab0b95e40 100644
--- a/docs/src/assets/images/icons/learn-more-arrow.svg
+++ b/docs/src/assets/images/icons/learn-more-arrow.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/link.svg b/docs/src/assets/images/icons/link.svg
index 856e3ae7cf9..6dfe15866b0 100644
--- a/docs/src/assets/images/icons/link.svg
+++ b/docs/src/assets/images/icons/link.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/linkedin.svg b/docs/src/assets/images/icons/linkedin.svg
index 804d62205f5..a7c36f64e25 100644
--- a/docs/src/assets/images/icons/linkedin.svg
+++ b/docs/src/assets/images/icons/linkedin.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/menu.svg b/docs/src/assets/images/icons/menu.svg
index c3db936136b..d068dbd04db 100644
--- a/docs/src/assets/images/icons/menu.svg
+++ b/docs/src/assets/images/icons/menu.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/minus-circle.svg b/docs/src/assets/images/icons/minus-circle.svg
index 49b35593aef..f8e8023389a 100644
--- a/docs/src/assets/images/icons/minus-circle.svg
+++ b/docs/src/assets/images/icons/minus-circle.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/npm.svg b/docs/src/assets/images/icons/npm.svg
index 34e9597cbd2..c9baf323174 100644
--- a/docs/src/assets/images/icons/npm.svg
+++ b/docs/src/assets/images/icons/npm.svg
@@ -1,10 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/open-collectione-mono.svg b/docs/src/assets/images/icons/open-collectione-mono.svg
index 2ac85b4e1b2..660478343ac 100644
--- a/docs/src/assets/images/icons/open-collectione-mono.svg
+++ b/docs/src/assets/images/icons/open-collectione-mono.svg
@@ -1,11 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/opencollective-img.svg b/docs/src/assets/images/icons/opencollective-img.svg
index 5ecb1f71758..a3b46dcd5d4 100644
--- a/docs/src/assets/images/icons/opencollective-img.svg
+++ b/docs/src/assets/images/icons/opencollective-img.svg
@@ -1,4 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/plus-circle.svg b/docs/src/assets/images/icons/plus-circle.svg
index e65aae3b596..58533a0b7bd 100644
--- a/docs/src/assets/images/icons/plus-circle.svg
+++ b/docs/src/assets/images/icons/plus-circle.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/search.svg b/docs/src/assets/images/icons/search.svg
index 2cd46bff5c4..6c70237669b 100644
--- a/docs/src/assets/images/icons/search.svg
+++ b/docs/src/assets/images/icons/search.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/icons/twitter.svg b/docs/src/assets/images/icons/twitter.svg
index 54e9463107b..ffee249edae 100644
--- a/docs/src/assets/images/icons/twitter.svg
+++ b/docs/src/assets/images/icons/twitter.svg
@@ -1,3 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/logo/brand-colors.svg b/docs/src/assets/images/logo/brand-colors.svg
index 99017ddf9e1..2c2048de281 100644
--- a/docs/src/assets/images/logo/brand-colors.svg
+++ b/docs/src/assets/images/logo/brand-colors.svg
@@ -1,5 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/logo/eslint-logo-color.svg b/docs/src/assets/images/logo/eslint-logo-color.svg
index 86f7ef5635b..5a8dbfc6818 100644
--- a/docs/src/assets/images/logo/eslint-logo-color.svg
+++ b/docs/src/assets/images/logo/eslint-logo-color.svg
@@ -1,10 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/images/logo/eslint-logo-white.svg b/docs/src/assets/images/logo/eslint-logo-white.svg
index 250ab8d7327..2493dc4cfdf 100644
--- a/docs/src/assets/images/logo/eslint-logo-white.svg
+++ b/docs/src/assets/images/logo/eslint-logo-white.svg
@@ -1,10 +1 @@
-
+
\ No newline at end of file
diff --git a/docs/src/assets/js/components-index.js b/docs/src/assets/js/components-index.js
index 87eb53ef901..9e3bc0f5cf9 100644
--- a/docs/src/assets/js/components-index.js
+++ b/docs/src/assets/js/components-index.js
@@ -6,7 +6,7 @@
if (matchMedia) {
const mq = window.matchMedia("(max-width: 1023px)");
- mq.addListener(WidthChange);
+ mq.addEventListener('change', WidthChange);
WidthChange(mq);
}
diff --git a/docs/src/assets/js/focus-visible.js b/docs/src/assets/js/focus-visible.js
index 2ffed420f81..c95845112cf 100644
--- a/docs/src/assets/js/focus-visible.js
+++ b/docs/src/assets/js/focus-visible.js
@@ -224,7 +224,7 @@ function applyFocusVisiblePolyfill(scope) {
}
/**
- * When the polfyill first loads, assume the user is in keyboard modality.
+ * When the polyfill first loads, assume the user is in keyboard modality.
* If any event is received from a pointing device (e.g. mouse, pointer,
* touch), turn off keyboard modality.
* This accounts for situations where focus enters the page from the URL bar.
diff --git a/docs/src/assets/js/main.js b/docs/src/assets/js/main.js
index 1122d78bc9d..28ec0e1306b 100644
--- a/docs/src/assets/js/main.js
+++ b/docs/src/assets/js/main.js
@@ -2,11 +2,11 @@
var toc_trigger = document.getElementById("js-toc-label"),
toc = document.getElementById("js-toc-panel"),
body = document.getElementsByTagName("body")[0],
- open = true;
+ open = false;
if (toc && matchMedia) {
const mq = window.matchMedia("(max-width: 1023px)");
- mq.addListener(WidthChange);
+ mq.addEventListener('change', WidthChange);
WidthChange(mq);
}
@@ -24,7 +24,7 @@
toc.setAttribute("data-open", "false");
toc_trigger.setAttribute("aria-expanded", "false");
- headingButton.addEventListener("click", toggleTOC, false);
+ headingButton.addEventListener("click", toggleTOC, true);
} else {
toc_trigger.innerHTML = 'Table of Contents';
toc.setAttribute("data-open", "true");
@@ -53,7 +53,7 @@
if (matchMedia) {
const mq = window.matchMedia("(max-width: 1023px)");
- mq.addListener(WidthChange);
+ mq.addEventListener('change', WidthChange);
WidthChange(mq);
}
@@ -87,13 +87,13 @@
(function() {
var index_trigger = document.getElementById("js-docs-index-toggle"),
- index = document.getElementById("js-docs-index-list"),
+ index = document.getElementById("js-docs-index-panel"),
body = document.getElementsByTagName("body")[0],
open = false;
if (matchMedia) {
const mq = window.matchMedia("(max-width: 1023px)");
- mq.addListener(WidthChange);
+ mq.addEventListener('change', WidthChange);
WidthChange(mq);
}
@@ -154,20 +154,20 @@
})();
// add "Open in Playground" button to code blocks
-(function() {
- let blocks = document.querySelectorAll('pre[class*="language-"]');
- if (blocks) {
- blocks.forEach(function(block) {
- let button = document.createElement("a");
- button.classList.add('c-btn--playground');
- button.classList.add('c-btn');
- button.classList.add('c-btn--secondary');
- button.setAttribute("href", "#");
- button.innerText = "Open in Playground";
- block.appendChild(button);
- });
- }
-})();
+// (function() {
+// let blocks = document.querySelectorAll('pre[class*="language-"]');
+// if (blocks) {
+// blocks.forEach(function(block) {
+// let button = document.createElement("a");
+// button.classList.add('c-btn--playground');
+// button.classList.add('c-btn');
+// button.classList.add('c-btn--secondary');
+// button.setAttribute("href", "#");
+// button.innerText = "Open in Playground";
+// block.appendChild(button);
+// });
+// }
+// })();
@@ -205,8 +205,8 @@ var util = {
var CollapsibleIndex = function(inst, options) {
var _options = Object.assign(CollapsibleIndexOptions, options);
var el = inst;
- var indexToggles = el.querySelectorAll(".docs-index > ul > .docs-index__item[data-has-children] > a"); // only top-most level
- var indexPanels = el.querySelectorAll(".docs-index > ul > .docs-index__item>[data-child-list]"); // the list
+ var indexToggles = el.querySelectorAll(".docs-index .docs__index__panel > ul > .docs-index__item[data-has-children] > a"); // only top-most level
+ var indexPanels = el.querySelectorAll(".docs-index .docs__index__panel > ul > .docs-index__item>[data-child-list]"); // the list
var accID = util.generateID("c-index-");
var init = function() {
@@ -276,3 +276,7 @@ if (index) {
allCollapsed: false
});
}
+
+document.addEventListener("DOMContentLoaded", () => {
+ anchors.add(".docs-content h2:not(.c-toc__label), .docs-content h3, .docs-content h4");
+});
\ No newline at end of file
diff --git a/docs/src/assets/js/search.js b/docs/src/assets/js/search.js
index e9f3a5e58f7..66d3b646372 100644
--- a/docs/src/assets/js/search.js
+++ b/docs/src/assets/js/search.js
@@ -19,7 +19,9 @@ const index = client.initIndex('eslint');
// page
const resultsElement = document.querySelector('#search-results');
+const resultsLiveRegion = document.querySelector('#search-results-announcement');
const searchInput = document.querySelector('#search');
+const searchClearBtn = document.querySelector('#search__clear-btn');
//-----------------------------------------------------------------------------
// Helpers
@@ -27,12 +29,12 @@ const searchInput = document.querySelector('#search');
/**
* Executes a search against the Algolia index.
- * @param {string} query The search query to execute.
+ * @param {string} query The search query to execute.
* @returns {Promise
>} The search results.
*/
function fetchSearchResults(query) {
return index.search(query, {
- facetFilters: ["tags:docs"]
+ // facetFilters: ["tags:docs"]
}).then(({ hits }) => hits);
}
@@ -44,6 +46,8 @@ function clearSearchResults() {
while (resultsElement.firstChild) {
resultsElement.removeChild(resultsElement.firstChild);
}
+ resultsElement.innerHTML = "";
+ searchClearBtn.setAttribute('hidden', '');
}
/**
@@ -58,18 +62,28 @@ function displaySearchResults(results) {
if (results.length) {
const list = document.createElement("ul");
+ list.setAttribute('role', 'list');
+ list.classList.add('search-results__list');
resultsElement.append(list);
-
+ resultsElement.setAttribute('data-results', 'true');
+
for (const result of results) {
const listItem = document.createElement('li');
+ listItem.classList.add('search-results__item');
+ const maxLvl = Math.max(...Object.keys(result._highlightResult.hierarchy).map(k => Number(k.substring(3))));
listItem.innerHTML = `
- ${result.hierarchy.lvl0}
- ${result._highlightResult.hierarchy.lvl0.value}
+
+ ${typeof result._highlightResult.content !== 'undefined' ? result._highlightResult.content.value : result._highlightResult.hierarchy[`lvl${maxLvl}`].value}
`.trim();
list.append(listItem);
}
+ searchClearBtn.removeAttribute('hidden');
+
} else {
+ resultsLiveRegion.innerHTML = "No results found.";
resultsElement.innerHTML = "No results found.";
+ resultsElement.setAttribute('data-results', 'false');
+ searchClearBtn.setAttribute('hidden', '');
}
}
@@ -78,45 +92,37 @@ function displaySearchResults(results) {
// Event Handlers
//-----------------------------------------------------------------------------
-
-
-
// listen for input changes
-searchInput.addEventListener('keyup', function (event) {
- const query = searchInput.value;
-
- if (query.length > 2) {
- fetchSearchResults(query)
- .then(displaySearchResults)
- .catch(clearSearchResults);
- } else {
- clearSearchResults();
- }
-});
-
- // add an event listenrer for a click on the search link
- // btnHandler('#search-link', function(){
-
- // // get the data
- // fetch('/search.json').then(function(response) {
- // return response.json();
- // }).then(function(response) {
-
- // searchIndex = response.search;
-
- // });
-
- // searchUI.toggleAttribute('hidden');
- // searchInput.focus();
+if(searchInput)
+ searchInput.addEventListener('keyup', function (e) {
+ const query = searchInput.value;
+
+ if(query.length) searchClearBtn.removeAttribute('hidden');
+ else searchClearBtn.setAttribute('hidden', '');
+
+ if (query.length > 2) {
+ fetchSearchResults(query)
+ .then(displaySearchResults)
+ .catch(clearSearchResults);
+
+ document.addEventListener('click', function(e) {
+ if(e.target !== resultsElement) clearSearchResults();
+ });
+ } else {
+ clearSearchResults();
+ }
+ });
- // // listen for input changes
- // searchInput.addEventListener('keyup', function(event) {
- // const str = searchInput.value;
- // if(str.length > 2) {
- // find(str);
- // } else {
- // clearResults();
- // }
- // });
+if(resultsElement)
+ resultsElement.addEventListener('keydown', function(e) {
+ if(e.key === "Escape") {
+ clearSearchResults();
+ }
+ }, true);
- // });
+if(searchClearBtn)
+ searchClearBtn.addEventListener('click', function(e) {
+ searchInput.value = '';
+ searchInput.focus();
+ clearSearchResults();
+ });
diff --git a/docs/src/assets/js/themes.js b/docs/src/assets/js/themes.js
index f080adcc9e6..e6071b21983 100644
--- a/docs/src/assets/js/themes.js
+++ b/docs/src/assets/js/themes.js
@@ -8,11 +8,6 @@
btn.setAttribute("aria-pressed", "false");
}
-
- let theme = window.localStorage.getItem("theme");
- document.documentElement.setAttribute('data-theme', theme);
- if (!theme) document.documentElement.setAttribute('data-theme', 'light');
-
document.addEventListener('DOMContentLoaded', function() {
var switcher = document.getElementById('js-theme-switcher');
switcher.removeAttribute('hidden');
@@ -21,11 +16,7 @@
dark_theme_toggle = document.getElementById('dark-theme-toggle');
// get any previously-chosen themes
- var theme = window.localStorage.getItem("theme");
- if (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches) {
- document.documentElement.setAttribute('data-theme', 'dark');
- }
- else if (theme) document.documentElement.setAttribute('data-theme', theme);
+ var theme = document.documentElement.getAttribute('data-theme');
if (theme == "light") {
enableToggle(light_theme_toggle);
diff --git a/docs/src/assets/scss/_docs-typography.scss b/docs/src/assets/scss/_docs-typography.scss
deleted file mode 100644
index d704721c282..00000000000
--- a/docs/src/assets/scss/_docs-typography.scss
+++ /dev/null
@@ -1,35 +0,0 @@
-.docs-main {
-
- h6,
- .h6 {
- font-size: var(--step-0);
- }
-
- h5,
- .h5 {
- font-size: var(--step-0); // 20
- }
-
- h4,
- .h4 {
- font-size: var(--step-1); // 24
- }
-
- h3,
- .h3 {
- font-size: var(--step-2);
- line-height: 1.2;
- }
-
- h2,
- .h2 {
- font-size: var(--step-3);
- line-height: 1.2;
- }
-
- h1,
- .h1 {
- font-size: var(--step-4);
- line-height: 1.2;
- }
-}
diff --git a/docs/src/assets/scss/_typography.scss b/docs/src/assets/scss/_typography.scss
deleted file mode 100644
index cd75ed3de3c..00000000000
--- a/docs/src/assets/scss/_typography.scss
+++ /dev/null
@@ -1,93 +0,0 @@
-body {
- font-size: var(--step-0);
- line-height: 1.5;
-}
-
-.eyebrow {
- color: var(--link-color);
- font-size: 1rem;
- font-weight: 500;
- display: block;
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem;
-}
-
-h1,
-h2,
-h3,
-h4,
-h5,
-h6 {
- font-family: var(--display-font);
- color: var(--headings-color);
- font-weight: 500;
- margin-top: 0;
- margin-block-start: 0;
-
-}
-
-h2,
-h3,
-h4,
-h5,
-h6 {
- .post-main &,
- .docs-main &,
- .components-main & {
- margin-top: 3rem;
- margin-bottom: 1.5rem;
- margin-block-start: 3rem;
- margin-block-end: 1.5rem;
-
- &:first-child {
- margin-top: 0;
- margin-block-start: 0;
- }
- }
-}
-
-
-h6,
-.h6 {
- font-size: var(--step-0);
-}
-
-h5,
-.h5 {
- font-size: var(--step-1);
-}
-
-h4,
-.h4 {
- font-size: var(--step-2);
-}
-
-h3,
-.h3 {
- font-size: var(--step-3);
- line-height: 1.2;
-}
-
-h2,
-.h2 {
- font-size: var(--step-4);
- line-height: 1.2;
-}
-
-h1,
-.h1 {
- font-size: var(--step-5);
- line-height: 1.2;
-}
-
-.h0 {
- font-size: var(--step-6);
- line-height: 1.2;
-}
-
-small,
-caption,
-cite,
-figcaption {
- font-size: var(--step--1);
-}
diff --git a/docs/src/assets/scss/_carbon-ads.scss b/docs/src/assets/scss/carbon-ads.scss
similarity index 88%
rename from docs/src/assets/scss/_carbon-ads.scss
rename to docs/src/assets/scss/carbon-ads.scss
index b5812dc0ee8..ccf578e6d9a 100644
--- a/docs/src/assets/scss/_carbon-ads.scss
+++ b/docs/src/assets/scss/carbon-ads.scss
@@ -11,11 +11,9 @@
#carbonads {
display: inline-block;
- margin: 2rem 0;;
+ margin: 2rem 0;
padding: .6em;
-
- font-size: 16px;
- line-height: 1.35;
+ font-size: 1rem;
overflow: hidden;
border-radius: 4px;
background-color: var(--body-background-color);
@@ -40,11 +38,12 @@
#carbonads a {
font-weight: 500;
color: inherit;
+ text-decoration: none;
}
#carbonads a:hover {
text-decoration: none;
- color: inherit;
+ color: var(--link-color);
}
.jumbotron #carbonads a {
@@ -58,13 +57,11 @@
#carbonads span {
display: block;
position: relative;
-
overflow: hidden;
}
#carbonads .carbon-wrap {
display: flex;
-
flex-direction: column;
max-width: 130px;
}
@@ -75,37 +72,36 @@
#carbonads .carbon-text {
margin-top: 10px;
-
- font-size: 14px;
+ line-height: 1rem;
+ font-size: .7em;
+ font-weight: 500;
text-align: left;
}
#carbonads .carbon-poweredby {
display: block;
margin-top: 10px;
- font-size: 10px;
+ font-size: 0.5rem;
+ font-weight: 500;
line-height: 1;
- letter-spacing: 1px;
+ letter-spacing: .1ch;
text-transform: uppercase;
}
@media only screen and (min-width: 320px) and (max-width: 759px) {
#carbonads {
margin-top: 0;
-
font-size: 12px;
}
#carbonads .carbon-wrap {
display: flex;
-
flex-direction: row;
max-width: 330px;
}
#carbonads .carbon-text {
margin: 0 0 14px 10px;
-
font-size: 14px;
text-align: left;
}
@@ -114,7 +110,6 @@
position: absolute;
bottom: 0;
left: 142px;
-
font-size: 8px;
}
}
diff --git a/docs/src/assets/scss/components/alert.scss b/docs/src/assets/scss/components/alert.scss
index b6ec304b730..ddd5c693d6a 100644
--- a/docs/src/assets/scss/components/alert.scss
+++ b/docs/src/assets/scss/components/alert.scss
@@ -8,22 +8,41 @@
margin-block-end: 1.5rem;
align-items: start;
font-size: .875rem;
- background-color: var(--body-background-color);
+ border: 1px solid currentColor;
border-radius: var(--border-radius);
&.alert--warning {
- border: 1px solid var(--color-rose-300);
+ background-color: var(--color-rose-25);
+ color: var(--color-rose-600);
+
+ [data-theme="dark"] & {
+ color: var(--color-rose-300);
+ background-color: var(--color-rose-900);
+ }
}
&.alert--important {
- border: 1px solid var(--color-warning-300);
+ background-color: var(--color-warning-25);
+ color: var(--color-warning-600);
+
+ [data-theme="dark"] & {
+ color: var(--color-warning-300);
+ background-color: var(--color-warning-900);
+ }
}
&.alert--tip {
- border: 1px solid var(--color-success-300);
+ background-color: var(--color-success-25);
+ color: var(--color-success-600);
+
+ [data-theme="dark"] & {
+ color: var(--color-success-300);
+ background-color: var(--color-success-900);
+ }
}
}
+
[data-theme="dark"] {
.alert {
&.alert--warning {
@@ -47,47 +66,21 @@
offset-block-start: 2px;
}
-.alert__type {
- font-weight: 500;
- margin-bottom: .25rem;
- margin-block-end: .25rem;
-}
-
-.alert--warning {
- color: var(--color-rose-600);
-}
-
-.alert--important {
- color: var(--color-warning-600);
-}
-
-.alert--tip {
- color: var(--color-success-600);
-}
-
-[data-theme="dark"] {
- .alert--warning {
- color: var(--color-rose-400);
- }
-
- .alert--important {
- color: var(--color-warning-400);
- }
-
- .alert--tip {
- color: var(--color-success-400);
- }
+.alert__text > p {
+ margin: 0;
}
.alert__type {
+ display: block;
font-weight: 500;
margin-bottom: .25rem;
+ margin-block-end: .25rem;
.alert--warning & {
color: var(--color-rose-700);
[data-theme="dark"] & {
- color: var(--color-rose-300);
+ color: var(--color-rose-200);
}
}
@@ -95,7 +88,7 @@
color: var(--color-warning-700);
[data-theme="dark"] & {
- color: var(--color-warning-300);
+ color: var(--color-warning-200);
}
}
@@ -103,7 +96,7 @@
color: var(--color-success-700);
[data-theme="dark"] & {
- color: var(--color-success-300);
+ color: var(--color-success-200);
}
}
}
@@ -119,7 +112,7 @@
color: var(--color-rose-700);
[data-theme="dark"] & {
- color: var(--color-rose-300);
+ color: var(--color-rose-200);
}
}
@@ -127,7 +120,7 @@
color: var(--color-warning-700);
[data-theme="dark"] & {
- color: var(--color-warning-300);
+ color: var(--color-warning-200);
}
}
@@ -135,25 +128,7 @@
color: var(--color-success-700);
[data-theme="dark"] & {
- color: var(--color-success-300);
+ color: var(--color-success-200);
}
}
}
-
-// .alert__remove-btn {
-// position: absolute;
-// right: 1rem;
-// top: 1rem;
-
-// .alert--warning & svg {
-// color: var(--color-rose-700);
-// }
-
-// .alert--important & svg {
-// color: var(--color-warning-700);
-// }
-
-// .alert--tip & svg {
-// color: var(--color-success-700);
-// }
-// }
diff --git a/docs/src/assets/scss/components/docs-index.scss b/docs/src/assets/scss/components/docs-index.scss
index 6f2a85478c7..2a4b86d140f 100644
--- a/docs/src/assets/scss/components/docs-index.scss
+++ b/docs/src/assets/scss/components/docs-index.scss
@@ -1,4 +1,4 @@
-.docs-index {
+.docs-index .docs-index__list {
a {
border-radius: var(--border-radius);
text-decoration: none;
@@ -15,6 +15,12 @@
background-color: var(--docs-lightest-background-color);
color: var(--link-color);
}
+
+ @media all and (max-width: 1023px) {
+ padding: .5rem 1rem;
+ margin-left: 0;
+ margin-inline-start: 0;
+ }
}
}
@@ -30,11 +36,11 @@
}
}
-.docs-index>ul>.docs-index__item {
+.docs-index__list > .docs-index__item {
margin-top: 1.5rem;
margin-block-start: 1.5rem;
- >a {
+ > a {
color: var(--icon-color);
text-transform: uppercase;
letter-spacing: 1px;
@@ -58,15 +64,15 @@
transform: rotate(180deg);
}
-.index-js [aria-hidden="true"] {
+.index-js ul[aria-hidden="true"] {
display: none;
}
-.index-js [aria-hidden="false"] {
+.index-js ul[aria-hidden="false"] {
display: block;
}
-.docs-index__list {
+.docs__index__panel {
&[data-open="false"] {
display: none;
@@ -95,9 +101,6 @@
font-weight: 500;
border: 1px solid var(--border-color);
border-radius: var(--border-radius);
- // background-color: var(--lightest-background-color);
- // color: inherit;
-
background-color: var(--secondary-button-background-color);
color: var(--secondary-button-text-color);
box-shadow: 0 1px 2px rgba(16, 24, 40, 0.1);
@@ -149,3 +152,15 @@
}
}
}
+
+.eslint-actions {
+ display: inline-flex;
+ flex-wrap: wrap;
+ flex-direction: column;
+ width: 100%;
+ gap: 1rem;
+
+ @media all and (min-width: 640px) {
+ flex-direction: row;
+ }
+}
diff --git a/docs/src/assets/scss/components/docs-navigation.scss b/docs/src/assets/scss/components/docs-navigation.scss
index 56409288e6c..f42a2ee17c5 100644
--- a/docs/src/assets/scss/components/docs-navigation.scss
+++ b/docs/src/assets/scss/components/docs-navigation.scss
@@ -35,6 +35,7 @@
text-decoration: none;
color: inherit;
transition: color .2s linear;
+ display: block;
&:hover {
color: var(--link-color);
diff --git a/docs/src/assets/scss/components/language-switcher.scss b/docs/src/assets/scss/components/language-switcher.scss
index f4d79b5fb3b..1aa9b2cea9f 100644
--- a/docs/src/assets/scss/components/language-switcher.scss
+++ b/docs/src/assets/scss/components/language-switcher.scss
@@ -1,11 +1,17 @@
.switcher--language {
display: flex;
align-items: center;
+ justify-content: center;
flex-wrap: wrap;
gap: .25rem .5rem;
position: relative;
- min-width: 15rem;
+ width: 100%;
padding: 0;
+ font-size: inherit;
+
+ @media all and (min-width: 800px) {
+ justify-content: flex-start;
+ }
}
.switcher--language .label__text {
@@ -14,8 +20,11 @@
.switcher--language .switcher__select {
- min-width: 15rem;
- flex: 1 0 15rem;
+ flex: 1 0 12rem;
+
+ @media all and (max-width: 800px) {
+ max-width: 250px;
+ }
}
.language-switcher {
diff --git a/docs/src/assets/scss/components/docs-resources.scss b/docs/src/assets/scss/components/resources.scss
similarity index 100%
rename from docs/src/assets/scss/components/docs-resources.scss
rename to docs/src/assets/scss/components/resources.scss
diff --git a/docs/src/assets/scss/components/rules.scss b/docs/src/assets/scss/components/rules.scss
index 27b1e492ad3..ec5217272c2 100644
--- a/docs/src/assets/scss/components/rules.scss
+++ b/docs/src/assets/scss/components/rules.scss
@@ -1,14 +1,41 @@
.rule-categories {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
- gap: 2rem 1rem;
+ gap: 0;
margin-bottom: 3rem;
+ background-color: var(--lightest-background-color);
+ border: 1px solid var(--divider-color);
+ border-radius: var(--border-radius);
.rule-category {
margin: 0;
- padding: 0;
+ padding: 1rem;
background: none;
border: none;
+
+ @media screen and (min-width:768px){
+ &:not(:first-child)::after {
+ content: "";
+ display: block;
+ padding: 1px;
+ border-left: 1px solid var(--divider-color);
+ left: 0px;
+ }
+ }
+
+ @media screen and (min-width:768px) and (max-width:1023px), screen and (min-width:1440px){
+ &:not(:first-child)::after {
+ height: 70%;
+ position: absolute;
+ }
+ }
+
+ @media screen and (min-width:1024px) and (max-width:1439px){
+ &:nth-child(2)::after {
+ height: 70%;
+ position: absolute;
+ }
+ }
}
.rule-category__description {
@@ -19,6 +46,7 @@
.rule-category {
font-size: var(--step--1);
display: flex;
+ position: relative;
flex-wrap: wrap;
align-items: flex-start;
gap: 1rem;
@@ -67,6 +95,14 @@
font-size: .875rem;
margin-bottom: .25rem;
margin-block-end: .25rem;
+}
+
+a.rule__name {
+ text-decoration: none;
+
+ &:hover {
+ text-decoration: underline;
+ }
&::after {
position: absolute;
@@ -80,14 +116,6 @@
}
}
-a.rule__name {
- text-decoration: none;
-
- &:hover {
- text-decoration: underline;
- }
-}
-
.rule__description {
font-size: var(--step--1);
}
@@ -133,7 +161,6 @@ a.rule__name {
}
}
-
/* related rules */
.related-rules__list {
@@ -166,3 +193,10 @@ a.rule__name {
}
}
}
+
+a.rule-list-item+a.rule-list-item::before {
+ content: ",";
+ display: inline-block;
+ margin-left: 5px;
+ margin-right: 5px;
+}
diff --git a/docs/src/assets/scss/components/search.scss b/docs/src/assets/scss/components/search.scss
index 60e01826315..8038e3a2cd4 100644
--- a/docs/src/assets/scss/components/search.scss
+++ b/docs/src/assets/scss/components/search.scss
@@ -1,11 +1,47 @@
+[type="search"]::-webkit-search-cancel-button,
+[type="search"]::-webkit-search-decoration {
+ -webkit-appearance: none;
+ appearance: none;
+}
+
+[type=search]::-ms-clear,
+[type=search]::-ms-reveal {
+ display: none;
+ width: 0;
+ height: 0;
+}
+
.search {
- margin-bottom: 1.5rem;
+ margin: 1rem 0;
+ position: relative;
}
-.search__input-wrapper {
+.search__input-wrapper,
+.search__inner-input-wrapper {
position: relative;
}
+.search__clear-btn {
+ color: var(--body-text-color);
+ position: absolute;
+ display: flex;
+ top: 50%;
+ offset-block-start: 50%;
+ transform: translateY(-50%);
+ right: 1.5rem;
+ offset-inline-end: 1.5rem;
+ z-index: 3;
+ padding: 0;
+
+ svg {
+ color: inherit;
+ width: 1rem;
+ height: 1rem;
+ border: 1px solid;
+ border-radius: 50%;
+ }
+}
+
.search__input {
padding-left: 2.5rem;
padding-inline-start: 2.5rem;
@@ -16,13 +52,110 @@
.search__icon {
color: var(--body-text-color);
position: absolute;
+ display: block;
top: 50%;
offset-block-start: 50%;
transform: translateY(-50%);
left: .75rem;
offset-inline-start: .75rem;
+ z-index: 3;
+}
+
+/* search results */
+.search .search-results {
+ font-size: .875rem;
+ background-color: var(--body-background-color);
+ position: relative;
+ z-index: 10;
+ width: 100%;
+ border-radius: 0 0 var(--border-radius) var(--border-radius);
+ border: 1px solid var(--divider-color);
+ position: rekative;
+ top: .25rem;
+ max-height: 400px;
+ overflow-y: auto;
+
+ @media all and (min-width: 1023px) {
+ box-shadow: var(--shadow-lg);
+ position: absolute;
+ top: calc(100% + .25rem);
+ }
+
+ &[data-results="true"] {
+ padding: 0;
+ }
+ &[data-results="false"] {
+ padding: 1rem;
+ }
+
+ &:empty {
+ display: none;
+ }
+}
+
+.search-results__list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+.search .search-results__item {
+ margin: 0;
+ padding: .875rem;
+ border-bottom: 1px solid var(--lightest-background-color);
+ border-block-end: 1px solid var(--lightest-background-color);
+ position: relative;
+
+ &:hover {
+ background-color: var(--lightest-background-color);
+ }
+}
+
+.search .search-results__item__title {
+ font-size: var(--step-0);
+ font-size: .875rem;
+ margin-bottom: 0;
+ font-family: var(--text-font);
+
+
+ a {
+ display: block;
+ text-decoration: none;
+ color: var(--link-color);
+ font: inherit;
+ padding: .25rem .75rem;
+
+ &:hover {
+ background-color: inherit;
+ color: var(--link-color);
+ }
+
+ &::after {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ content: "";
+ }
+ }
+}
+
+.search-results__item__context {
+ margin: 0;
+ font-size: .875rem;
+ padding-left: 1rem;
}
.algolia-docsearch-suggestion--highlight {
- background-color: var(--color-warning-300);
+ background-color: var(--color-brand);
+ color: #fff;
+ display: inline-block;
+ padding: 0 2px;
+ border-radius: 2px;
+
+ [data-theme="dark"] & {
+ background-color: var(--link-color);
+ color: var(--color-neutral-900);
+ }
}
diff --git a/docs/src/assets/scss/components/social-icons.scss b/docs/src/assets/scss/components/social-icons.scss
index 207c2b60e58..37902a9f588 100644
--- a/docs/src/assets/scss/components/social-icons.scss
+++ b/docs/src/assets/scss/components/social-icons.scss
@@ -16,7 +16,7 @@
a {
display: flex;
- padding: 1rem;
+ padding: 1rem .75rem;
}
}
}
diff --git a/docs/src/assets/scss/components/theme-switcher.scss b/docs/src/assets/scss/components/theme-switcher.scss
index 47b7cf3ff24..0fa59fe1845 100644
--- a/docs/src/assets/scss/components/theme-switcher.scss
+++ b/docs/src/assets/scss/components/theme-switcher.scss
@@ -27,8 +27,8 @@
display: inline-flex;
align-items: center;
margin: 0;
- width: 40px;
- height: 40px;
+ gap: .25rem;
+ color: inherit;
&:first-of-type {
border-right: .5px solid var(--border-color);
@@ -52,6 +52,8 @@
}
.theme-switcher__button[aria-pressed="true"] {
+ color: var(--link-color);
+
.theme-switcher__icon {
color: var(--link-color);
}
diff --git a/docs/src/assets/scss/components/toc.scss b/docs/src/assets/scss/components/toc.scss
index d906cda0604..d1f47a6faeb 100644
--- a/docs/src/assets/scss/components/toc.scss
+++ b/docs/src/assets/scss/components/toc.scss
@@ -2,6 +2,22 @@
margin: 2rem 0;
}
+.docs-toc {
+ .docs-aside & {
+ display: none;
+ }
+
+ @media all and (min-width: 1400px) {
+ display: none;
+ }
+
+ .docs-aside & {
+ @media all and (min-width: 1400px) {
+ display: block;
+ }
+ }
+}
+
.c-toc {
ol {
margin: 0;
@@ -13,7 +29,7 @@
padding-left: 1rem;
padding-inline-start: 1rem;
- > ol {
+ >ol {
margin-top: .25rem;
}
}
@@ -64,7 +80,6 @@
padding: 0;
border-radius: 0;
position: relative;
- border: none;
transition: outline 0.1s linear;
svg {
@@ -79,14 +94,14 @@
width: 0.75rem;
height: 0.5rem;
transform-origin: 50% 50%;
- margin-left: 3rem;
- margin-inline-start: 3rem;
+ margin-left: 2rem;
+ margin-inline-start: 2rem;
transition: all 0.1s linear;
color: var(--color-neutral-400);
[aria-expanded="true"] & {
- -ms-transform: translateY(-50%) rotate(180deg);
- transform: translateY(-50%) rotate(180deg);
+ -ms-transform: rotate(180deg);
+ transform: rotate(180deg);
}
}
@@ -96,6 +111,7 @@
&[data-open="false"] {
display: none;
}
+
&[data-open="true"] {
display: block;
}
diff --git a/docs/src/assets/scss/components/version-switcher.scss b/docs/src/assets/scss/components/version-switcher.scss
index dfbf9ac82c4..606b802395c 100644
--- a/docs/src/assets/scss/components/version-switcher.scss
+++ b/docs/src/assets/scss/components/version-switcher.scss
@@ -1,4 +1,4 @@
.version-switcher {
- margin-bottom: 1.5rem;
- margin-block-end: 1.5rem;
+ margin-bottom: .5rem;
+ margin-block-end: .5rem;
}
diff --git a/docs/src/assets/scss/_docs-footer.scss b/docs/src/assets/scss/docs-footer.scss
similarity index 93%
rename from docs/src/assets/scss/_docs-footer.scss
rename to docs/src/assets/scss/docs-footer.scss
index 950aa51834e..347afd3978e 100644
--- a/docs/src/assets/scss/_docs-footer.scss
+++ b/docs/src/assets/scss/docs-footer.scss
@@ -4,9 +4,11 @@
gap: 2rem;
justify-content: space-between;
align-items: baseline;
+ font-size: .875rem;
@media all and (max-width: 800px) {
padding: 1.5rem 0 4rem;
+ align-items: center;
}
}
diff --git a/docs/src/assets/scss/_docs-header.scss b/docs/src/assets/scss/docs-header.scss
similarity index 100%
rename from docs/src/assets/scss/_docs-header.scss
rename to docs/src/assets/scss/docs-header.scss
diff --git a/docs/src/assets/scss/_docs.scss b/docs/src/assets/scss/docs.scss
similarity index 70%
rename from docs/src/assets/scss/_docs.scss
rename to docs/src/assets/scss/docs.scss
index fc48d66e8fc..a9a07349728 100644
--- a/docs/src/assets/scss/_docs.scss
+++ b/docs/src/assets/scss/docs.scss
@@ -1,75 +1,97 @@
+/* docs layout styles */
+
+html {
+ scroll-behavior: smooth;
+}
+
.docs {
max-width: 1700px;
margin: 0 auto;
}
-.docs-ad {
+.docs-aside__content {
flex: 1;
}
.docs-wrapper {
- padding: 0 calc(1rem + 1vw);
+ padding: 0 var(--space-s-l);
flex: 1;
+ display: flex;
+ flex-direction: column;
@media all and (min-width: 1023px) {
display: grid;
grid-template-columns: minmax(250px, 1fr) minmax(0, 3.5fr);
- grid-gap: 0rem;
align-items: stretch;
}
}
-.docs-left-sidebar {
+.docs-nav {
grid-column: 1 / 2;
grid-row: 1 / 2;
- padding: calc(1rem + 1vw) 0;
+ padding-top: var(--space-l-xl);
+ padding-block-start: var(--space-l-xl);
font-size: .875rem;
- @media all and (min-width: 1023px) {
- border-right: 1px solid var(--divider-color);
- border-right: 1px solid var(--divider-color);
- padding-right: calc(1rem + 1vw);
- padding-inline-end: calc(1rem + 1vw);
- }
-
-
-
display: grid;
grid-auto-rows: max-content;
align-items: start;
+
+ @media all and (min-width: 1023px) {
+ padding: var(--space-l-xl) 0;
+ padding-right: var(--space-s-l);
+ padding-inline-end: var(--space-s-l);
+
+ border-right: 1px solid var(--divider-color);
+ border-inline-end: 1px solid var(--divider-color);
+ }
}
.docs-content {
grid-column: 2 / 3;
+ padding: var(--space-l-xl) 0;
+ flex: 1;
@media all and (min-width: 800px) {
display: grid;
- grid-template-columns: minmax(0, 3fr) minmax(230px, 1fr);
- grid-gap: 2rem;
+ grid-template-columns: minmax(0, 4fr) minmax(160px, 1fr);
+ grid-gap: 1rem;
}
@media all and (min-width: 1023px) {
- padding: calc(2rem + 1vw) 0;
+ padding: 0;
}
+ @media all and (min-width: 1300px) {
+ grid-gap: 2rem;
+ }
}
.docs-main {
- flex: 1 1 65ch;
+ flex: 1 1 68ch;
+
+ @media all and (min-width: 800px) {
+ padding-right: var(--space-s-l);
+ padding-inline-end: var(--space-s-l);
+
+ border-right: 1px solid var(--divider-color);
+ border-inline-end: 1px solid var(--divider-color);
+ }
@media all and (min-width: 1023px) {
- padding: 0 2rem;
+ padding: var(--space-l-xl) var(--space-l-2xl);
}
}
-.docs-right-sidebar {
+.docs-aside {
grid-column: 2 / 3;
-
display: flex;
flex-direction: column;
- flex: 1 1 200px;
+ @media all and (min-width: 800px) {
+ padding: var(--space-l-xl) 0;
+ }
}
.docs-toc {
@@ -84,8 +106,8 @@
margin: 3rem 0;
}
-div[data-correct-code],
-div[data-incorrect-code] {
+div.correct,
+div.incorrect {
position: relative;
&::after {
@@ -97,13 +119,13 @@ div[data-incorrect-code] {
}
}
-div[data-correct-code] {
+div.correct {
&::after {
content: url("data:image/svg+xml,%3Csvg width='45' height='44' viewBox='0 0 45 44' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='1.5' y='1' width='42' height='42' rx='21' fill='%23ECFDF3'/%3E%3Cpath d='M30.5 16L19.5 27L14.5 22' stroke='%2312B76A' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Crect x='1.5' y='1' width='42' height='42' rx='21' stroke='white' stroke-width='2'/%3E%3C/svg%3E%0A");
}
}
-div[data-incorrect-code] {
+div.incorrect {
&::after {
content: url("data:image/svg+xml,%3Csvg width='45' height='44' viewBox='0 0 45 44' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect x='1.5' y='1' width='42' height='42' rx='21' fill='%23FFF1F3'/%3E%3Cpath d='M28.5 16L16.5 28M16.5 16L28.5 28' stroke='%23F63D68' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Crect x='1.5' y='1' width='42' height='42' rx='21' stroke='white' stroke-width='2'/%3E%3C/svg%3E%0A");
}
diff --git a/docs/src/assets/scss/_site-footer.scss b/docs/src/assets/scss/eslint-site-footer.scss
similarity index 100%
rename from docs/src/assets/scss/_site-footer.scss
rename to docs/src/assets/scss/eslint-site-footer.scss
diff --git a/docs/src/assets/scss/_header.scss b/docs/src/assets/scss/eslint-site-header.scss
similarity index 98%
rename from docs/src/assets/scss/_header.scss
rename to docs/src/assets/scss/eslint-site-header.scss
index 199c42bc2a4..239d14d3428 100644
--- a/docs/src/assets/scss/_header.scss
+++ b/docs/src/assets/scss/eslint-site-header.scss
@@ -1,8 +1,8 @@
.site-header {
padding: .75rem 0;
border-top: 4px solid var(--link-color);
- border-bottom: 1px solid var(--divider-color);
border-block-start: 4px solid var(--link-color);
+ border-bottom: 1px solid var(--divider-color);
border-block-end: 1px solid var(--divider-color);
.content-container {
@@ -28,6 +28,7 @@
grid-column: 1 / -1;
grid-row: 1;
padding: .5rem 0;
+ z-index: 2;
}
.logo svg {
diff --git a/docs/src/assets/scss/_forms.scss b/docs/src/assets/scss/forms.scss
similarity index 87%
rename from docs/src/assets/scss/_forms.scss
rename to docs/src/assets/scss/forms.scss
index a6527d08593..e6d830c9897 100644
--- a/docs/src/assets/scss/_forms.scss
+++ b/docs/src/assets/scss/forms.scss
@@ -8,11 +8,10 @@
max-width: 100%;
min-width: 0px;
padding: .625rem .875rem;
- padding-right: calc(.875rem * 3);
- padding-inline-end: calc(.875rem * 3);
+ padding-right: calc(.875rem * 2.5);
+ padding-inline-end: calc(.875rem * 2.5);
font: inherit;
color: var(--body-text-color);
- color: inherit;
line-height: 1.3;
border: 1px solid var(--border-color);
border-radius: var(--border-radius);
@@ -20,15 +19,14 @@
background-color: var(--body-background-color);
background-image: url("data:image/svg+xml,%3Csvg width='20' height='21' viewBox='0 0 20 21' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M5 7.60938L10 12.6094L15 7.60938' stroke='%23667085' stroke-width='1.66667' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E%0A"), linear-gradient(to bottom, var(--body-background-color) 0%, var(--body-background-color) 100%);
background-repeat: no-repeat, repeat;
- background-position: right calc(.875rem * 1.5) top 50%, 0 0;
+ background-position: right .875rem top 50%,
+ 0 0;
background-size: 1em auto, 100%;
}
.label__text.label__text {
- display: block;
display: flex;
font-size: .875rem;
- color: inherit;
align-items: center;
gap: .5rem;
font-size: .875rem;
@@ -47,8 +45,9 @@ input {
font: inherit;
font-size: 1rem;
display: block;
+ line-height: 1.3;
min-width: 0;
- // width: 100%;
+ line-height: 1.3;
max-width: 100%;
background-color: var(--body-background-color);
color: inherit;
diff --git a/docs/src/assets/scss/_foundations.scss b/docs/src/assets/scss/foundations.scss
similarity index 78%
rename from docs/src/assets/scss/_foundations.scss
rename to docs/src/assets/scss/foundations.scss
index 4551eea116f..27849b3c145 100644
--- a/docs/src/assets/scss/_foundations.scss
+++ b/docs/src/assets/scss/foundations.scss
@@ -36,6 +36,17 @@ h6:target {
box-shadow: none;
}
+input:focus-visible {
+ outline: 2px solid var(--link-color);
+ border-color: var(--border-color);
+}
+
+input:focus {
+ outline: 2px solid transparent;
+ box-shadow: 0 0 0 2px var(--link-color);
+}
+
+
*,
*::before,
*::after {
@@ -148,6 +159,7 @@ hr {
code,
pre {
font-family: var(--mono-font);
+ font-variant-ligatures: none;
}
code {
@@ -334,3 +346,99 @@ nav {
outline-offset: 3px;
}
}
+
+
+/* typography */
+body {
+ font-size: var(--step-0);
+ line-height: 1.5;
+}
+
+.eyebrow {
+ color: var(--link-color);
+ font-size: 1rem;
+ font-weight: 500;
+ display: block;
+ margin-bottom: 1.5rem;
+ margin-block-end: 1.5rem;
+}
+
+h1,
+h2,
+h3,
+h4,
+h5,
+h6 {
+ font-family: var(--display-font);
+ color: var(--headings-color);
+ font-weight: 500;
+ margin-top: 0;
+ margin-block-start: 0;
+
+}
+
+h2,
+h3,
+h4,
+h5,
+h6 {
+
+ .docs-main &,
+ .components-main & {
+ margin-top: 3rem;
+ margin-bottom: 1.5rem;
+ margin-block-start: 3rem;
+ margin-block-end: 1.5rem;
+
+ &:first-child {
+ margin-top: 0;
+ margin-block-start: 0;
+ }
+ }
+}
+
+
+small,
+caption,
+cite,
+figcaption {
+ font-size: var(--step--1);
+}
+
+h6,
+.h6 {
+ font-size: var(--step-0);
+}
+
+h5,
+.h5 {
+ font-size: var(--step-0); // 20
+}
+
+h4,
+.h4 {
+ font-size: var(--step-1); // 24
+}
+
+h3,
+.h3 {
+ font-size: var(--step-2);
+ line-height: 1.2;
+}
+
+h2,
+.h2 {
+ font-size: var(--step-3);
+ line-height: 1.2;
+}
+
+h1,
+.h1 {
+ font-size: var(--step-4);
+ line-height: 1.2;
+}
+
+.h0 {
+ font-size: var(--step-6);
+ line-height: 1.2;
+}
diff --git a/docs/src/assets/scss/components/languages.scss b/docs/src/assets/scss/languages.scss
similarity index 100%
rename from docs/src/assets/scss/components/languages.scss
rename to docs/src/assets/scss/languages.scss
diff --git a/docs/src/assets/scss/print.scss b/docs/src/assets/scss/print.scss
index 04868a5966c..446c585ef41 100644
--- a/docs/src/assets/scss/print.scss
+++ b/docs/src/assets/scss/print.scss
@@ -196,6 +196,9 @@ ul {
page-break-inside: avoid;
}
+.docs-toc, .docs-index, .docs-aside, #skip-link{
+ display: none;
+}
@media print {
@page {
diff --git a/docs/src/assets/scss/styles.scss b/docs/src/assets/scss/styles.scss
index 435da5d5c35..e07b280a89d 100644
--- a/docs/src/assets/scss/styles.scss
+++ b/docs/src/assets/scss/styles.scss
@@ -4,15 +4,16 @@
@import "tokens/typography.scss";
@import "tokens/ui.scss";
-@import "_typography.scss";
-@import "_docs-typography.scss";
-@import "_foundations.scss";
-@import "_prism-syntax-highlighter.scss";
-@import "_docs-header.scss";
-@import "_docs-footer.scss";
-@import "_site-footer.scss";
-@import "_forms.scss";
-@import "_docs.scss";
+@import "foundations.scss";
+@import "syntax-highlighter.scss";
+@import "docs-header.scss";
+@import "docs-footer.scss";
+@import "eslint-site-footer.scss";
+@import "eslint-site-header.scss";
+@import "forms.scss";
+@import "docs.scss";
+@import "versions.scss";
+@import "languages.scss";
@import "components/buttons.scss";
@import "components/docs-navigation.scss";
@@ -20,18 +21,17 @@
@import "components/search.scss";
@import "components/alert.scss";
@import "components/rules.scss";
-@import "components/languages.scss";
-@import "components/versions.scss";
@import "components/social-icons.scss";
@import "components/hero.scss";
@import "components/theme-switcher.scss";
@import "components/version-switcher.scss";
@import "components/language-switcher.scss";
-@import "components/docs-index.scss";
+@import "components/docs-index.scss"; // docs index on the main docs pages
+@import "components/index.scss"; // used in component library
@import "components/tabs.scss";
-@import "components/docs-resources.scss";
@import "components/index.scss";
+@import "components/resources.scss";
-@import "_carbon-ads.scss";
+@import "carbon-ads.scss";
-@import "_utilities.scss";
+@import "utilities.scss";
diff --git a/docs/src/assets/scss/_prism-syntax-highlighter.scss b/docs/src/assets/scss/syntax-highlighter.scss
similarity index 97%
rename from docs/src/assets/scss/_prism-syntax-highlighter.scss
rename to docs/src/assets/scss/syntax-highlighter.scss
index e4c51087d16..85823a9dc1e 100644
--- a/docs/src/assets/scss/_prism-syntax-highlighter.scss
+++ b/docs/src/assets/scss/syntax-highlighter.scss
@@ -109,6 +109,10 @@ pre {
counter-reset: lineNumber;
}
+code .highlight-line {
+ font-variant-ligatures: none;
+}
+
code .highlight-line:before {
-webkit-user-select: none;
color: var(--icon-color);
diff --git a/docs/src/assets/scss/tokens/spacing.scss b/docs/src/assets/scss/tokens/spacing.scss
index 3525195276b..173401c043a 100644
--- a/docs/src/assets/scss/tokens/spacing.scss
+++ b/docs/src/assets/scss/tokens/spacing.scss
@@ -1,4 +1,18 @@
-/* @link https://utopia.fyi/space/calculator?c=320,16,1.125,1440,16,1.25,6,2,&s=0.75|0.5|0.25,1.5|2|3|4|6|8,l-2xl|xl-3xl|xl-4xl */
+/* @link https://utopia.fyi/space/calculator?c=320,16,1.125,1023,16,1.25,6,2,&s=0.75|0.5|0.25,1.5|2|3|4|6|8,l-2xl|xl-3xl|xl-4xl|l-3xl|s-l */
+
+:root {
+ --fluid-min-width: 320;
+ --fluid-max-width: 1023;
+
+ --fluid-screen: 100vw;
+ --fluid-bp: calc((var(--fluid-screen) - var(--fluid-min-width) / 16 * 1rem) / (var(--fluid-max-width) - var(--fluid-min-width)));
+}
+
+@media screen and (min-width: 1023px) {
+ :root {
+ --fluid-screen: calc(var(--fluid-max-width) * 1px);
+ }
+}
:root {
--fc-3xs-min: (var(--fc-s-min) * 0.25);
@@ -10,8 +24,8 @@
--fc-xs-min: (var(--fc-s-min) * 0.75);
--fc-xs-max: (var(--fc-s-max) * 0.75);
- --fc-s-min: (var(--f-0-min));
- --fc-s-max: (var(--f-0-max));
+ --fc-s-min: (var(--f-0-min, 16));
+ --fc-s-max: (var(--f-0-max, 16));
--fc-m-min: (var(--fc-s-min) * 1.5);
--fc-m-max: (var(--fc-s-max) * 1.5);
@@ -58,12 +72,6 @@
--space-l-2xl: calc(((var(--fc-l-min) / 16) * 1rem) + (var(--fc-2xl-max) - var(--fc-l-min)) * var(--fluid-bp));
--space-xl-3xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-3xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
--space-xl-4xl: calc(((var(--fc-xl-min) / 16) * 1rem) + (var(--fc-4xl-max) - var(--fc-xl-min)) * var(--fluid-bp));
-
-
- // spacing
- --spacer-2x: 2rem; // 32px
- --spacer-3x: 3rem; // 48px
- --spacer-4x: 4rem; // 64px
- --spacer-6x: 6rem; // 96px
- --spacer-8x: 8rem; // 128px
+ --space-l-3xl: calc(((var(--fc-l-min) / 16) * 1rem) + (var(--fc-3xl-max) - var(--fc-l-min)) * var(--fluid-bp));
+ --space-s-l: calc(((var(--fc-s-min) / 16) * 1rem) + (var(--fc-l-max) - var(--fc-s-min)) * var(--fluid-bp));
}
diff --git a/docs/src/assets/scss/tokens/themes.scss b/docs/src/assets/scss/tokens/themes.scss
index 1a262e020c0..11ced7f9ee5 100644
--- a/docs/src/assets/scss/tokens/themes.scss
+++ b/docs/src/assets/scss/tokens/themes.scss
@@ -93,26 +93,25 @@
}
@media (prefers-color-scheme: dark) {
- --secondary-button-background-color: var(--color-neutral-700);
- --secondary-button-hover-color: var(--color-neutral-800);
- --secondary-button-text-color: var(--body-text-color);
-
- --body-background-color: var(--color-neutral-900);
- --body-text-color: var(--color-neutral-300);
- --headings-color: #fff;
-
- --divider-color: var(--color-neutral-600);
- --border-color: var(--color-neutral-500);
-
- --icon-color: var(--body-text-color);
- --dark-icon-color: #fff;
- --link-color: var(--color-primary-400);
-
- --lighter-background-color: var(--color-neutral-800);
- --lightest-background-color: var(--color-neutral-800);
- --hero-background-color: var(--color-neutral-800);
- --footer-background-color: var(--color-neutral-800);
- --outline-color: #fff;
+ :root {
+ --body-background-color: var(--color-neutral-900);
+ --body-text-color: var(--color-neutral-300);
+ --headings-color: #fff;
+
+ --divider-color: var(--color-neutral-600);
+ --border-color: var(--color-neutral-500);
+
+ --icon-color: var(--body-text-color);
+ --dark-icon-color: #fff;
+ --link-color: var(--color-primary-400);
+
+ --lighter-background-color: var(--color-neutral-800);
+ --lightest-background-color: var(--color-neutral-800);
+ --docs-lightest-background-color: var(--color-neutral-800);
+ --hero-background-color: var(--color-neutral-800);
+ --footer-background-color: var(--color-neutral-800);
+ --outline-color: #fff;
+ }
}
diff --git a/docs/src/assets/scss/_utilities.scss b/docs/src/assets/scss/utilities.scss
similarity index 100%
rename from docs/src/assets/scss/_utilities.scss
rename to docs/src/assets/scss/utilities.scss
diff --git a/docs/src/assets/scss/components/versions.scss b/docs/src/assets/scss/versions.scss
similarity index 100%
rename from docs/src/assets/scss/components/versions.scss
rename to docs/src/assets/scss/versions.scss
diff --git a/docs/src/developer-guide/architecture/dependency.svg b/docs/src/developer-guide/architecture/dependency.svg
deleted file mode 100644
index 3b0c74c9b92..00000000000
--- a/docs/src/developer-guide/architecture/dependency.svg
+++ /dev/null
@@ -1,52 +0,0 @@
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/architecture/index.md b/docs/src/developer-guide/architecture/index.md
index b2ec2bc194b..1c580e469a2 100644
--- a/docs/src/developer-guide/architecture/index.md
+++ b/docs/src/developer-guide/architecture/index.md
@@ -2,10 +2,14 @@
title: Architecture
layout: doc
edit_link: https://github.com/eslint/eslint/edit/main/docs/src/developer-guide/architecture/index.md
-
+eleventyNavigation:
+ key: architecture
+ parent: developer guide
+ title: Architecture
+ order: 1
---
-
+
At a high level, there are a few key parts to ESLint:
diff --git a/docs/src/developer-guide/code-path-analysis.md b/docs/src/developer-guide/code-path-analysis.md
index 68348f3e7a2..17daf3196cc 100644
--- a/docs/src/developer-guide/code-path-analysis.md
+++ b/docs/src/developer-guide/code-path-analysis.md
@@ -16,7 +16,7 @@ if (a && b) {
bar();
```
-![Code Path Example](./code-path-analysis/helo.svg)
+![Code Path Example](../assets/images/code-path-analysis/helo.svg)
## Objects
@@ -100,10 +100,10 @@ module.exports = function(context) {
},
/**
- * This is called when a code path segment was leaved.
+ * This is called when a code path segment was left.
* In this time, the segment does not have the next segments yet.
*
- * @param {CodePathSegment} segment - The leaved code path segment.
+ * @param {CodePathSegment} segment - The left code path segment.
* @param {ASTNode} node - The current node.
* @returns {void}
*/
@@ -145,17 +145,17 @@ bar();
1. First, the analysis advances to the end of loop.
- ![Loop Event's Example 1](./code-path-analysis/loop-event-example-while-1.svg)
+ ![Loop Event's Example 1](../assets/images/code-path-analysis/loop-event-example-while-1.svg)
2. Second, it creates the looping path.
At this time, the next segment has existed already, so the `onCodePathSegmentStart` event is not fired.
It fires `onCodePathSegmentLoop` instead.
- ![Loop Event's Example 2](./code-path-analysis/loop-event-example-while-2.svg)
+ ![Loop Event's Example 2](../assets/images/code-path-analysis/loop-event-example-while-2.svg)
3. Last, it advances to the end.
- ![Loop Event's Example 3](./code-path-analysis/loop-event-example-while-3.svg)
+ ![Loop Event's Example 3](../assets/images/code-path-analysis/loop-event-example-while-3.svg)
For example 2:
@@ -170,29 +170,29 @@ bar();
First, the analysis advances to `ForStatement.update`.
The `update` segment is hovered at first.
- ![Loop Event's Example 1](./code-path-analysis/loop-event-example-for-1.svg)
+ ![Loop Event's Example 1](../assets/images/code-path-analysis/loop-event-example-for-1.svg)
2. Second, it advances to `ForStatement.body`.
Of course the `body` segment is preceded by the `test` segment.
It keeps the `update` segment hovering.
- ![Loop Event's Example 2](./code-path-analysis/loop-event-example-for-2.svg)
+ ![Loop Event's Example 2](../assets/images/code-path-analysis/loop-event-example-for-2.svg)
3. Third, it creates the looping path from `body` segment to `update` segment.
At this time, the next segment has existed already, so the `onCodePathSegmentStart` event is not fired.
It fires `onCodePathSegmentLoop` instead.
- ![Loop Event's Example 3](./code-path-analysis/loop-event-example-for-3.svg)
+ ![Loop Event's Example 3](../assets/images/code-path-analysis/loop-event-example-for-3.svg)
4. Fourth, also it creates the looping path from `update` segment to `test` segment.
At this time, the next segment has existed already, so the `onCodePathSegmentStart` event is not fired.
It fires `onCodePathSegmentLoop` instead.
- ![Loop Event's Example 4](./code-path-analysis/loop-event-example-for-4.svg)
+ ![Loop Event's Example 4](../assets/images/code-path-analysis/loop-event-example-for-4.svg)
5. Last, it advances to the end.
- ![Loop Event's Example 5](./code-path-analysis/loop-event-example-for-5.svg)
+ ![Loop Event's Example 5](../assets/images/code-path-analysis/loop-event-example-for-5.svg)
## Usage Examples
@@ -338,7 +338,7 @@ See Also:
console.log("Hello world!");
```
-![Hello World](./code-path-analysis/example-hello-world.svg)
+![Hello World](../assets/images/code-path-analysis/example-hello-world.svg)
### `IfStatement`
@@ -350,7 +350,7 @@ if (a) {
}
```
-![`IfStatement`](./code-path-analysis/example-ifstatement.svg)
+![`IfStatement`](../assets/images/code-path-analysis/example-ifstatement.svg)
### `IfStatement` (chain)
@@ -364,7 +364,7 @@ if (a) {
}
```
-![`IfStatement` (chain)](./code-path-analysis/example-ifstatement-chain.svg)
+![`IfStatement` (chain)](../assets/images/code-path-analysis/example-ifstatement-chain.svg)
### `SwitchStatement`
@@ -385,7 +385,7 @@ switch (a) {
}
```
-![`SwitchStatement`](./code-path-analysis/example-switchstatement.svg)
+![`SwitchStatement`](../assets/images/code-path-analysis/example-switchstatement.svg)
### `SwitchStatement` (has `default`)
@@ -410,7 +410,7 @@ switch (a) {
}
```
-![`SwitchStatement` (has `default`)](./code-path-analysis/example-switchstatement-has-default.svg)
+![`SwitchStatement` (has `default`)](../assets/images/code-path-analysis/example-switchstatement-has-default.svg)
### `TryStatement` (try-catch)
@@ -433,7 +433,7 @@ It creates the paths from `try` block to `catch` block at:
* The first throwable node (e.g. a function call) in the `try` block.
* The end of the `try` block.
-![`TryStatement` (try-catch)](./code-path-analysis/example-trystatement-try-catch.svg)
+![`TryStatement` (try-catch)](../assets/images/code-path-analysis/example-trystatement-try-catch.svg)
### `TryStatement` (try-finally)
@@ -451,7 +451,7 @@ If there is not `catch` block, `finally` block has two current segments.
At this time, `CodePath.currentSegments.length` is `2`.
One is the normal path, and another is the leaving path (`throw` or `return`).
-![`TryStatement` (try-finally)](./code-path-analysis/example-trystatement-try-finally.svg)
+![`TryStatement` (try-finally)](../assets/images/code-path-analysis/example-trystatement-try-finally.svg)
### `TryStatement` (try-catch-finally)
@@ -467,7 +467,7 @@ try {
last();
```
-![`TryStatement` (try-catch-finally)](./code-path-analysis/example-trystatement-try-catch-finally.svg)
+![`TryStatement` (try-catch-finally)](../assets/images/code-path-analysis/example-trystatement-try-catch-finally.svg)
### `WhileStatement`
@@ -481,7 +481,7 @@ while (a) {
}
```
-![`WhileStatement`](./code-path-analysis/example-whilestatement.svg)
+![`WhileStatement`](../assets/images/code-path-analysis/example-whilestatement.svg)
### `DoWhileStatement`
@@ -492,7 +492,7 @@ do {
} while (a);
```
-![`DoWhileStatement`](./code-path-analysis/example-dowhilestatement.svg)
+![`DoWhileStatement`](../assets/images/code-path-analysis/example-dowhilestatement.svg)
### `ForStatement`
@@ -506,7 +506,7 @@ for (let i = 0; i < 10; ++i) {
}
```
-![`ForStatement`](./code-path-analysis/example-forstatement.svg)
+![`ForStatement`](../assets/images/code-path-analysis/example-forstatement.svg)
### `ForStatement` (for ever)
@@ -517,7 +517,7 @@ for (;;) {
bar();
```
-![`ForStatement` (for ever)](./code-path-analysis/example-forstatement-for-ever.svg)
+![`ForStatement` (for ever)](../assets/images/code-path-analysis/example-forstatement-for-ever.svg)
### `ForInStatement`
@@ -527,7 +527,7 @@ for (let key in obj) {
}
```
-![`ForInStatement`](./code-path-analysis/example-forinstatement.svg)
+![`ForInStatement`](../assets/images/code-path-analysis/example-forinstatement.svg)
### When there is a function
@@ -546,8 +546,8 @@ It creates two code paths.
* The global's
- ![When there is a function](./code-path-analysis/example-when-there-is-a-function-g.svg)
+ ![When there is a function](../assets/images/code-path-analysis/example-when-there-is-a-function-g.svg)
* The function's
- ![When there is a function](./code-path-analysis/example-when-there-is-a-function-f.svg)
+ ![When there is a function](../assets/images/code-path-analysis/example-when-there-is-a-function-f.svg)
diff --git a/docs/src/developer-guide/code-path-analysis/example-dowhilestatement.svg b/docs/src/developer-guide/code-path-analysis/example-dowhilestatement.svg
deleted file mode 100644
index 4a3d5289dc8..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-dowhilestatement.svg
+++ /dev/null
@@ -1,100 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-forinstatement.svg b/docs/src/developer-guide/code-path-analysis/example-forinstatement.svg
deleted file mode 100644
index 00da11ecd4c..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-forinstatement.svg
+++ /dev/null
@@ -1,148 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-forstatement-for-ever.svg b/docs/src/developer-guide/code-path-analysis/example-forstatement-for-ever.svg
deleted file mode 100644
index b4bdb2337e7..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-forstatement-for-ever.svg
+++ /dev/null
@@ -1,63 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-forstatement.svg b/docs/src/developer-guide/code-path-analysis/example-forstatement.svg
deleted file mode 100644
index 376d91b4467..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-forstatement.svg
+++ /dev/null
@@ -1,201 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-hello-world.svg b/docs/src/developer-guide/code-path-analysis/example-hello-world.svg
deleted file mode 100644
index 26c40387cd1..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-hello-world.svg
+++ /dev/null
@@ -1,48 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-ifstatement-chain.svg b/docs/src/developer-guide/code-path-analysis/example-ifstatement-chain.svg
deleted file mode 100644
index 88c2b6e43d0..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-ifstatement-chain.svg
+++ /dev/null
@@ -1,203 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-ifstatement.svg b/docs/src/developer-guide/code-path-analysis/example-ifstatement.svg
deleted file mode 100644
index 7ea670afff7..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-ifstatement.svg
+++ /dev/null
@@ -1,122 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-switchstatement-has-default.svg b/docs/src/developer-guide/code-path-analysis/example-switchstatement-has-default.svg
deleted file mode 100644
index 26c45fa79ab..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-switchstatement-has-default.svg
+++ /dev/null
@@ -1,279 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-switchstatement.svg b/docs/src/developer-guide/code-path-analysis/example-switchstatement.svg
deleted file mode 100644
index 778017efdbc..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-switchstatement.svg
+++ /dev/null
@@ -1,232 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-trystatement-try-catch-finally.svg b/docs/src/developer-guide/code-path-analysis/example-trystatement-try-catch-finally.svg
deleted file mode 100644
index fbc00830294..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-trystatement-try-catch-finally.svg
+++ /dev/null
@@ -1,137 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-trystatement-try-catch.svg b/docs/src/developer-guide/code-path-analysis/example-trystatement-try-catch.svg
deleted file mode 100644
index c6f1879f03e..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-trystatement-try-catch.svg
+++ /dev/null
@@ -1,186 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-trystatement-try-finally.svg b/docs/src/developer-guide/code-path-analysis/example-trystatement-try-finally.svg
deleted file mode 100644
index 8b1fb92117f..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-trystatement-try-finally.svg
+++ /dev/null
@@ -1,139 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-when-there-is-a-function-f.svg b/docs/src/developer-guide/code-path-analysis/example-when-there-is-a-function-f.svg
deleted file mode 100644
index a91270022f3..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-when-there-is-a-function-f.svg
+++ /dev/null
@@ -1,99 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-when-there-is-a-function-g.svg b/docs/src/developer-guide/code-path-analysis/example-when-there-is-a-function-g.svg
deleted file mode 100644
index 7bde3ea8da5..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-when-there-is-a-function-g.svg
+++ /dev/null
@@ -1,47 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/example-whilestatement.svg b/docs/src/developer-guide/code-path-analysis/example-whilestatement.svg
deleted file mode 100644
index d833dc08a6d..00000000000
--- a/docs/src/developer-guide/code-path-analysis/example-whilestatement.svg
+++ /dev/null
@@ -1,172 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/helo.svg b/docs/src/developer-guide/code-path-analysis/helo.svg
deleted file mode 100644
index e2dd9f2228b..00000000000
--- a/docs/src/developer-guide/code-path-analysis/helo.svg
+++ /dev/null
@@ -1,113 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-1.svg b/docs/src/developer-guide/code-path-analysis/loop-event-example-for-1.svg
deleted file mode 100644
index 497554025ca..00000000000
--- a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-1.svg
+++ /dev/null
@@ -1,84 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-2.svg b/docs/src/developer-guide/code-path-analysis/loop-event-example-for-2.svg
deleted file mode 100644
index d35bddfe18f..00000000000
--- a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-2.svg
+++ /dev/null
@@ -1,110 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-3.svg b/docs/src/developer-guide/code-path-analysis/loop-event-example-for-3.svg
deleted file mode 100644
index a1af0e6d7eb..00000000000
--- a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-3.svg
+++ /dev/null
@@ -1,115 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-4.svg b/docs/src/developer-guide/code-path-analysis/loop-event-example-for-4.svg
deleted file mode 100644
index a4ee87ec543..00000000000
--- a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-4.svg
+++ /dev/null
@@ -1,115 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-5.svg b/docs/src/developer-guide/code-path-analysis/loop-event-example-for-5.svg
deleted file mode 100644
index cba3a010b5e..00000000000
--- a/docs/src/developer-guide/code-path-analysis/loop-event-example-for-5.svg
+++ /dev/null
@@ -1,149 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/loop-event-example-while-1.svg b/docs/src/developer-guide/code-path-analysis/loop-event-example-while-1.svg
deleted file mode 100644
index 8036529e7cb..00000000000
--- a/docs/src/developer-guide/code-path-analysis/loop-event-example-while-1.svg
+++ /dev/null
@@ -1,82 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/loop-event-example-while-2.svg b/docs/src/developer-guide/code-path-analysis/loop-event-example-while-2.svg
deleted file mode 100644
index 63355dd815d..00000000000
--- a/docs/src/developer-guide/code-path-analysis/loop-event-example-while-2.svg
+++ /dev/null
@@ -1,87 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/code-path-analysis/loop-event-example-while-3.svg b/docs/src/developer-guide/code-path-analysis/loop-event-example-while-3.svg
deleted file mode 100644
index cb21c43828b..00000000000
--- a/docs/src/developer-guide/code-path-analysis/loop-event-example-while-3.svg
+++ /dev/null
@@ -1,121 +0,0 @@
-
-
\ No newline at end of file
diff --git a/docs/src/developer-guide/development-environment.md b/docs/src/developer-guide/development-environment.md
index 0b4b45be1a6..75c0aaf5c3c 100644
--- a/docs/src/developer-guide/development-environment.md
+++ b/docs/src/developer-guide/development-environment.md
@@ -47,11 +47,15 @@ Now, the remote `upstream` points to the upstream source.
[Yeoman](http://yeoman.io) is a scaffold generator that ESLint uses to help streamline development of new rules. If you don't already have Yeoman installed, you can install it via npm:
- npm install -g yo
+```shell
+npm install -g yo
+```
Then, you can install the ESLint Yeoman generator:
- npm install -g generator-eslint
+```shell
+npm install -g generator-eslint
+```
Please see the [generator documentation](https://github.com/eslint/generator-eslint) for instructions on how to use it.
diff --git a/docs/src/developer-guide/nodejs-api.md b/docs/src/developer-guide/nodejs-api.md
index 105996ab87e..cefd83a1470 100644
--- a/docs/src/developer-guide/nodejs-api.md
+++ b/docs/src/developer-guide/nodejs-api.md
@@ -14,39 +14,6 @@ While ESLint is designed to be run on the command line, it's possible to use ESL
**Note:** Use undocumented parts of the API at your own risk. Only those parts that are specifically mentioned in this document are approved for use and will remain stable and reliable. Anything left undocumented is unstable and may change or be removed at any point.
-## Table of Contents
-
-* [ESLint]
- * [constructor()][eslint-constructor]
- * [lintFiles()][eslint-lintfiles]
- * [lintText()][eslint-linttext]
- * [getRulesMetaForResults()][eslint-getrulesmetaforresults]
- * [calculateConfigForFile()][eslint-calculateconfigforfile]
- * [isPathIgnored()][eslint-ispathignored]
- * [loadFormatter()][eslint-loadformatter]
- * [static version][eslint-version]
- * [static outputFixes()][eslint-outputfixes]
- * [static getErrorResults()][eslint-geterrorresults]
- * [LintResult type][lintresult]
- * [LintMessage type][lintmessage]
- * [SuppressedLintMessage type][suppressedlintmessage]
- * [EditInfo type][editinfo]
- * [LoadedFormatter type][loadedformatter]
-* [SourceCode](#sourcecode)
- * [splitLines()](#sourcecodesplitlines)
-* [Linter](#linter)
- * [verify()](#linterverify)
- * [verifyAndFix()](#linterverifyandfix)
- * [defineRule()](#linterdefinerule)
- * [defineRules()](#linterdefinerules)
- * [getRules()](#lintergetrules)
- * [defineParser()](#linterdefineparser)
- * [version](#linterversionlinterversion)
-* [RuleTester](#ruletester)
- * [Customizing RuleTester](#customizing-ruletester)
-
----
-
## ESLint class
The `ESLint` class is the primary class to use in Node.js applications.
@@ -289,7 +256,7 @@ This method loads a formatter. Formatters convert lint results to a human- or ma
The path to the file you want to check. The following values are allowed:
* `undefined`. In this case, loads the `"stylish"` built-in formatter.
* A name of [built-in formatters][builtin-formatters].
- * A name of [third-party formatters][thirdparty-formatters]. For examples:
+ * A name of [third-party formatters][third-party-formatters]. For examples:
* `"foo"` will load `eslint-formatter-foo`.
* `"@foo"` will load `@foo/eslint-formatter`.
* `"@foo/bar"` will load `@foo/eslint-formatter-bar`.
@@ -952,9 +919,9 @@ ruleTester.run("my-rule", myRule, {
---
-[configuration object]: ../user-guide/configuring
+[configuration object]: ../user-guide/configuring/
[builtin-formatters]: https://eslint.org/docs/user-guide/formatters/
-[thirdparty-formatters]: https://www.npmjs.com/search?q=eslintformatter
+[third-party-formatters]: https://www.npmjs.com/search?q=eslintformatter
[eslint]: #eslint-class
[eslint-constructor]: #-new-eslintoptions
[eslint-lintfiles]: #-eslintlintfilespatterns
diff --git a/docs/src/developer-guide/source-code.md b/docs/src/developer-guide/source-code.md
index d95f8a643d5..558434e15a8 100644
--- a/docs/src/developer-guide/source-code.md
+++ b/docs/src/developer-guide/source-code.md
@@ -14,7 +14,9 @@ ESLint is hosted at [GitHub](https://github.com/eslint/eslint) and uses [Git](ht
If you simply want to create a local copy of the source to play with, you can clone the main repository using this command:
- git clone git://github.com/eslint/eslint.git
+```shell
+git clone git://github.com/eslint/eslint.git
+```
If you're planning on contributing to ESLint, then it's a good idea to fork the repository. You can find instructions for forking a repository at [https://help.github.com/articles/fork-a-repo/](https://help.github.com/articles/fork-a-repo/). After forking the ESLint repository, you'll want to create a local copy of your fork.
@@ -27,8 +29,10 @@ Before you can get started developing, you'll need to have a couple of things in
Once you have a local copy and have Node.JS and npm installed, you'll need to install the ESLint dependencies:
- cd eslint
- npm install
+```shell
+cd eslint
+npm install
+```
Now when you run `eslint`, it will be running your local copy and showing your changes.
diff --git a/docs/src/developer-guide/unit-tests.md b/docs/src/developer-guide/unit-tests.md
index cc9a28e3b3b..a8ff6ecb5e3 100644
--- a/docs/src/developer-guide/unit-tests.md
+++ b/docs/src/developer-guide/unit-tests.md
@@ -14,7 +14,9 @@ Most parts of ESLint have unit tests associated with them. Unit tests are writte
When you first get the source code, you need to run `npm install` once initially to set ESLint for development. Once you've done that, you can run the tests via:
- npm test
+```shell
+npm test
+```
This automatically starts Mocha and runs all tests in the `tests` directory. You need only add yours and it will automatically be picked up when running tests.
@@ -22,7 +24,9 @@ This automatically starts Mocha and runs all tests in the `tests` directory. You
If you want to quickly run just one test file, you can do so by running Mocha directly and passing in the filename. For example:
- npm run test:cli tests/lib/rules/no-undef.js
+```shell
+npm run test:cli tests/lib/rules/no-undef.js
+```
If you want to run just one or a subset of `RuleTester` test cases, add `only: true` to each test case or wrap the test case in `RuleTester.only(...)` to add it automatically:
@@ -50,4 +54,6 @@ Running individual tests is useful when you're working on a specific bug and ite
The default timeout for tests in `npm test` is 10000ms. You may change the timeout by providing `ESLINT_MOCHA_TIMEOUT` environment variable, for example:
- ESLINT_MOCHA_TIMEOUT=20000 npm test
+```shell
+ESLINT_MOCHA_TIMEOUT=20000 npm test
+```
diff --git a/docs/src/developer-guide/working-with-rules.md b/docs/src/developer-guide/working-with-rules.md
index d13e921daa8..be6d971a390 100644
--- a/docs/src/developer-guide/working-with-rules.md
+++ b/docs/src/developer-guide/working-with-rules.md
@@ -41,7 +41,6 @@ module.exports = {
docs: {
description: "disallow unnecessary semicolons",
- category: "Possible Errors",
recommended: true,
url: "https://eslint.org/docs/rules/no-extra-semi"
},
@@ -70,7 +69,6 @@ The source file for a rule exports an object with the following properties.
* `docs` (object) is required for core rules of ESLint:
* `description` (string) provides the short description of the rule in the [rules index](../rules/)
- * `category` (string) specifies the heading under which the rule is listed in the [rules index](../rules/)
* `recommended` (boolean) is whether the `"extends": "eslint:recommended"` property in a [configuration file](../user-guide/configuring/configuration-files#extending-configuration-files) enables the rule
* `url` (string) specifies the URL at which the full documentation can be accessed (enabling code editors to provide a helpful link on highlighted rule violations)
@@ -732,7 +730,7 @@ Performance budget ok: 1443.736547ms (limit: 3409.090909090909ms)
### Per-rule Performance
-ESLint has a built-in method to track performance of individual rules. Setting the `TIMING` environment variable will trigger the display, upon linting completion, of the ten longest-running rules, along with their individual running time and relative performance impact as a percentage of total rule processing time.
+ESLint has a built-in method to track performance of individual rules. Setting the `TIMING` environment variable will trigger the display, upon linting completion, of the ten longest-running rules, along with their individual running time (rule creation + rule execution) and relative performance impact as a percentage of total rule processing time (rule creation + rule execution).
```bash
$ TIMING=1 eslint lib
diff --git a/docs/src/library/code-blocks.md b/docs/src/library/code-blocks.md
index 7db4d1ccfa6..222d3e68519 100644
--- a/docs/src/library/code-blocks.md
+++ b/docs/src/library/code-blocks.md
@@ -6,35 +6,35 @@ To indicate correct and incorrect code usage, some code blocks can have correct
## Usage
-To indicate that a code block is correct or incorrect, wrap the code block in a `div` and provide the `data-correct-code` and `data-incorrect-code` attributes, repsectively.
+To indicate that a code block is correct or incorrect, wrap the code block in a container labeled either `correct` or `incorrect`.
Make sure to leave space above and below the markdown code block to ensure it is rendered correctly.
-```html
-
+```text
+::: correct
`` `js
function() {
const another = [];
}
`` `
-
+:::
-
+::: incorrect
`` `js
function() {
const another = [];
}
`` `
-
+:::
```
## Examples
Correct usage:
-
+::: correct
```js
const { ESLint } = require("eslint");
@@ -61,11 +61,11 @@ const { ESLint } = require("eslint");
});
```
-
+:::
Incorrect usage:
-
+::: incorrect
```js
const { ESLint } = require("eslint");
@@ -92,4 +92,4 @@ const { ESLint } = require("eslint");
});
```
-
+:::
diff --git a/docs/src/library/library.json b/docs/src/library/library.json
index b9cc8311a04..dd622a721c6 100644
--- a/docs/src/library/library.json
+++ b/docs/src/library/library.json
@@ -1,4 +1,4 @@
{
"layout": "components.html",
- "permalink": "/component-library/{{ page.fileSlug }}/index.html"
+ "permalink": "/component-library/{{ page.fileSlug }}.html"
}
diff --git a/docs/src/library/link-card.md b/docs/src/library/link-card.md
index 858664c95b1..db400f31d68 100644
--- a/docs/src/library/link-card.md
+++ b/docs/src/library/link-card.md
@@ -10,10 +10,6 @@ Links can be rendered as cards by using the `link` shortcode. The only required
## Examples
-{% link "https://developer.mozilla.org/en-US/docs/Web/JavaScript" %}
-
-{% link "https://github.com/microlinkhq/metascraper" %}
-
{% link "https://blog.izs.me/2010/12/an-open-letter-to-javascript-leaders-regarding/" %}
-{% link "https://humanwhocodes.com/blog/2021/12/making-open-source-project-sponsor-ready-accepting-sponsorships/" %}
+{% link "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get" %}
diff --git a/docs/src/library/rule-list.md b/docs/src/library/rule-list.md
new file mode 100644
index 00000000000..635e6b40023
--- /dev/null
+++ b/docs/src/library/rule-list.md
@@ -0,0 +1,25 @@
+---
+title: Rule list
+---
+
+The rule list is a macro defined in `components/rule-list.macro.html`. The macro accepts a list of rule names and renders comma-separated links.
+
+## Usage
+
+{% raw %}
+
+```html
+
+{% from 'components/rule-list.macro.html' import ruleList %}
+
+
+{{ ruleList({ rules: ['accessor-pairs', 'no-undef'] }) }}
+```
+
+{% endraw %}
+
+## Examples
+
+{% from 'components/rule-list.macro.html' import ruleList %}
+
+{{ ruleList({ rules: ['accessor-pairs', 'no-undef'] }) }}
diff --git a/docs/src/maintainer-guide/governance.md b/docs/src/maintainer-guide/governance.md
index 57067963adf..da3548ba787 100644
--- a/docs/src/maintainer-guide/governance.md
+++ b/docs/src/maintainer-guide/governance.md
@@ -4,7 +4,7 @@ layout: doc
edit_link: https://github.com/eslint/eslint/edit/main/docs/src/maintainer-guide/governance.md
eleventyNavigation:
key: governance
- parent: maintainer guide
+ parent: maintainer guide
title: Governance
order: 4
@@ -26,11 +26,34 @@ Contributors are community members who contribute in concrete ways to the projec
Contributors have read-only access to source code and so submit changes via pull requests. Contributor pull requests have their contribution reviewed and merged by a TSC member. TSC members and Committers work with Contributors to review their code and prepare it for merging.
-As Contributors gain experience and familiarity with the project, their profile within, and commitment to, the community will increase. At some stage, they may find themselves being nominated for committership by an existing Committer.
+As Contributors gain experience and familiarity with the project, their profile within, and commitment to, the community will increase. At some stage, they may find themselves being nominated as either a Website Team Member or Committer by an existing Website Team Member or Committer.
+
+### Website Team Member
+
+Website Team Members are community members who have shown that they are committed to the continued maintenance of [eslint.org](https://eslint.org/) through ongoing engagement with the community. Website Team Members are given push access to the `eslint.org` GitHub repository and must abide by the project's [Contribution Guidelines](../developer-guide/contributing/).
+
+ Website Team Members:
+
+* Are expected to work on public branches of the source repository and submit pull requests from that branch to the master branch.
+* Are expected to delete their public branches when they are no longer necessary.
+* Must submit pull requests for all changes.
+* Have their work reviewed by Reviewers and TSC members before acceptance into the repository.
+* May label and close website-related issues (see [Managing Issues](issues.html))
+* May merge some pull requests (see [Managing Pull Requests](pullrequests.html))
+
+To become a Website Team Member:
+
+* One must have shown a willingness and ability to participate in the maintenance of [eslint.org](https://eslint.org/) as a team player. Typically, a potential Website Team Member will need to show that they have an understanding of the structure of the website and how it fits into the larger ESLint project's objectives and strategy.
+* Website Team Members are expected to be respectful of every community member and to work collaboratively in the spirit of inclusion.
+* Have submitted a minimum of 10 website-related pull requests. What's a website-related pull request? One that is made to the `eslint.org` repository or the `docs` directory in the `eslint` repository and requires little effort to accept because it's well documented and tested.
+
+New Website Team Members can be nominated by any existing Website Team Member or Committer. Once they have been nominated, there will be a vote by the TSC members.
+
+It is important to recognize that membership on the website team is a privilege, not a right. That privilege must be earned and once earned it can be removed by the TSC members by a standard TSC motion. However, under normal circumstances Website Team Members remain for as long as they wish to continue engaging with the project.
### Committers
-Committers are community members who have shown that they are committed to the continued development of the project through ongoing engagement with the community. Committers are given push access to the project's GitHub repos and must abide by the project's [Contribution Guidelines](../developer-guide/contributing).
+Committers are community members who have shown that they are committed to the continued development of the project through ongoing engagement with the community. Committers are given push access to the project's GitHub repos and must abide by the project's [Contribution Guidelines](../developer-guide/contributing/).
Committers:
diff --git a/docs/src/maintainer-guide/pullrequests.md b/docs/src/maintainer-guide/pullrequests.md
index 813a241c679..c9f7c4830fd 100644
--- a/docs/src/maintainer-guide/pullrequests.md
+++ b/docs/src/maintainer-guide/pullrequests.md
@@ -41,7 +41,13 @@ Once the bot checks have been satisfied, you check the following:
## Who Can Merge a Pull Request
-TSC members and committers may merge pull requests, depending on the contents of the pull request.
+TSC members, Reviewers, Committers, and Website Team Members may merge pull requests, depending on the contents of the pull request.
+
+Website Team Members may merge a pull request in the `eslint.org` repository if it is:
+
+1. A documentation change
+1. A dependency upgrade
+1. A chore
Committers may merge a pull request if it is a non-breaking change and is:
diff --git a/docs/src/pages/404.html b/docs/src/pages/404.html
index 7bb07cfbfe3..ee6413c1143 100644
--- a/docs/src/pages/404.html
+++ b/docs/src/pages/404.html
@@ -1,29 +1,29 @@
---
layout: main.html
-title: 404 error page not found — ESLint
permalink: /404.html
eleventyExcludeFromCollections: true
-hook: "404-page"
+hook: "404_page"
---
- 404 error
- Page not found
+ {{ site.404_page.title }}
+ {{ site.404_page.subtitle }}
- Sorry, the page you are looking for doesn't exist or has been moved.
+ {{ site.404_page.description }}
-
+
diff --git a/docs/src/pages/index.md b/docs/src/pages/index.md
index 8ca84e9db16..016d9d0f422 100644
--- a/docs/src/pages/index.md
+++ b/docs/src/pages/index.md
@@ -7,16 +7,16 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/pages/index.md
Welcome to our documentation pages! What would you like to view?
-## [User Guide](user-guide)
+## [User Guide](user-guide/)
Intended for end users of ESLint. Contains information about core rules, configuration, command line options, formatters, and integrations,
as well as guides for migrating from earlier versions of ESLint.
-## [Developer Guide](developer-guide)
+## [Developer Guide](developer-guide/)
Intended for contributors to ESLint and people who wish to extend ESLint. Contains information about contributing to ESLint; creating custom
rules, configurations, plugins, and formatters; and information about our architecture and Node.js API.
-## [Maintainer Guide](maintainer-guide)
+## [Maintainer Guide](maintainer-guide/)
Intended for maintainers of ESLint.
diff --git a/docs/src/pages/rules.md b/docs/src/pages/rules.md
index 22ce383f2eb..7ede8bf2277 100644
--- a/docs/src/pages/rules.md
+++ b/docs/src/pages/rules.md
@@ -15,6 +15,7 @@ eleventyNavigation:
Rules in ESLint are grouped by type to help you understand their purpose. Each rule has emojis denoting:
{{ ruleCategories({
+ index: true,
recommended: true,
fixable: true,
hasSuggestions: true
@@ -83,3 +84,5 @@ Rules in ESLint are grouped by type to help you understand their purpose. Each r
}) }}
{%- endfor -%}
{%- endif -%}
+
+{# #}
diff --git a/docs/src/rules/accessor-pairs.md b/docs/src/rules/accessor-pairs.md
index 06bc33fe649..0ce706a7708 100644
--- a/docs/src/rules/accessor-pairs.md
+++ b/docs/src/rules/accessor-pairs.md
@@ -12,7 +12,6 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
---
-Enforces getter/setter pairs in objects and classes.
It's a common mistake in JavaScript to create an object with just a setter for a property but never have a corresponding getter defined for it. Without a getter, you cannot read the property, so it ends up not being used.
@@ -26,6 +25,7 @@ var o = {
}
};
+
// Good
var o = {
set a(value) {
@@ -58,6 +58,8 @@ This rule always checks object literals and property descriptors. By default, it
Examples of **incorrect** code for the default `{ "setWithoutGet": true }` option:
+:::incorrect
+
```js
/*eslint accessor-pairs: "error"*/
@@ -67,6 +69,7 @@ var o = {
}
};
+
var o = {d: 1};
Object.defineProperty(o, 'c', {
set: function(value) {
@@ -75,8 +78,12 @@ Object.defineProperty(o, 'c', {
});
```
+:::
+
Examples of **correct** code for the default `{ "setWithoutGet": true }` option:
+:::correct
+
```js
/*eslint accessor-pairs: "error"*/
@@ -101,10 +108,14 @@ Object.defineProperty(o, 'c', {
```
+:::
+
### getWithoutSet
Examples of **incorrect** code for the `{ "getWithoutSet": true }` option:
+:::incorrect
+
```js
/*eslint accessor-pairs: ["error", { "getWithoutSet": true }]*/
@@ -135,8 +146,12 @@ Object.defineProperty(o, 'c', {
});
```
+:::
+
Examples of **correct** code for the `{ "getWithoutSet": true }` option:
+:::correct
+
```js
/*eslint accessor-pairs: ["error", { "getWithoutSet": true }]*/
var o = {
@@ -160,6 +175,8 @@ Object.defineProperty(o, 'c', {
```
+:::
+
### enforceForClassMembers
When `enforceForClassMembers` is set to `true` (default):
@@ -169,6 +186,8 @@ When `enforceForClassMembers` is set to `true` (default):
Examples of **incorrect** code for `{ "getWithoutSet": true, "enforceForClassMembers": true }`:
+:::incorrect
+
```js
/*eslint accessor-pairs: ["error", { "getWithoutSet": true, "enforceForClassMembers": true }]*/
@@ -194,8 +213,12 @@ const Baz = class {
}
```
+:::
+
Examples of **incorrect** code for `{ "setWithoutGet": true, "enforceForClassMembers": true }`:
+:::incorrect
+
```js
/*eslint accessor-pairs: ["error", { "setWithoutGet": true, "enforceForClassMembers": true }]*/
@@ -212,10 +235,14 @@ const Bar = class {
}
```
+:::
+
When `enforceForClassMembers` is set to `false`, this rule ignores classes.
Examples of **correct** code for `{ "getWithoutSet": true, "setWithoutGet": true, "enforceForClassMembers": false }`:
+:::correct
+
```js
/*eslint accessor-pairs: ["error", {
"getWithoutSet": true, "setWithoutGet": true, "enforceForClassMembers": false
@@ -246,6 +273,8 @@ const Quux = class {
}
```
+:::
+
## Known Limitations
Due to the limits of static analysis, this rule does not account for possible side effects and in certain cases
diff --git a/docs/src/rules/array-bracket-newline.md b/docs/src/rules/array-bracket-newline.md
index a363f02e425..04b527f8aff 100644
--- a/docs/src/rules/array-bracket-newline.md
+++ b/docs/src/rules/array-bracket-newline.md
@@ -7,9 +7,7 @@ related_rules:
- array-bracket-spacing
---
-
-Enforces line breaks after opening and before closing array brackets.
A number of style guides require or disallow line breaks inside of array brackets.
@@ -34,6 +32,8 @@ Or an object option (Requires line breaks if any of properties is satisfied. Oth
Examples of **incorrect** code for this rule with the `"always"` option:
+:::incorrect
+
```js
/*eslint array-bracket-newline: ["error", "always"]*/
@@ -47,8 +47,12 @@ var e = [function foo() {
}];
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+:::correct
+
```js
/*eslint array-bracket-newline: ["error", "always"]*/
@@ -71,10 +75,14 @@ var e = [
];
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+:::incorrect
+
```js
/*eslint array-bracket-newline: ["error", "never"]*/
@@ -97,8 +105,12 @@ var e = [
];
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+:::correct
+
```js
/*eslint array-bracket-newline: ["error", "never"]*/
@@ -112,10 +124,14 @@ var e = [function foo() {
}];
```
+:::
+
### consistent
Examples of **incorrect** code for this rule with the `"consistent"` option:
+:::incorrect
+
```js
/*eslint array-bracket-newline: ["error", "consistent"]*/
@@ -133,8 +149,12 @@ var d = [
}]
```
+:::
+
Examples of **correct** code for this rule with the `"consistent"` option:
+:::correct
+
```js
/*eslint array-bracket-newline: ["error", "consistent"]*/
@@ -155,10 +175,14 @@ var f = [
];
```
+:::
+
### multiline
Examples of **incorrect** code for this rule with the default `{ "multiline": true }` option:
+:::incorrect
+
```js
/*eslint array-bracket-newline: ["error", { "multiline": true }]*/
@@ -177,8 +201,12 @@ var e = [function foo() {
}];
```
+:::
+
Examples of **correct** code for this rule with the default `{ "multiline": true }` option:
+:::correct
+
```js
/*eslint array-bracket-newline: ["error", { "multiline": true }]*/
@@ -196,10 +224,14 @@ var e = [
];
```
+:::
+
### minItems
Examples of **incorrect** code for this rule with the `{ "minItems": 2 }` option:
+:::incorrect
+
```js
/*eslint array-bracket-newline: ["error", { "minItems": 2 }]*/
@@ -218,8 +250,12 @@ var e = [
];
```
+:::
+
Examples of **correct** code for this rule with the `{ "minItems": 2 }` option:
+:::correct
+
```js
/*eslint array-bracket-newline: ["error", { "minItems": 2 }]*/
@@ -237,10 +273,14 @@ var e = [function foo() {
}];
```
+:::
+
### multiline and minItems
Examples of **incorrect** code for this rule with the `{ "multiline": true, "minItems": 2 }` options:
+:::incorrect
+
```js
/*eslint array-bracket-newline: ["error", { "multiline": true, "minItems": 2 }]*/
@@ -257,8 +297,12 @@ var e = [function foo() {
}];
```
+:::
+
Examples of **correct** code for this rule with the `{ "multiline": true, "minItems": 2 }` options:
+:::correct
+
```js
/*eslint array-bracket-newline: ["error", { "multiline": true, "minItems": 2 }]*/
@@ -278,6 +322,8 @@ var e = [
];
```
+:::
+
## When Not To Use It
If you don't want to enforce line breaks after opening and before closing array brackets, don't enable this rule.
diff --git a/docs/src/rules/array-bracket-spacing.md b/docs/src/rules/array-bracket-spacing.md
index 1caa2a6c107..cc5589ef502 100644
--- a/docs/src/rules/array-bracket-spacing.md
+++ b/docs/src/rules/array-bracket-spacing.md
@@ -9,9 +9,7 @@ related_rules:
- computed-property-spacing
---
-
-Disallows or enforce spaces inside of brackets.
A number of style guides require or disallow spaces between array brackets and other tokens. This rule
applies to both array literals and destructuring assignments (ECMAScript 6).
@@ -58,6 +56,8 @@ This rule has built-in exceptions:
Examples of **incorrect** code for this rule with the default `"never"` option:
+:::incorrect
+
```js
/*eslint array-bracket-spacing: ["error", "never"]*/
/*eslint-env es6*/
@@ -75,8 +75,12 @@ var [ x, ...y ] = z;
var [ ,,x, ] = z;
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+:::correct
+
```js
/*eslint array-bracket-spacing: ["error", "never"]*/
/*eslint-env es6*/
@@ -102,10 +106,14 @@ var [x, ...y] = z;
var [,,x,] = z;
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+:::incorrect
+
```js
/*eslint array-bracket-spacing: ["error", "always"]*/
/*eslint-env es6*/
@@ -126,8 +134,12 @@ var [x, ...y] = z;
var [,,x,] = z;
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+:::correct
+
```js
/*eslint array-bracket-spacing: ["error", "always"]*/
/*eslint-env es6*/
@@ -153,10 +165,14 @@ var [ x, ...y ] = z;
var [ ,,x, ] = z;
```
+:::
+
### singleValue
Examples of **incorrect** code for this rule with the `"always", { "singleValue": false }` options:
+:::incorrect
+
```js
/*eslint array-bracket-spacing: ["error", "always", { "singleValue": false }]*/
@@ -170,8 +186,12 @@ var foo = [ [ 1, 2 ] ];
var foo = [ { 'foo': 'bar' } ];
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "singleValue": false }` options:
+:::correct
+
```js
/*eslint array-bracket-spacing: ["error", "always", { "singleValue": false }]*/
@@ -181,10 +201,14 @@ var foo = [[ 1, 1 ]];
var foo = [{ 'foo': 'bar' }];
```
+:::
+
### objectsInArrays
Examples of **incorrect** code for this rule with the `"always", { "objectsInArrays": false }` options:
+:::incorrect
+
```js
/*eslint array-bracket-spacing: ["error", "always", { "objectsInArrays": false }]*/
@@ -194,8 +218,12 @@ var arr = [ {
} ]
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "objectsInArrays": false }` options:
+:::correct
+
```js
/*eslint array-bracket-spacing: ["error", "always", { "objectsInArrays": false }]*/
@@ -205,10 +233,14 @@ var arr = [{
}];
```
+:::
+
### arraysInArrays
Examples of **incorrect** code for this rule with the `"always", { "arraysInArrays": false }` options:
+:::incorrect
+
```js
/*eslint array-bracket-spacing: ["error", "always", { "arraysInArrays": false }]*/
@@ -216,8 +248,12 @@ var arr = [ [ 1, 2 ], 2, 3, 4 ];
var arr = [ [ 1, 2 ], 2, [ 3, 4 ] ];
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "arraysInArrays": false }` options:
+:::correct
+
```js
/*eslint array-bracket-spacing: ["error", "always", { "arraysInArrays": false }]*/
@@ -225,6 +261,8 @@ var arr = [[ 1, 2 ], 2, 3, 4 ];
var arr = [[ 1, 2 ], 2, [ 3, 4 ]];
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between array brackets.
diff --git a/docs/src/rules/array-callback-return.md b/docs/src/rules/array-callback-return.md
index a269a53b5f3..ebd7e977010 100644
--- a/docs/src/rules/array-callback-return.md
+++ b/docs/src/rules/array-callback-return.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/array-callb
rule_type: problem
---
-Enforces return statements in callbacks of array's methods.
`Array` has several methods for filtering, mapping, and folding.
If we forget to write `return` statement in a callback of those, it's probably a mistake. If you don't want to use a return or don't need the returned results, consider using [.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) instead.
@@ -40,6 +39,8 @@ This rule finds callback functions of the following methods, then checks usage o
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint array-callback-return: "error"*/
@@ -62,8 +63,12 @@ var bar = foo.filter(function(x) {
});
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint array-callback-return: "error"*/
@@ -82,6 +87,8 @@ var foo = Array.from(nodes, function(node) {
var bar = foo.map(node => node.getAttribute("id"));
```
+:::
+
## Options
This rule accepts a configuration object with two options:
@@ -93,6 +100,8 @@ This rule accepts a configuration object with two options:
Examples of **correct** code for the `{ "allowImplicit": true }` option:
+:::correct
+
```js
/*eslint array-callback-return: ["error", { allowImplicit: true }]*/
var undefAllTheThings = myArray.map(function(item) {
@@ -100,10 +109,14 @@ var undefAllTheThings = myArray.map(function(item) {
});
```
+:::
+
### checkForEach
Examples of **incorrect** code for the `{ "checkForEach": true }` option:
+:::incorrect
+
```js
/*eslint array-callback-return: ["error", { checkForEach: true }]*/
@@ -125,8 +138,12 @@ myArray.forEach(item => {
});
```
+:::
+
Examples of **correct** code for the `{ "checkForEach": true }` option:
+:::correct
+
```js
/*eslint array-callback-return: ["error", { checkForEach: true }]*/
@@ -151,6 +168,8 @@ myArray.forEach(item => {
});
```
+:::
+
## Known Limitations
This rule checks callback functions of methods with the given names, *even if* the object which has the method is *not* an array.
diff --git a/docs/src/rules/array-element-newline.md b/docs/src/rules/array-element-newline.md
index 936f8fa9512..ec21c6fbaae 100644
--- a/docs/src/rules/array-element-newline.md
+++ b/docs/src/rules/array-element-newline.md
@@ -14,9 +14,7 @@ related_rules:
- brace-style
---
-
-Enforces line breaks between array elements.
A number of style guides require or disallow line breaks between array elements.
@@ -55,6 +53,8 @@ Alternatively, different configurations can be specified for array expressions a
Examples of **incorrect** code for this rule with the default `"always"` option:
+:::incorrect
+
```js
/*eslint array-element-newline: ["error", "always"]*/
@@ -74,8 +74,12 @@ var g = [
];
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+:::correct
+
```js
/*eslint array-element-newline: ["error", "always"]*/
@@ -101,10 +105,14 @@ var e = [
];
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+:::incorrect
+
```js
/*eslint array-element-newline: ["error", "never"]*/
@@ -127,8 +135,12 @@ var e = [
];
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+:::correct
+
```js
/*eslint array-element-newline: ["error", "never"]*/
@@ -150,10 +162,14 @@ var g = [
];
```
+:::
+
### consistent
Examples of **incorrect** code for this rule with the `"consistent"` option:
+:::incorrect
+
```js
/*eslint array-element-newline: ["error", "consistent"]*/
@@ -173,8 +189,12 @@ var b = [
];
```
+:::
+
Examples of **correct** code for this rule with the `"consistent"` option:
+:::correct
+
```js
/*eslint array-element-newline: ["error", "consistent"]*/
@@ -213,10 +233,14 @@ var h = [
];
```
+:::
+
### multiline
Examples of **incorrect** code for this rule with the `{ "multiline": true }` option:
+:::incorrect
+
```js
/*eslint array-element-newline: ["error", { "multiline": true }]*/
@@ -231,8 +255,12 @@ var e = [
];
```
+:::
+
Examples of **correct** code for this rule with the `{ "multiline": true }` option:
+:::correct
+
```js
/*eslint array-element-newline: ["error", { "multiline": true }]*/
@@ -250,10 +278,14 @@ var e = [
];
```
+:::
+
### minItems
Examples of **incorrect** code for this rule with the `{ "minItems": 3 }` option:
+:::incorrect
+
```js
/*eslint array-element-newline: ["error", { "minItems": 3 }]*/
@@ -270,8 +302,12 @@ var e = [
];
```
+:::
+
Examples of **correct** code for this rule with the `{ "minItems": 3 }` option:
+:::correct
+
```js
/*eslint array-element-newline: ["error", { "minItems": 3 }]*/
@@ -290,10 +326,14 @@ var e = [
];
```
+:::
+
### multiline and minItems
Examples of **incorrect** code for this rule with the `{ "multiline": true, "minItems": 3 }` options:
+:::incorrect
+
```js
/*eslint array-element-newline: ["error", { "multiline": true, "minItems": 3 }]*/
@@ -309,8 +349,12 @@ var e = [
];
```
+:::
+
Examples of **correct** code for this rule with the `{ "multiline": true, "minItems": 3 }` options:
+:::correct
+
```js
/*eslint array-element-newline: ["error", { "multiline": true, "minItems": 3 }]*/
@@ -330,10 +374,14 @@ var e = [
];
```
+:::
+
### ArrayExpression and ArrayPattern
Examples of **incorrect** code for this rule with the `{ "ArrayExpression": "always", "ArrayPattern": "never" }` options:
+:::incorrect
+
```js
/*eslint array-element-newline: ["error", { "ArrayExpression": "always", "ArrayPattern": "never" }]*/
@@ -360,8 +408,12 @@ j = function bar() {
}] = arr
```
+:::
+
Examples of **correct** code for this rule with the `{ "ArrayExpression": "always", "ArrayPattern": "never" }` options:
+:::correct
+
```js
/*eslint array-element-newline: ["error", { "ArrayExpression": "always", "ArrayPattern": "never" }]*/
@@ -388,6 +440,8 @@ var [i = function foo() {
}] = arr
```
+:::
+
## When Not To Use It
If you don't want to enforce linebreaks between array elements, don't enable this rule.
diff --git a/docs/src/rules/arrow-body-style.md b/docs/src/rules/arrow-body-style.md
index 68876696fce..050d4b11b76 100644
--- a/docs/src/rules/arrow-body-style.md
+++ b/docs/src/rules/arrow-body-style.md
@@ -5,10 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/arrow-body-
rule_type: suggestion
---
-
-
-Requires braces in arrow function bodies.
-
Arrow functions have two syntactic forms for their function bodies. They may be defined with a *block* body (denoted by curly braces) `() => { ... }` or with a single expression `() => ...`, whose value is implicitly returned.
## Rule Details
@@ -33,14 +29,20 @@ The second one is an object for more fine-grained configuration when the first o
Examples of **incorrect** code for this rule with the `"always"` option:
+:::incorrect
+
```js
/*eslint arrow-body-style: ["error", "always"]*/
/*eslint-env es6*/
let foo = () => 0;
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+:::correct
+
```js
let foo = () => {
return 0;
@@ -51,10 +53,14 @@ let foo = (retv, name) => {
};
```
+:::
+
### as-needed
Examples of **incorrect** code for this rule with the default `"as-needed"` option:
+:::incorrect
+
```js
/*eslint arrow-body-style: ["error", "as-needed"]*/
/*eslint-env es6*/
@@ -72,8 +78,12 @@ let foo = () => {
};
```
+:::
+
Examples of **correct** code for this rule with the default `"as-needed"` option:
+:::correct
+
```js
/*eslint arrow-body-style: ["error", "as-needed"]*/
/*eslint-env es6*/
@@ -98,12 +108,16 @@ let foo = () => {
let foo = () => ({ bar: 0 });
```
+:::
+
#### requireReturnForObjectLiteral
> This option is only applicable when used in conjunction with the `"as-needed"` option.
Examples of **incorrect** code for this rule with the `{ "requireReturnForObjectLiteral": true }` option:
+:::incorrect
+
```js
/*eslint arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }]*/
/*eslint-env es6*/
@@ -111,8 +125,12 @@ let foo = () => ({});
let foo = () => ({ bar: 0 });
```
+:::
+
Examples of **correct** code for this rule with the `{ "requireReturnForObjectLiteral": true }` option:
+:::correct
+
```js
/*eslint arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }]*/
/*eslint-env es6*/
@@ -121,10 +139,14 @@ let foo = () => {};
let foo = () => { return { bar: 0 }; };
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+:::incorrect
+
```js
/*eslint arrow-body-style: ["error", "never"]*/
/*eslint-env es6*/
@@ -138,8 +160,12 @@ let foo = (retv, name) => {
};
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+:::correct
+
```js
/*eslint arrow-body-style: ["error", "never"]*/
/*eslint-env es6*/
@@ -147,3 +173,5 @@ Examples of **correct** code for this rule with the `"never"` option:
let foo = () => 0;
let foo = () => ({ foo: 0 });
```
+
+:::
diff --git a/docs/src/rules/arrow-parens.md b/docs/src/rules/arrow-parens.md
index 522034aacee..66c7fa8bca8 100644
--- a/docs/src/rules/arrow-parens.md
+++ b/docs/src/rules/arrow-parens.md
@@ -7,9 +7,7 @@ further_reading:
- https://github.com/airbnb/javascript#arrows--one-arg-parens
---
-
-Requires parens in arrow function arguments.
Arrow functions can omit parentheses when they have exactly one parameter. In all other cases the parameter(s) must
be wrapped in parentheses. This rule enforces the consistent use of parentheses in arrow functions.
@@ -72,6 +70,8 @@ Object properties for variants of the `"as-needed"` option:
Examples of **incorrect** code for this rule with the default `"always"` option:
+:::incorrect
+
```js
/*eslint arrow-parens: ["error", "always"]*/
/*eslint-env es6*/
@@ -84,8 +84,12 @@ a.then(foo => a);
a(foo => { if (true) {} });
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+:::correct
+
```js
/*eslint arrow-parens: ["error", "always"]*/
/*eslint-env es6*/
@@ -98,6 +102,8 @@ a.then((foo) => {});
a.then((foo) => { if (true) {} });
```
+:::
+
#### If Statements
One of the benefits of this option is that it prevents the incorrect use of arrow functions in conditionals:
@@ -159,6 +165,8 @@ var f = (a) => b ? c: d;
Examples of **incorrect** code for this rule with the `"as-needed"` option:
+:::incorrect
+
```js
/*eslint arrow-parens: ["error", "as-needed"]*/
/*eslint-env es6*/
@@ -174,8 +182,12 @@ const g = /* comment */ (a) => a + a;
const h = (a) /* comment */ => a + a;
```
+:::
+
Examples of **correct** code for this rule with the `"as-needed"` option:
+:::correct
+
```js
/*eslint arrow-parens: ["error", "as-needed"]*/
/*eslint-env es6*/
@@ -195,10 +207,14 @@ const g = (/* comment */ a) => a + a;
const h = (a /* comment */) => a + a;
```
+:::
+
### requireForBlockBody
Examples of **incorrect** code for the `{ "requireForBlockBody": true }` option:
+:::incorrect
+
```js
/*eslint arrow-parens: [2, "as-needed", { "requireForBlockBody": true }]*/
/*eslint-env es6*/
@@ -213,8 +229,12 @@ a.map(x => {
a.then(foo => {});
```
+:::
+
Examples of **correct** code for the `{ "requireForBlockBody": true }` option:
+:::correct
+
```js
/*eslint arrow-parens: [2, "as-needed", { "requireForBlockBody": true }]*/
/*eslint-env es6*/
@@ -232,3 +252,5 @@ a((foo) => { if (true) {} });
([a, b]) => a;
({a, b}) => a;
```
+
+:::
diff --git a/docs/src/rules/arrow-spacing.md b/docs/src/rules/arrow-spacing.md
index c6453d11e6d..a8feec96499 100644
--- a/docs/src/rules/arrow-spacing.md
+++ b/docs/src/rules/arrow-spacing.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/arrow-spaci
rule_type: layout
---
-
-Requires space before/after arrow function's arrow.
This rule normalize style of spacing before/after an arrow function's arrow(`=>`).
@@ -31,6 +29,8 @@ The default configuration is `{ "before": true, "after": true }`.
Examples of **incorrect** code for this rule with the default `{ "before": true, "after": true }` option:
+:::incorrect
+
```js
/*eslint arrow-spacing: "error"*/
/*eslint-env es6*/
@@ -45,8 +45,12 @@ a=> a;
() =>{'\n'};
```
+:::
+
Examples of **correct** code for this rule with the default `{ "before": true, "after": true }` option:
+:::correct
+
```js
/*eslint arrow-spacing: "error"*/
/*eslint-env es6*/
@@ -57,8 +61,12 @@ a => a;
() => {'\n'};
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "before": false, "after": false }` option:
+:::incorrect
+
```js
/*eslint arrow-spacing: ["error", { "before": false, "after": false }]*/
/*eslint-env es6*/
@@ -68,8 +76,12 @@ Examples of **incorrect** code for this rule with the `{ "before": false, "after
()=> {'\n'};
```
+:::
+
Examples of **correct** code for this rule with the `{ "before": false, "after": false }` option:
+:::correct
+
```js
/*eslint arrow-spacing: ["error", { "before": false, "after": false }]*/
/*eslint-env es6*/
@@ -79,8 +91,12 @@ Examples of **correct** code for this rule with the `{ "before": false, "after":
()=>{'\n'};
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "before": false, "after": true }` option:
+:::incorrect
+
```js
/*eslint arrow-spacing: ["error", { "before": false, "after": true }]*/
/*eslint-env es6*/
@@ -90,8 +106,12 @@ Examples of **incorrect** code for this rule with the `{ "before": false, "after
()=>{'\n'};
```
+:::
+
Examples of **correct** code for this rule with the `{ "before": false, "after": true }` option:
+:::correct
+
```js
/*eslint arrow-spacing: ["error", { "before": false, "after": true }]*/
/*eslint-env es6*/
@@ -100,3 +120,5 @@ Examples of **correct** code for this rule with the `{ "before": false, "after":
(a)=> {};
()=> {'\n'};
```
+
+:::
diff --git a/docs/src/rules/block-scoped-var.md b/docs/src/rules/block-scoped-var.md
index a9131e6045e..4ef6548f6fc 100644
--- a/docs/src/rules/block-scoped-var.md
+++ b/docs/src/rules/block-scoped-var.md
@@ -8,7 +8,6 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting
---
-Enforces treating `var` as block scoped.
The `block-scoped-var` rule generates warnings when variables are used outside of the block in which they were defined. This emulates C-style block scope.
@@ -18,6 +17,8 @@ This rule aims to reduce the usage of variables outside of their binding context
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint block-scoped-var: "error"*/
@@ -62,8 +63,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint block-scoped-var: "error"*/
@@ -114,3 +119,5 @@ class C {
}
}
```
+
+:::
diff --git a/docs/src/rules/block-spacing.md b/docs/src/rules/block-spacing.md
index 76ca2e61273..ea3426a7854 100644
--- a/docs/src/rules/block-spacing.md
+++ b/docs/src/rules/block-spacing.md
@@ -8,9 +8,7 @@ related_rules:
- brace-style
---
-
-Disallows or enforces spaces inside of blocks after opening blocks and before closing blocks.
## Rule Details
@@ -27,6 +25,8 @@ This rule has a string option:
Examples of **incorrect** code for this rule with the default `"always"` option:
+:::incorrect
+
```js
/*eslint block-spacing: "error"*/
@@ -41,8 +41,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+:::correct
+
```js
/*eslint block-spacing: "error"*/
@@ -54,10 +58,14 @@ class C {
}
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+:::incorrect
+
```js
/*eslint block-spacing: ["error", "never"]*/
@@ -69,8 +77,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+:::correct
+
```js
/*eslint block-spacing: ["error", "never"]*/
@@ -82,6 +94,8 @@ class C {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about spacing style inside of blocks, you can safely disable this rule.
diff --git a/docs/src/rules/brace-style.md b/docs/src/rules/brace-style.md
index 477d866d93d..6320fec42d3 100644
--- a/docs/src/rules/brace-style.md
+++ b/docs/src/rules/brace-style.md
@@ -10,9 +10,7 @@ further_reading:
- https://en.wikipedia.org/wiki/Indent_style
---
-
-Enforces consistent brace style for blocks.
Brace style is closely related to [indent style](https://en.wikipedia.org/wiki/Indent_style) in programming and describes the placement of braces relative to their control statement and body. There are probably a dozen, if not more, brace styles in the world.
@@ -72,6 +70,8 @@ This rule has an object option for an exception:
Examples of **incorrect** code for this rule with the default `"1tbs"` option:
+:::incorrect
+
```js
/*eslint brace-style: "error"*/
@@ -109,8 +109,12 @@ class C
}
```
+:::
+
Examples of **correct** code for this rule with the default `"1tbs"` option:
+:::correct
+
```js
/*eslint brace-style: "error"*/
@@ -145,8 +149,12 @@ if (foo) bar();
else if (baz) boom();
```
+:::
+
Examples of **correct** code for this rule with the `"1tbs", { "allowSingleLine": true }` options:
+:::correct
+
```js
/*eslint brace-style: ["error", "1tbs", { "allowSingleLine": true }]*/
@@ -186,10 +194,14 @@ class C {
class D { static { foo(); } }
```
+:::
+
### stroustrup
Examples of **incorrect** code for this rule with the `"stroustrup"` option:
+:::incorrect
+
```js
/*eslint brace-style: ["error", "stroustrup"]*/
@@ -226,8 +238,12 @@ if (foo) {
}
```
+:::
+
Examples of **correct** code for this rule with the `"stroustrup"` option:
+:::correct
+
```js
/*eslint brace-style: ["error", "stroustrup"]*/
@@ -264,8 +280,12 @@ if (foo) bar();
else if (baz) boom();
```
+:::
+
Examples of **correct** code for this rule with the `"stroustrup", { "allowSingleLine": true }` options:
+:::correct
+
```js
/*eslint brace-style: ["error", "stroustrup", { "allowSingleLine": true }]*/
@@ -286,10 +306,14 @@ class C {
class D { static { foo(); } }
```
+:::
+
### allman
Examples of **incorrect** code for this rule with the `"allman"` option:
+:::incorrect
+
```js
/*eslint brace-style: ["error", "allman"]*/
@@ -322,8 +346,12 @@ if (foo) {
}
```
+:::
+
Examples of **correct** code for this rule with the `"allman"` option:
+:::correct
+
```js
/*eslint brace-style: ["error", "allman"]*/
@@ -368,8 +396,12 @@ if (foo) bar();
else if (baz) boom();
```
+:::
+
Examples of **correct** code for this rule with the `"allman", { "allowSingleLine": true }` options:
+:::correct
+
```js
/*eslint brace-style: ["error", "allman", { "allowSingleLine": true }]*/
@@ -394,6 +426,8 @@ class C
class D { static { foo(); } }
```
+:::
+
## When Not To Use It
If you don't want to enforce a particular brace style, don't enable this rule.
diff --git a/docs/src/rules/callback-return.md b/docs/src/rules/callback-return.md
index 87a927ec98b..b9db4659f82 100644
--- a/docs/src/rules/callback-return.md
+++ b/docs/src/rules/callback-return.md
@@ -10,7 +10,6 @@ further_reading:
- https://web.archive.org/web/20171224042620/https://docs.nodejitsu.com/articles/errors/what-are-the-error-conventions/
---
-Enforces return after callback.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -44,6 +43,8 @@ The rule takes a single option - an array of possible callback names - which may
Examples of **incorrect** code for this rule with the default `["callback", "cb", "next"]` option:
+:::incorrect
+
```js
/*eslint callback-return: "error"*/
@@ -55,8 +56,12 @@ function foo(err, callback) {
}
```
+:::
+
Examples of **correct** code for this rule with the default `["callback", "cb", "next"]` option:
+:::correct
+
```js
/*eslint callback-return: "error"*/
@@ -68,10 +73,14 @@ function foo(err, callback) {
}
```
+:::
+
### Supplied callback names
Examples of **incorrect** code for this rule with the option `["done", "send.error", "send.success"]`:
+:::incorrect
+
```js
/*eslint callback-return: ["error", ["done", "send.error", "send.success"]]*/
@@ -90,8 +99,12 @@ function bar(err, send) {
}
```
+:::
+
Examples of **correct** code for this rule with the option `["done", "send.error", "send.success"]`:
+:::correct
+
```js
/*eslint callback-return: ["error", ["done", "send.error", "send.success"]]*/
@@ -110,6 +123,8 @@ function bar(err, send) {
}
```
+:::
+
## Known Limitations
Because it is difficult to understand the meaning of a program through static analysis, this rule has limitations:
diff --git a/docs/src/rules/camelcase.md b/docs/src/rules/camelcase.md
index 83843c34bd2..294f597e338 100644
--- a/docs/src/rules/camelcase.md
+++ b/docs/src/rules/camelcase.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/camelcase.m
rule_type: suggestion
---
-Enforces camelcase naming convention.
When it comes to naming variables, style guides generally fall into one of two camps: camelcase (`variableName`) and underscores (`variable_name`). This rule focuses on using the camelcase approach. If your style guide calls for camelCasing your variable names, then this rule is for you!
@@ -31,6 +30,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "properties": "always" }` option:
+:::incorrect
+
```js
/*eslint camelcase: "error"*/
@@ -69,8 +70,12 @@ var { foo: no_camelcased } = bar;
var { foo: bar_baz = 1 } = quz;
```
+:::
+
Examples of **correct** code for this rule with the default `{ "properties": "always" }` option:
+:::correct
+
```js
/*eslint camelcase: "error"*/
@@ -109,10 +114,14 @@ var { foo: isCamelCased = 1 } = quz;
```
+:::
+
### properties: "never"
Examples of **correct** code for this rule with the `{ "properties": "never" }` option:
+:::correct
+
```js
/*eslint camelcase: ["error", {properties: "never"}]*/
@@ -121,10 +130,14 @@ var obj = {
};
```
+:::
+
### ignoreDestructuring: false
Examples of **incorrect** code for this rule with the default `{ "ignoreDestructuring": false }` option:
+:::incorrect
+
```js
/*eslint camelcase: "error"*/
@@ -139,10 +152,14 @@ var { category_id: category_alias } = query;
var { category_id: categoryId, ...other_props } = query;
```
+:::
+
### ignoreDestructuring: true
Examples of **incorrect** code for this rule with the `{ "ignoreDestructuring": true }` option:
+:::incorrect
+
```js
/*eslint camelcase: ["error", {ignoreDestructuring: true}]*/
@@ -151,8 +168,12 @@ var { category_id: category_alias } = query;
var { category_id, ...other_props } = query;
```
+:::
+
Examples of **correct** code for this rule with the `{ "ignoreDestructuring": true }` option:
+:::correct
+
```js
/*eslint camelcase: ["error", {ignoreDestructuring: true}]*/
@@ -163,10 +184,14 @@ var { category_id = 1 } = query;
var { category_id: category_id } = query;
```
+:::
+
Please note that this option applies only to identifiers inside destructuring patterns. It doesn't additionally allow any particular use of the created variables later in the code apart from the use that is already allowed by default or by other options.
Examples of additional **incorrect** code for this rule with the `{ "ignoreDestructuring": true }` option:
+:::incorrect
+
```js
/*eslint camelcase: ["error", {ignoreDestructuring: true}]*/
@@ -174,10 +199,14 @@ var { some_property } = obj; // allowed by {ignoreDestructuring: true}
var foo = some_property + 1; // error, ignoreDestructuring does not apply to this statement
```
+:::
+
A common use case for this option is to avoid useless renaming when the identifier is not intended to be used later in the code.
Examples of additional **correct** code for this rule with the `{ "ignoreDestructuring": true }` option:
+:::correct
+
```js
/*eslint camelcase: ["error", {ignoreDestructuring: true}]*/
@@ -185,10 +214,14 @@ var { some_property, ...rest } = obj;
// do something with 'rest', nothing with 'some_property'
```
+:::
+
Another common use case for this option is in combination with `{ "properties": "never" }`, when the identifier is intended to be used only as a property shorthand.
Examples of additional **correct** code for this rule with the `{ "properties": "never", "ignoreDestructuring": true }` options:
+:::correct
+
```js
/*eslint camelcase: ["error", {"properties": "never", ignoreDestructuring: true}]*/
@@ -196,20 +229,28 @@ var { some_property } = obj;
doSomething({ some_property });
```
+:::
+
### ignoreImports: false
Examples of **incorrect** code for this rule with the default `{ "ignoreImports": false }` option:
+:::incorrect
+
```js
/*eslint camelcase: "error"*/
import { snake_cased } from 'mod';
```
+:::
+
### ignoreImports: true
Examples of **incorrect** code for this rule with the `{ "ignoreImports": true }` option:
+:::incorrect
+
```js
/*eslint camelcase: ["error", {ignoreImports: true}]*/
@@ -218,18 +259,26 @@ import default_import from 'mod';
import * as namespaced_import from 'mod';
```
+:::
+
Examples of **correct** code for this rule with the `{ "ignoreImports": true }` option:
+:::correct
+
```js
/*eslint camelcase: ["error", {ignoreImports: true}]*/
import { snake_cased } from 'mod';
```
+:::
+
### ignoreGlobals: false
Examples of **incorrect** code for this rule with the default `{ "ignoreGlobals": false }` option:
+:::incorrect
+
```js
/*eslint camelcase: ["error", {ignoreGlobals: false}]*/
/* global no_camelcased */
@@ -237,10 +286,14 @@ Examples of **incorrect** code for this rule with the default `{ "ignoreGlobals"
const foo = no_camelcased;
```
+:::
+
### ignoreGlobals: true
Examples of **correct** code for this rule with the `{ "ignoreGlobals": true }` option:
+:::correct
+
```js
/*eslint camelcase: ["error", {ignoreGlobals: true}]*/
/* global no_camelcased */
@@ -248,10 +301,14 @@ Examples of **correct** code for this rule with the `{ "ignoreGlobals": true }`
const foo = no_camelcased;
```
+:::
+
### allow
Examples of **correct** code for this rule with the `allow` option:
+:::correct
+
```js
/*eslint camelcase: ["error", {allow: ["UNSAFE_componentWillMount"]}]*/
@@ -260,6 +317,10 @@ function UNSAFE_componentWillMount() {
}
```
+:::
+
+::: correct
+
```js
/*eslint camelcase: ["error", {allow: ["^UNSAFE_"]}]*/
@@ -272,6 +333,8 @@ function UNSAFE_componentWillMount() {
}
```
+:::
+
## When Not To Use It
If you have established coding standards using a different naming convention (separating words with underscores), turn this rule off.
diff --git a/docs/src/rules/capitalized-comments.md b/docs/src/rules/capitalized-comments.md
index 601de8864e2..1334aaaa173 100644
--- a/docs/src/rules/capitalized-comments.md
+++ b/docs/src/rules/capitalized-comments.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/capitalized
rule_type: suggestion
---
-
-Enforces or disallows capitalization of the first letter of a comment.
Comments are useful for leaving information for future developers. In order for that information to be useful and not distracting, it is sometimes desirable for comments to follow a particular style. One element of comment formatting styles is whether the first word of a comment should be capitalized or lowercase.
@@ -21,6 +19,8 @@ By default, this rule will require a non-lowercase letter at the beginning of co
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/* eslint capitalized-comments: ["error"] */
@@ -28,8 +28,12 @@ Examples of **incorrect** code for this rule:
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
// Capitalized comment
@@ -54,6 +58,8 @@ Examples of **correct** code for this rule:
```
+:::
+
### Options
This rule has two options: a string value `"always"` or `"never"` which determines whether capitalization of the first word of a comment should be required or forbidden, and optionally an object containing more configuration parameters for the rule.
@@ -88,6 +94,8 @@ Note that configuration comments and comments which start with URLs are never re
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/* eslint capitalized-comments: ["error", "always"] */
@@ -95,8 +103,12 @@ Examples of **incorrect** code for this rule:
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/* eslint capitalized-comments: ["error", "always"] */
@@ -122,12 +134,16 @@ Examples of **correct** code for this rule:
```
+:::
+
#### `"never"`
Using the `"never"` option means that this rule will report any comments which start with an uppercase letter.
Examples of **incorrect** code with the `"never"` option:
+:::incorrect
+
```js
/* eslint capitalized-comments: ["error", "never"] */
@@ -135,8 +151,12 @@ Examples of **incorrect** code with the `"never"` option:
```
+:::
+
Examples of **correct** code with the `"never"` option:
+:::correct
+
```js
/* eslint capitalized-comments: ["error", "never"] */
@@ -148,12 +168,16 @@ Examples of **correct** code with the `"never"` option:
```
+:::
+
#### `ignorePattern`
The `ignorePattern` object takes a string value, which is used as a regular expression applied to the first word of a comment.
Examples of **correct** code with the `"ignorePattern"` option set to `"pragma"`:
+:::correct
+
```js
/* eslint capitalized-comments: ["error", "always", { "ignorePattern": "pragma" }] */
@@ -163,12 +187,16 @@ function foo() {
```
+:::
+
#### `ignoreInlineComments`
Setting the `ignoreInlineComments` option to `true` means that comments in the middle of code (with a token on the same line as the beginning of the comment, and another token on the same line as the end of the comment) will not be reported by this rule.
Examples of **correct** code with the `"ignoreInlineComments"` option set to `true`:
+:::correct
+
```js
/* eslint capitalized-comments: ["error", "always", { "ignoreInlineComments": true }] */
@@ -177,12 +205,16 @@ function foo(/* ignored */ a) {
```
+:::
+
#### `ignoreConsecutiveComments`
If the `ignoreConsecutiveComments` option is set to `true`, then comments which otherwise violate the rule will not be reported as long as they immediately follow another comment. This can be applied more than once.
Examples of **correct** code with `ignoreConsecutiveComments` set to `true`:
+:::correct
+
```js
/* eslint capitalized-comments: ["error", "always", { "ignoreConsecutiveComments": true }] */
@@ -197,8 +229,12 @@ Examples of **correct** code with `ignoreConsecutiveComments` set to `true`:
*/
```
+:::
+
Examples of **incorrect** code with `ignoreConsecutiveComments` set to `true`:
+:::incorrect
+
```js
/* eslint capitalized-comments: ["error", "always", { "ignoreConsecutiveComments": true }] */
@@ -206,6 +242,8 @@ Examples of **incorrect** code with `ignoreConsecutiveComments` set to `true`:
// this comment does NOT get reported, since it is a consecutive comment.
```
+:::
+
### Using Different Options for Line and Block Comments
If you wish to have a different configuration for line comments and block comments, you can do so by using two different object configurations (note that the capitalization option will be enforced consistently for line and block comments):
@@ -230,6 +268,8 @@ If you wish to have a different configuration for line comments and block commen
Examples of **incorrect** code with different line and block comment configuration:
+:::incorrect
+
```js
/* eslint capitalized-comments: ["error", "always", { "block": { "ignorePattern": "blockignore" } }] */
@@ -238,8 +278,12 @@ Examples of **incorrect** code with different line and block comment configurati
```
+:::
+
Examples of **correct** code with different line and block comment configuration:
+:::correct
+
```js
/* eslint capitalized-comments: ["error", "always", { "block": { "ignorePattern": "blockignore" } }] */
@@ -248,6 +292,8 @@ Examples of **correct** code with different line and block comment configuration
```
+:::
+
## When Not To Use It
This rule can be disabled if you do not care about the grammatical style of comments in your codebase.
diff --git a/docs/src/rules/class-methods-use-this.md b/docs/src/rules/class-methods-use-this.md
index b02cf487ed2..8b3df9643a4 100644
--- a/docs/src/rules/class-methods-use-this.md
+++ b/docs/src/rules/class-methods-use-this.md
@@ -8,7 +8,6 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
---
-Enforces that class methods utilize `this`.
If a class method does not use `this`, it can *sometimes* be made into a static function. If you do convert the method into a static function, instances of the class that call that particular method have to be converted to a static call as well (`MyClass.callStaticMethod()`)
@@ -61,6 +60,8 @@ This rule is aimed to flag class methods that do not use `this`.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint class-methods-use-this: "error"*/
/*eslint-env es6*/
@@ -72,8 +73,12 @@ class A {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint class-methods-use-this: "error"*/
/*eslint-env es6*/
@@ -100,6 +105,8 @@ class A {
}
```
+:::
+
## Options
This rule has two options:
@@ -117,6 +124,8 @@ The `exceptMethods` option allows you to pass an array of method names for which
Examples of **incorrect** code for this rule when used without exceptMethods:
+::: incorrect
+
```js
/*eslint class-methods-use-this: "error"*/
@@ -126,8 +135,12 @@ class A {
}
```
+:::
+
Examples of **correct** code for this rule when used with exceptMethods:
+::: correct
+
```js
/*eslint class-methods-use-this: ["error", { "exceptMethods": ["foo", "#bar"] }] */
@@ -139,6 +152,8 @@ class A {
}
```
+:::
+
### enforceForClassFields
```js
@@ -149,6 +164,8 @@ The `enforceForClassFields` option enforces that arrow functions and function ex
Examples of **incorrect** code for this rule with the `{ "enforceForClassFields": true }` option (default):
+::: incorrect
+
```js
/*eslint class-methods-use-this: ["error", { "enforceForClassFields": true }] */
@@ -157,8 +174,12 @@ class A {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "enforceForClassFields": true }` option (default):
+::: correct
+
```js
/*eslint class-methods-use-this: ["error", { "enforceForClassFields": true }] */
@@ -167,8 +188,12 @@ class A {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "enforceForClassFields": false }` option:
+::: correct
+
```js
/*eslint class-methods-use-this: ["error", { "enforceForClassFields": false }] */
@@ -176,3 +201,5 @@ class A {
foo = () => {}
}
```
+
+:::
diff --git a/docs/src/rules/comma-dangle.md b/docs/src/rules/comma-dangle.md
index a40f1cb76ca..26d650210c2 100644
--- a/docs/src/rules/comma-dangle.md
+++ b/docs/src/rules/comma-dangle.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/comma-dangl
rule_type: layout
---
-
-Requires or disallows trailing commas.
Trailing commas in object literals are valid according to the ECMAScript 5 (and ECMAScript 3!) spec. However, IE8 (when not in IE8 document mode) and below will throw an error when it encounters trailing commas in JavaScript.
@@ -82,6 +80,8 @@ The default for each option is `"never"` unless otherwise specified.
Examples of **incorrect** code for this rule with the default `"never"` option:
+:::incorrect
+
```js
/*eslint comma-dangle: ["error", "never"]*/
@@ -98,8 +98,12 @@ foo({
});
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+:::correct
+
```js
/*eslint comma-dangle: ["error", "never"]*/
@@ -116,10 +120,14 @@ foo({
});
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+:::incorrect
+
```js
/*eslint comma-dangle: ["error", "always"]*/
@@ -136,8 +144,12 @@ foo({
});
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+:::correct
+
```js
/*eslint comma-dangle: ["error", "always"]*/
@@ -154,10 +166,14 @@ foo({
});
```
+:::
+
### always-multiline
Examples of **incorrect** code for this rule with the `"always-multiline"` option:
+:::incorrect
+
```js
/*eslint comma-dangle: ["error", "always-multiline"]*/
@@ -184,8 +200,12 @@ foo({
});
```
+:::
+
Examples of **correct** code for this rule with the `"always-multiline"` option:
+:::correct
+
```js
/*eslint comma-dangle: ["error", "always-multiline"]*/
@@ -211,10 +231,14 @@ foo({
});
```
+:::
+
### only-multiline
Examples of **incorrect** code for this rule with the `"only-multiline"` option:
+:::incorrect
+
```js
/*eslint comma-dangle: ["error", "only-multiline"]*/
@@ -227,8 +251,12 @@ var arr = [1,
```
+:::
+
Examples of **correct** code for this rule with the `"only-multiline"` option:
+:::correct
+
```js
/*eslint comma-dangle: ["error", "only-multiline"]*/
@@ -269,10 +297,14 @@ foo({
});
```
+:::
+
### functions
Examples of **incorrect** code for this rule with the `{"functions": "never"}` option:
+:::incorrect
+
```js
/*eslint comma-dangle: ["error", {"functions": "never"}]*/
@@ -283,8 +315,12 @@ foo(a, b,);
new foo(a, b,);
```
+:::
+
Examples of **correct** code for this rule with the `{"functions": "never"}` option:
+:::correct
+
```js
/*eslint comma-dangle: ["error", {"functions": "never"}]*/
@@ -295,8 +331,12 @@ foo(a, b);
new foo(a, b);
```
+:::
+
Examples of **incorrect** code for this rule with the `{"functions": "always"}` option:
+:::incorrect
+
```js
/*eslint comma-dangle: ["error", {"functions": "always"}]*/
@@ -307,8 +347,12 @@ foo(a, b);
new foo(a, b);
```
+:::
+
Examples of **correct** code for this rule with the `{"functions": "always"}` option:
+:::correct
+
```js
/*eslint comma-dangle: ["error", {"functions": "always"}]*/
@@ -319,6 +363,8 @@ foo(a, b,);
new foo(a, b,);
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with dangling commas.
diff --git a/docs/src/rules/comma-spacing.md b/docs/src/rules/comma-spacing.md
index 55eb9ccdcde..ca10ca0a6a7 100644
--- a/docs/src/rules/comma-spacing.md
+++ b/docs/src/rules/comma-spacing.md
@@ -6,6 +6,7 @@ rule_type: layout
related_rules:
- array-bracket-spacing
- comma-style
+- object-curly-spacing
- space-in-brackets
- space-in-parens
- space-infix-ops
@@ -17,9 +18,7 @@ further_reading:
- https://dojotoolkit.org/reference-guide/1.9/developer/styleguide.html
---
-
-Enforces spacing around commas.
Spacing around commas improves readability of a list of items. Although most of the style guidelines for languages prescribe adding a space after a comma and not before it, it is subjective to the preferences of a project.
@@ -32,10 +31,13 @@ var foo = 1 ,bar = 2;
This rule enforces consistent spacing before and after commas in variable declarations, array literals, object literals, function parameters, and sequences.
-This rule does not apply in an `ArrayExpression` or `ArrayPattern` in either of the following cases:
+This rule does not apply in either of the following cases:
-* adjacent null elements
-* an initial null element, to avoid conflicts with the [`array-bracket-spacing`](array-bracket-spacing) rule
+* between two commas
+* between opening bracket `[` and comma, to avoid conflicts with the [`array-bracket-spacing`](array-bracket-spacing) rule
+* between comma and closing bracket `]`, to avoid conflicts with the [`array-bracket-spacing`](array-bracket-spacing) rule
+* between comma and closing brace `}`, to avoid conflicts with the [`object-curly-spacing`](object-curly-spacing) rule
+* between comma and closing parentheses `)`, to avoid conflicts with the [`space-in-parens`](space-in-parens) rule
## Options
@@ -50,6 +52,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "before": false, "after": true }` options:
+:::incorrect
+
```js
/*eslint comma-spacing: ["error", { "before": false, "after": true }]*/
@@ -62,8 +66,12 @@ function foo(a ,b){}
a ,b
```
+:::
+
Examples of **correct** code for this rule with the default `{ "before": false, "after": true }` options:
+:::correct
+
```js
/*eslint comma-spacing: ["error", { "before": false, "after": true }]*/
@@ -78,19 +86,46 @@ function foo(a, b){}
a, b
```
-Example of **correct** code for this rule with initial null element for the default `{ "before": false, "after": true }` options:
+:::
+
+Additional examples of **correct** code for this rule with the default `{ "before": false, "after": true }` options:
+
+:::correct
```js
/*eslint comma-spacing: ["error", { "before": false, "after": true }]*/
-/*eslint array-bracket-spacing: ["error", "always"]*/
-var arr = [ , 2, 3 ]
+// this rule does not enforce spacing between two commas
+var arr = [
+ ,,
+ , ,
+];
+
+// this rule does not enforce spacing after `[` and before `]`
+var arr = [,];
+var arr = [ , ];
+var arr = [a, b,];
+[,] = arr;
+[ , ] = arr;
+[a, b,] = arr;
+
+// this rule does not enforce spacing before `}`
+var obj = {x, y,};
+var {z, q,} = obj;
+import {foo, bar,} from "mod";
+
+// this rule does not enforce spacing before `)`
+foo(a, b,)
```
+:::
+
### before
Examples of **incorrect** code for this rule with the `{ "before": true, "after": false }` options:
+:::incorrect
+
```js
/*eslint comma-spacing: ["error", { "before": true, "after": false }]*/
@@ -102,8 +137,12 @@ function foo(a,b){}
a, b
```
+:::
+
Examples of **correct** code for this rule with the `{ "before": true, "after": false }` options:
+:::correct
+
```js
/*eslint comma-spacing: ["error", { "before": true, "after": false }]*/
@@ -118,14 +157,7 @@ function foo(a ,b){}
a ,b
```
-Examples of **correct** code for this rule with initial null element for the `{ "before": true, "after": false }` options:
-
-```js
-/*eslint comma-spacing: ["error", { "before": true, "after": false }]*/
-/*eslint array-bracket-spacing: ["error", "never"]*/
-
-var arr = [,2 ,3]
-```
+:::
## When Not To Use It
diff --git a/docs/src/rules/comma-style.md b/docs/src/rules/comma-style.md
index e72c59b79f5..1535ef667fa 100644
--- a/docs/src/rules/comma-style.md
+++ b/docs/src/rules/comma-style.md
@@ -9,9 +9,7 @@ further_reading:
- https://gist.github.com/isaacs/357981
---
-
-Enforces consistent comma styles.
The Comma Style rule enforces styles for comma-separated lists. There are two comma styles primarily used in JavaScript:
@@ -58,6 +56,8 @@ A way to determine the node types as defined by [ESTree](https://github.com/estr
Examples of **incorrect** code for this rule with the default `"last"` option:
+:::incorrect
+
```js
/*eslint comma-style: ["error", "last"]*/
@@ -79,8 +79,12 @@ function bar() {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"last"` option:
+:::correct
+
```js
/*eslint comma-style: ["error", "last"]*/
@@ -100,10 +104,14 @@ function bar() {
}
```
+:::
+
### first
Examples of **incorrect** code for this rule with the `"first"` option:
+:::incorrect
+
```js
/*eslint comma-style: ["error", "first"]*/
@@ -121,8 +129,12 @@ function bar() {
}
```
+:::
+
Examples of **correct** code for this rule with the `"first"` option:
+:::correct
+
```js
/*eslint comma-style: ["error", "first"]*/
@@ -142,12 +154,16 @@ function bar() {
}
```
+:::
+
### exceptions
An example use case is to enforce comma style *only* in var statements.
Examples of **incorrect** code for this rule with sample `"first", { "exceptions": { … } }` options:
+:::incorrect
+
```js
/*eslint comma-style: ["error", "first", { "exceptions": { "ArrayExpression": true, "ObjectExpression": true } }]*/
@@ -155,8 +171,12 @@ var o = {},
a = [];
```
+:::
+
Examples of **correct** code for this rule with sample `"first", { "exceptions": { … } }` options:
+:::correct
+
```js
/*eslint comma-style: ["error", "first", { "exceptions": { "ArrayExpression": true, "ObjectExpression": true } }]*/
@@ -166,6 +186,8 @@ var o = {fst:1,
, a = [];
```
+:::
+
## When Not To Use It
This rule can safely be turned off if your project does not care about enforcing a consistent comma style.
diff --git a/docs/src/rules/complexity.md b/docs/src/rules/complexity.md
index e58e75415e7..cb4bbdb5d2d 100644
--- a/docs/src/rules/complexity.md
+++ b/docs/src/rules/complexity.md
@@ -19,7 +19,6 @@ further_reading:
- https://github.com/eslint/eslint/issues/4808#issuecomment-167795140
---
-Enforces a maximum cyclomatic complexity.
Cyclomatic complexity measures the number of linearly independent paths through a program's source code. This rule allows setting a cyclomatic complexity threshold.
@@ -41,6 +40,8 @@ This rule is aimed at reducing code complexity by capping the amount of cyclomat
Examples of **incorrect** code for a maximum of 2:
+::: incorrect
+
```js
/*eslint complexity: ["error", 2]*/
@@ -60,8 +61,12 @@ function b() {
}
```
+:::
+
Examples of **correct** code for a maximum of 2:
+::: correct
+
```js
/*eslint complexity: ["error", 2]*/
@@ -78,10 +83,14 @@ function b() {
}
```
+:::
+
Class field initializers and class static blocks are implicit functions. Therefore, their complexity is calculated separately for each initializer and each static block, and it doesn't contribute to the complexity of the enclosing code.
Examples of additional **incorrect** code for a maximum of 2:
+::: incorrect
+
```js
/*eslint complexity: ["error", 2]*/
@@ -98,8 +107,12 @@ class D { // this static block has complexity = 3
}
```
+:::
+
Examples of additional **correct** code for a maximum of 2:
+::: correct
+
```js
/*eslint complexity: ["error", 2]*/
@@ -125,6 +138,8 @@ function foo() { // this function has complexity = 1
}
```
+:::
+
## Options
Optionally, you may specify a `max` object property:
diff --git a/docs/src/rules/computed-property-spacing.md b/docs/src/rules/computed-property-spacing.md
index e0546c6dbce..96fb8b06132 100644
--- a/docs/src/rules/computed-property-spacing.md
+++ b/docs/src/rules/computed-property-spacing.md
@@ -9,9 +9,7 @@ related_rules:
- space-in-parens
---
-
-Disallows or enforces spaces inside of computed properties.
While formatting preferences are very personal, a number of style guides require
or disallow spaces between computed properties in the following situations:
@@ -57,6 +55,8 @@ Object option:
Examples of **incorrect** code for this rule with the default `"never"` option:
+::: incorrect
+
```js
/*eslint computed-property-spacing: ["error", "never"]*/
/*eslint-env es6*/
@@ -70,8 +70,12 @@ const { [ a ]: someProp } = obj;
({ [ b ]: anotherProp } = anotherObj);
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+::: correct
+
```js
/*eslint computed-property-spacing: ["error", "never"]*/
/*eslint-env es6*/
@@ -85,10 +89,14 @@ const { [a]: someProp } = obj;
({ [b]: anotherProp } = anotherObj);
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint computed-property-spacing: ["error", "always"]*/
/*eslint-env es6*/
@@ -103,8 +111,12 @@ const { [a]: someProp } = obj;
({ [b ]: anotherProp } = anotherObj);
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint computed-property-spacing: ["error", "always"]*/
/*eslint-env es6*/
@@ -117,12 +129,16 @@ const { [ a ]: someProp } = obj;
({ [ b ]: anotherProp } = anotherObj);
```
+:::
+
#### enforceForClassMembers
With `enforceForClassMembers` set to `true` (default), the rule also disallows/enforces spaces inside of computed keys of class methods, getters and setters.
Examples of **incorrect** code for this rule with `"never"` and `{ "enforceForClassMembers": true }` (default):
+::: incorrect
+
```js
/*eslint computed-property-spacing: ["error", "never", { "enforceForClassMembers": true }]*/
/*eslint-env es6*/
@@ -141,8 +157,12 @@ const Bar = class {
}
```
+:::
+
Examples of **correct** code for this rule with `"never"` and `{ "enforceForClassMembers": true }` (default):
+::: correct
+
```js
/*eslint computed-property-spacing: ["error", "never", { "enforceForClassMembers": true }]*/
/*eslint-env es6*/
@@ -161,8 +181,12 @@ const Bar = class {
}
```
+:::
+
Examples of **correct** code for this rule with `"never"` and `{ "enforceForClassMembers": false }`:
+::: correct
+
```js
/*eslint computed-property-spacing: ["error", "never", { "enforceForClassMembers": false }]*/
/*eslint-env es6*/
@@ -181,6 +205,8 @@ const Bar = class {
}
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of computed properties.
diff --git a/docs/src/rules/consistent-return.md b/docs/src/rules/consistent-return.md
index 76cf86f0ba2..b948bc5607c 100644
--- a/docs/src/rules/consistent-return.md
+++ b/docs/src/rules/consistent-return.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/consistent-
rule_type: suggestion
---
-Requires `return` statements to either always or never specify values.
Unlike statically-typed languages which enforce that a function returns a specified type of value, JavaScript allows different code paths in a function to return different types of values.
@@ -38,6 +37,8 @@ This rule requires `return` statements to either always or never specify values.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint consistent-return: "error"*/
@@ -56,8 +57,12 @@ function doSomething(condition) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint consistent-return: "error"*/
@@ -78,6 +83,8 @@ function Foo() {
}
```
+:::
+
## Options
This rule has an object option:
@@ -89,6 +96,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "treatUndefinedAsUnspecified": false }` option:
+::: incorrect
+
```js
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": false }]*/
@@ -107,8 +116,12 @@ function bar(condition) {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "treatUndefinedAsUnspecified": true }` option:
+::: incorrect
+
```js
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": true }]*/
@@ -127,8 +140,12 @@ function bar(condition) {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "treatUndefinedAsUnspecified": true }` option:
+::: correct
+
```js
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": true }]*/
@@ -147,6 +164,8 @@ function bar(condition) {
}
```
+:::
+
## When Not To Use It
If you want to allow functions to have different `return` behavior depending on code branching, then it is safe to disable this rule.
diff --git a/docs/src/rules/consistent-this.md b/docs/src/rules/consistent-this.md
index 18ff87ea1eb..8947d92d2f4 100644
--- a/docs/src/rules/consistent-this.md
+++ b/docs/src/rules/consistent-this.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/consistent-
rule_type: suggestion
---
-Enforces consistent naming when capturing the current execution context.
It is often necessary to capture the current execution context in order to make it available subsequently. A prominent example of this are jQuery callbacks:
@@ -34,6 +33,8 @@ This rule has one or more string options:
Examples of **incorrect** code for this rule with the default `"that"` option:
+::: incorrect
+
```js
/*eslint consistent-this: ["error", "that"]*/
@@ -46,8 +47,12 @@ that = 42;
self = this;
```
+:::
+
Examples of **correct** code for this rule with the default `"that"` option:
+::: correct
+
```js
/*eslint consistent-this: ["error", "that"]*/
@@ -62,8 +67,12 @@ that = this;
foo.bar = this;
```
+:::
+
Examples of **incorrect** code for this rule with the default `"that"` option, if the variable is not initialized:
+::: incorrect
+
```js
/*eslint consistent-this: ["error", "that"]*/
@@ -73,8 +82,12 @@ function f() {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"that"` option, if the variable is not initialized:
+::: correct
+
```js
/*eslint consistent-this: ["error", "that"]*/
@@ -86,6 +99,8 @@ foo = 42;
that = this;
```
+:::
+
## When Not To Use It
If you need to capture nested context, `consistent-this` is going to be problematic. Code of that nature is usually difficult to read and maintain and you should consider refactoring it.
diff --git a/docs/src/rules/constructor-super.md b/docs/src/rules/constructor-super.md
index c6510372b4f..1497b0188fb 100644
--- a/docs/src/rules/constructor-super.md
+++ b/docs/src/rules/constructor-super.md
@@ -5,10 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/constructor
rule_type: problem
---
-
-
-Verifies calls of `super()` in constructors.
-
Constructors of derived classes must call `super()`.
Constructors of non derived classes must not call `super()`.
If this is not observed, the JavaScript engine will raise a runtime error.
@@ -21,6 +17,8 @@ This rule is aimed to flag invalid/missing `super()` calls.
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint constructor-super: "error"*/
/*eslint-env es6*/
@@ -47,8 +45,12 @@ class A extends null {
}
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint constructor-super: "error"*/
/*eslint-env es6*/
@@ -64,6 +66,8 @@ class A extends B {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about invalid/missing `super()` callings in constructors, you can safely disable this rule.
diff --git a/docs/src/rules/curly.md b/docs/src/rules/curly.md
index e7f7dd0b1a8..15f28c6559f 100644
--- a/docs/src/rules/curly.md
+++ b/docs/src/rules/curly.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/curly.md
rule_type: suggestion
---
-
-Requires following curly brace conventions.
JavaScript allows the omission of curly braces when a block contains only one statement. However, it is considered by many to be best practice to _never_ omit curly braces around blocks, even when they are optional, because it can lead to bugs and reduces code clarity. So the following:
@@ -35,6 +33,8 @@ This rule is aimed at preventing bugs and increasing code clarity by ensuring th
Examples of **incorrect** code for the default `"all"` option:
+::: incorrect
+
```js
/*eslint curly: "error"*/
@@ -48,8 +48,12 @@ if (foo) {
} else qux();
```
+:::
+
Examples of **correct** code for the default `"all"` option:
+::: correct
+
```js
/*eslint curly: "error"*/
@@ -68,12 +72,16 @@ if (foo) {
}
```
+:::
+
### multi
By default, this rule warns whenever `if`, `else`, `for`, `while`, or `do` are used without block statements as their body. However, you can specify that block statements should be used only when there are multiple statements in the block and warn when there is only one statement in the block.
Examples of **incorrect** code for the `"multi"` option:
+::: incorrect
+
```js
/*eslint curly: ["error", "multi"]*/
@@ -95,8 +103,12 @@ for (var i=0; i < items.length; i++) {
}
```
+:::
+
Examples of **correct** code for the `"multi"` option:
+::: correct
+
```js
/*eslint curly: ["error", "multi"]*/
@@ -110,12 +122,16 @@ while (true) {
}
```
+:::
+
### multi-line
Alternatively, you can relax the rule to allow brace-less single-line `if`, `else if`, `else`, `for`, `while`, or `do`, while still enforcing the use of curly braces for other instances.
Examples of **incorrect** code for the `"multi-line"` option:
+::: incorrect
+
```js
/*eslint curly: ["error", "multi-line"]*/
@@ -129,8 +145,12 @@ if (foo) foo(
baz);
```
+:::
+
Examples of **correct** code for the `"multi-line"` option:
+::: correct
+
```js
/*eslint curly: ["error", "multi-line"]*/
@@ -158,12 +178,16 @@ while (true) {
}
```
+:::
+
### multi-or-nest
You can use another configuration that forces brace-less `if`, `else if`, `else`, `for`, `while`, or `do` if their body contains only one single-line statement. And forces braces in all other cases.
Examples of **incorrect** code for the `"multi-or-nest"` option:
+::: incorrect
+
```js
/*eslint curly: ["error", "multi-or-nest"]*/
@@ -192,8 +216,12 @@ for (var i = 0; foo; i++) {
}
```
+:::
+
Examples of **correct** code for the `"multi-or-nest"` option:
+::: correct
+
```js
/*eslint curly: ["error", "multi-or-nest"]*/
@@ -221,10 +249,14 @@ for (var i = 0; foo; i++)
doSomething();
```
+:::
+
For single-line statements preceded by a comment, braces are allowed but not required.
Examples of additional **correct** code for the `"multi-or-nest"` option:
+::: correct
+
```js
/*eslint curly: ["error", "multi-or-nest"]*/
@@ -238,6 +270,8 @@ if (foo) {
}
```
+:::
+
### consistent
When using any of the `multi*` options, you can add an option to enforce all bodies of a `if`,
@@ -245,6 +279,8 @@ When using any of the `multi*` options, you can add an option to enforce all bod
Examples of **incorrect** code for the `"multi", "consistent"` options:
+::: incorrect
+
```js
/*eslint curly: ["error", "multi", "consistent"]*/
@@ -274,8 +310,12 @@ if (foo) {
}
```
+:::
+
Examples of **correct** code for the `"multi", "consistent"` options:
+::: correct
+
```js
/*eslint curly: ["error", "multi", "consistent"]*/
@@ -305,6 +345,8 @@ if (foo)
```
+:::
+
## When Not To Use It
If you have no strict conventions about when to use block statements and when not to, you can safely disable this rule.
diff --git a/docs/src/rules/default-case-last.md b/docs/src/rules/default-case-last.md
index 279d11280b9..7a3c5d60524 100644
--- a/docs/src/rules/default-case-last.md
+++ b/docs/src/rules/default-case-last.md
@@ -9,7 +9,6 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
---
-Enforces default clauses in switch statements to be last.
A `switch` statement can optionally have a `default` clause.
@@ -29,6 +28,8 @@ This rule does not enforce the existence of `default` clauses. See [default-case
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint default-case-last: "error"*/
@@ -79,8 +80,12 @@ switch (foo) {
}
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint default-case-last: "error"*/
@@ -126,3 +131,5 @@ if (foo !== 0) {
}
doSomethingAnyway();
```
+
+:::
diff --git a/docs/src/rules/default-case.md b/docs/src/rules/default-case.md
index f43bc21b023..cab7be84046 100644
--- a/docs/src/rules/default-case.md
+++ b/docs/src/rules/default-case.md
@@ -7,7 +7,6 @@ related_rules:
- no-fallthrough
---
-Requires a `default` case in switch statements.
Some code conventions require that all `switch` statements have a `default` case, even if the default case is empty, such as:
@@ -52,6 +51,8 @@ This rule aims to require `default` case in `switch` statements. You may optiona
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint default-case: "error"*/
@@ -63,8 +64,12 @@ switch (a) {
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint default-case: "error"*/
@@ -95,6 +100,8 @@ switch (a) {
}
```
+:::
+
## Options
This rule accepts a single options argument:
@@ -105,6 +112,8 @@ This rule accepts a single options argument:
Examples of **correct** code for the `{ "commentPattern": "^skip\\sdefault" }` option:
+::: correct
+
```js
/*eslint default-case: ["error", { "commentPattern": "^skip\\sdefault" }]*/
@@ -125,6 +134,8 @@ switch(a) {
}
```
+:::
+
## When Not To Use It
If you don't want to enforce a `default` case for `switch` statements, you can safely disable this rule.
diff --git a/docs/src/rules/default-param-last.md b/docs/src/rules/default-param-last.md
index a2eea8ea37a..b9e85c71bbd 100644
--- a/docs/src/rules/default-param-last.md
+++ b/docs/src/rules/default-param-last.md
@@ -5,8 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/default-par
rule_type: suggestion
---
-Enforces default parameters to be last.
-
Putting default parameter at last allows function calls to omit optional tail arguments.
```js
@@ -25,6 +23,8 @@ This rule enforces default parameters to be the last of parameters.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/* eslint default-param-last: ["error"] */
@@ -33,10 +33,16 @@ function f(a = 0, b) {}
function f(a, b = 0, c) {}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/* eslint default-param-last: ["error"] */
function f(a, b = 0) {}
```
+
+:::
diff --git a/docs/src/rules/dot-location.md b/docs/src/rules/dot-location.md
index 73b0481edab..5650ddd3bf1 100644
--- a/docs/src/rules/dot-location.md
+++ b/docs/src/rules/dot-location.md
@@ -8,9 +8,7 @@ related_rules:
- dot-notation
---
-
-Enforces newline before and after dots.
JavaScript allows you to place newlines before or after a dot in a member expression.
@@ -41,6 +39,8 @@ The default `"object"` option requires the dot to be on the same line as the obj
Examples of **incorrect** code for the default `"object"` option:
+::: incorrect
+
```js
/*eslint dot-location: ["error", "object"]*/
@@ -48,8 +48,12 @@ var foo = object
.property;
```
+:::
+
Examples of **correct** code for the default `"object"` option:
+::: correct
+
```js
/*eslint dot-location: ["error", "object"]*/
@@ -64,12 +68,16 @@ property;
var baz = object.property;
```
+:::
+
### property
The `"property"` option requires the dot to be on the same line as the property.
Examples of **incorrect** code for the `"property"` option:
+::: incorrect
+
```js
/*eslint dot-location: ["error", "property"]*/
@@ -77,8 +85,12 @@ var foo = object.
property;
```
+:::
+
Examples of **correct** code for the `"property"` option:
+::: correct
+
```js
/*eslint dot-location: ["error", "property"]*/
@@ -87,6 +99,8 @@ var foo = object
var bar = object.property;
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of newlines before or after dots in member expressions.
diff --git a/docs/src/rules/dot-notation.md b/docs/src/rules/dot-notation.md
index d386b4df4e6..3a40363ac42 100644
--- a/docs/src/rules/dot-notation.md
+++ b/docs/src/rules/dot-notation.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/dot-notatio
rule_type: suggestion
---
-
-Enforces dot notation whenever possible.
In JavaScript, one can access properties using the dot notation (`foo.bar`) or square-bracket notation (`foo["bar"]`). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers.
@@ -21,14 +19,20 @@ This rule is aimed at maintaining code consistency and improving code readabilit
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint dot-notation: "error"*/
var x = foo["bar"];
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint dot-notation: "error"*/
@@ -37,6 +41,8 @@ var x = foo.bar;
var x = foo[bar]; // Property name is a variable, square-bracket notation required
```
+:::
+
## Options
This rule accepts a single options argument:
@@ -48,6 +54,8 @@ This rule accepts a single options argument:
Examples of **correct** code for the `{ "allowKeywords": false }` option:
+:::correct
+
```js
/*eslint dot-notation: ["error", { "allowKeywords": false }]*/
@@ -55,8 +63,12 @@ var foo = { "class": "CS 101" }
var x = foo["class"]; // Property name is a reserved word, square-bracket notation required
```
+:::
+
Examples of additional **correct** code for the `{ "allowKeywords": false }` option:
+:::correct
+
```js
/*eslint dot-notation: ["error", { "allowKeywords": false }]*/
@@ -68,12 +80,16 @@ class C {
}
```
+:::
+
### allowPattern
For example, when preparing data to be sent to an external API, it is often required to use property names that include underscores. If the `camelcase` rule is in effect, these [snake case](https://en.wikipedia.org/wiki/Snake_case) properties would not be allowed. By providing an `allowPattern` to the `dot-notation` rule, these snake case properties can be accessed with bracket notation.
Examples of **correct** code for the sample `{ "allowPattern": "^[a-z]+(_[a-z]+)+$" }` option:
+:::correct
+
```js
/*eslint camelcase: "error"*/
/*eslint dot-notation: ["error", { "allowPattern": "^[a-z]+(_[a-z]+)+$" }]*/
@@ -87,3 +103,5 @@ data["fooBar"] = 42;
var data = {};
data["foo_bar"] = 42; // no warning
```
+
+:::
diff --git a/docs/src/rules/eol-last.md b/docs/src/rules/eol-last.md
index 58d8955dd86..a3a19f983bb 100644
--- a/docs/src/rules/eol-last.md
+++ b/docs/src/rules/eol-last.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/eol-last.md
rule_type: layout
---
-
-Requires or disallows newline at the end of files.
Trailing newlines in non-empty files are a common UNIX idiom. Benefits of
trailing newlines include the ability to concatenate or append to files as well
@@ -25,24 +23,32 @@ the end of the file. If you still want this behavior, consider enabling
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint eol-last: ["error", "always"]*/
-function doSmth() {
+function doSomething() {
var foo = 2;
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint eol-last: ["error", "always"]*/
-function doSmth() {
+function doSomething() {
var foo = 2;
}\n
```
+:::
+
## Options
This rule has a string option:
diff --git a/docs/src/rules/eqeqeq.md b/docs/src/rules/eqeqeq.md
index 6874896ada0..6c16d0454a6 100644
--- a/docs/src/rules/eqeqeq.md
+++ b/docs/src/rules/eqeqeq.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/eqeqeq.md
rule_type: suggestion
---
-
-Requires the use of `===` and `!==`.
It is considered good practice to use the type-safe equality operators `===` and `!==` instead of their regular counterparts `==` and `!=`.
@@ -26,6 +24,8 @@ This rule is aimed at eliminating the type-unsafe equality operators.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint eqeqeq: "error"*/
@@ -36,6 +36,8 @@ if ("" == text) { }
if (obj.getStuff() != undefined) { }
```
+:::
+
The `--fix` option on the command line automatically fixes some problems reported by this rule. A problem is only fixed if one of the operands is a `typeof` expression, or if both operands are literals with the same type.
## Options
@@ -46,6 +48,8 @@ The `"always"` option (default) enforces the use of `===` and `!==` in every sit
Examples of **incorrect** code for the `"always"` option:
+::: incorrect
+
```js
/*eslint eqeqeq: ["error", "always"]*/
@@ -61,8 +65,12 @@ foo == null
```
+:::
+
Examples of **correct** code for the `"always"` option:
+::: correct
+
```js
/*eslint eqeqeq: ["error", "always"]*/
@@ -78,6 +86,8 @@ foo === null
```
+:::
+
This rule optionally takes a second argument, which should be an object with the following supported properties:
* `"null"`: Customize how this rule treats `null` literals. Possible values:
@@ -95,6 +105,8 @@ The `"smart"` option enforces the use of `===` and `!==` except for these cases:
Examples of **incorrect** code for the `"smart"` option:
+::: incorrect
+
```js
/*eslint eqeqeq: ["error", "smart"]*/
@@ -109,8 +121,12 @@ bananas != 1
value == undefined
```
+:::
+
Examples of **correct** code for the `"smart"` option:
+::: correct
+
```js
/*eslint eqeqeq: ["error", "smart"]*/
@@ -121,6 +137,8 @@ true == true
foo == null
```
+:::
+
### allow-null
**Deprecated:** Instead of using this option use "always" and pass a "null" option property with value "ignore". This will tell ESLint to always enforce strict equality except when comparing with the `null` literal.
diff --git a/docs/src/rules/for-direction.md b/docs/src/rules/for-direction.md
index f349d2662b8..c9b99d6beae 100644
--- a/docs/src/rules/for-direction.md
+++ b/docs/src/rules/for-direction.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/for-directi
rule_type: problem
---
-
-Enforces `for` loop update clause moving the counter in the right direction.
## Rule Details
@@ -15,6 +13,8 @@ A `for` loop with a stop condition that can never be reached, such as one with a
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint for-direction: "error"*/
for (var i = 0; i < 10; i--) {
@@ -27,10 +27,16 @@ for (var i = 0; i > 10; i++) {
}
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint for-direction: "error"*/
for (var i = 0; i < 10; i++) {
}
```
+
+:::
diff --git a/docs/src/rules/func-call-spacing.md b/docs/src/rules/func-call-spacing.md
index 0f5032b322c..cc2005660b9 100644
--- a/docs/src/rules/func-call-spacing.md
+++ b/docs/src/rules/func-call-spacing.md
@@ -7,9 +7,7 @@ related_rules:
- no-spaced-func
---
-
-Requires or disallows spacing between function identifiers and their invocations.
When calling a function, developers may insert optional whitespace between the function's name and the parentheses that invoke it. The following pairs of function calls are equivalent:
@@ -41,6 +39,8 @@ Further, in `"always"` mode, a second object option is available that contains a
Examples of **incorrect** code for this rule with the default `"never"` option:
+::: incorrect
+
```js
/*eslint func-call-spacing: ["error", "never"]*/
@@ -50,18 +50,26 @@ fn
();
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+::: correct
+
```js
/*eslint func-call-spacing: ["error", "never"]*/
fn();
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint func-call-spacing: ["error", "always"]*/
@@ -71,28 +79,40 @@ fn
();
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint func-call-spacing: ["error", "always"]*/
fn ();
```
+:::
+
#### allowNewlines
By default, `"always"` does not allow newlines. To permit newlines when in `"always"` mode, set the `allowNewlines` option to `true`. Newlines are never required.
Examples of **incorrect** code for this rule with `allowNewlines` option enabled:
+::: incorrect
+
```js
/*eslint func-call-spacing: ["error", "always", { "allowNewlines": true }]*/
fn();
```
+:::
+
Examples of **correct** code for this rule with the `allowNewlines` option enabled:
+::: correct
+
```js
/*eslint func-call-spacing: ["error", "always", { "allowNewlines": true }]*/
@@ -102,6 +122,8 @@ fn
();
```
+:::
+
## When Not To Use It
This rule can safely be turned off if your project does not care about enforcing a consistent style for spacing within function calls.
diff --git a/docs/src/rules/func-name-matching.md b/docs/src/rules/func-name-matching.md
index 21217c7140c..fc45a652859 100644
--- a/docs/src/rules/func-name-matching.md
+++ b/docs/src/rules/func-name-matching.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/func-name-m
rule_type: suggestion
---
-Requires function names to match the name of the variable or property to which they are assigned.
## Rule Details
@@ -13,6 +12,8 @@ This rule requires function names to match the name of the variable or property
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint func-name-matching: "error"*/
@@ -28,6 +29,10 @@ class C {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint func-name-matching: ["error", "never"] */
@@ -43,8 +48,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint func-name-matching: "error"*/
/*eslint func-name-matching: ["error", "always"]*/ // these are equivalent
@@ -88,6 +97,10 @@ module.exports = function foo(name) {};
module['exports'] = function foo(name) {};
```
+:::
+
+::: correct
+
```js
/*eslint func-name-matching: ["error", "never"] */
/*eslint-env es6*/
@@ -130,6 +143,8 @@ module.exports = function foo(name) {};
module['exports'] = function foo(name) {};
```
+:::
+
## Options
This rule takes an optional string of "always" or "never" (when omitted, it defaults to "always"), and an optional options object with two properties `considerPropertyDescriptor` and `includeCommonJSModuleExports`.
@@ -140,6 +155,8 @@ A boolean value that defaults to `false`. If `considerPropertyDescriptor` is set
Examples of **correct** code for the `{ considerPropertyDescriptor: true }` option:
+::: correct
+
```js
/*eslint func-name-matching: ["error", { "considerPropertyDescriptor": true }]*/
/*eslint func-name-matching: ["error", "always", { "considerPropertyDescriptor": true }]*/ // these are equivalent
@@ -150,8 +167,12 @@ Object.defineProperties(obj, {baz:{value: function baz() {} }});
Reflect.defineProperty(obj, 'foo', {value: function foo() {}});
```
+:::
+
Examples of **incorrect** code for the `{ considerPropertyDescriptor: true }` option:
+::: incorrect
+
```js
/*eslint func-name-matching: ["error", { "considerPropertyDescriptor": true }]*/
/*eslint func-name-matching: ["error", "always", { "considerPropertyDescriptor": true }]*/ // these are equivalent
@@ -162,12 +183,16 @@ Object.defineProperties(obj, {baz:{value: function foo() {} }});
Reflect.defineProperty(obj, 'foo', {value: function value() {}});
```
+:::
+
### includeCommonJSModuleExports
A boolean value that defaults to `false`. If `includeCommonJSModuleExports` is set to true, `module.exports` and `module["exports"]` will be checked by this rule.
Examples of **incorrect** code for the `{ includeCommonJSModuleExports: true }` option:
+::: incorrect
+
```js
/*eslint func-name-matching: ["error", { "includeCommonJSModuleExports": true }]*/
/*eslint func-name-matching: ["error", "always", { "includeCommonJSModuleExports": true }]*/ // these are equivalent
@@ -176,6 +201,8 @@ module.exports = function foo(name) {};
module['exports'] = function foo(name) {};
```
+:::
+
## When Not To Use It
Do not use this rule if you want to allow named functions to have different names from the variable or property to which they are assigned.
diff --git a/docs/src/rules/func-names.md b/docs/src/rules/func-names.md
index b626860066d..bdc0ea596f0 100644
--- a/docs/src/rules/func-names.md
+++ b/docs/src/rules/func-names.md
@@ -8,7 +8,6 @@ further_reading:
- https://2ality.com/2015/09/function-names-es6.html
---
-Requires or disallows named `function` expressions.
A pattern that's becoming more common is to give function expressions names to aid in debugging. For example:
@@ -45,6 +44,8 @@ Please note that `"always"` and `"as-needed"` require function expressions and f
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint func-names: ["error", "always"]*/
@@ -61,8 +62,12 @@ const cat = {
export default function() {}
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint func-names: ["error", "always"]*/
@@ -79,12 +84,16 @@ const cat = {
export default function foo() {}
```
+:::
+
### as-needed
ECMAScript 6 introduced a `name` property on all functions. The value of `name` is determined by evaluating the code around the function to see if a name can be inferred. For example, a function assigned to a variable will automatically have a `name` property equal to the name of the variable. The value of `name` is then used in stack traces for easier debugging.
Examples of **incorrect** code for this rule with the `"as-needed"` option:
+::: incorrect
+
```js
/*eslint func-names: ["error", "as-needed"]*/
@@ -97,8 +106,12 @@ Foo.prototype.bar = function() {};
export default function() {}
```
+:::
+
Examples of **correct** code for this rule with the `"as-needed"` option:
+::: correct
+
```js
/*eslint func-names: ["error", "as-needed"]*/
@@ -122,10 +135,14 @@ quux ??= function() {};
export default function foo() {}
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint func-names: ["error", "never"]*/
@@ -136,8 +153,12 @@ Foo.prototype.bar = function bar() {};
}())
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint func-names: ["error", "never"]*/
@@ -148,10 +169,14 @@ Foo.prototype.bar = function() {};
}())
```
+:::
+
### generators
Examples of **incorrect** code for this rule with the `"always", { "generators": "as-needed" }` options:
+::: incorrect
+
```js
/*eslint func-names: ["error", "always", { "generators": "as-needed" }]*/
@@ -160,62 +185,92 @@ Examples of **incorrect** code for this rule with the `"always", { "generators":
}())
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "generators": "as-needed" }` options:
+::: correct
+
```js
/*eslint func-names: ["error", "always", { "generators": "as-needed" }]*/
var foo = function*() {};
```
+:::
+
Examples of **incorrect** code for this rule with the `"always", { "generators": "never" }` options:
+::: incorrect
+
```js
/*eslint func-names: ["error", "always", { "generators": "never" }]*/
var foo = bar(function *baz() {});
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "generators": "never" }` options:
+::: correct
+
```js
/*eslint func-names: ["error", "always", { "generators": "never" }]*/
var foo = bar(function *() {});
```
+:::
+
Examples of **incorrect** code for this rule with the `"as-needed", { "generators": "never" }` options:
+::: incorrect
+
```js
/*eslint func-names: ["error", "as-needed", { "generators": "never" }]*/
var foo = bar(function *baz() {});
```
+:::
+
Examples of **correct** code for this rule with the `"as-needed", { "generators": "never" }` options:
+::: correct
+
```js
/*eslint func-names: ["error", "as-needed", { "generators": "never" }]*/
var foo = bar(function *() {});
```
+:::
+
Examples of **incorrect** code for this rule with the `"never", { "generators": "always" }` options:
+::: incorrect
+
```js
/*eslint func-names: ["error", "never", { "generators": "always" }]*/
var foo = bar(function *() {});
```
+:::
+
Examples of **correct** code for this rule with the `"never", { "generators": "always" }` options:
+::: correct
+
```js
/*eslint func-names: ["error", "never", { "generators": "always" }]*/
var foo = bar(function *baz() {});
```
+:::
+
## Compatibility
* **JSCS**: [requireAnonymousFunctions](https://jscs-dev.github.io/rule/requireAnonymousFunctions)
diff --git a/docs/src/rules/func-style.md b/docs/src/rules/func-style.md
index 769a7a1f8a5..8897692cec0 100644
--- a/docs/src/rules/func-style.md
+++ b/docs/src/rules/func-style.md
@@ -7,7 +7,6 @@ further_reading:
- https://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
---
-Enforces the consistent use of either `function` declarations or expressions.
There are two ways of defining functions in JavaScript: `function` declarations and `function` expressions. Declarations contain the `function` keyword first, followed by a name and then its arguments and the function body, for example:
@@ -70,6 +69,8 @@ This rule has an object option for an exception:
Examples of **incorrect** code for this rule with the default `"expression"` option:
+::: incorrect
+
```js
/*eslint func-style: ["error", "expression"]*/
@@ -78,8 +79,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"expression"` option:
+::: correct
+
```js
/*eslint func-style: ["error", "expression"]*/
@@ -92,10 +97,14 @@ var foo = () => {};
// allowed as allowArrowFunctions : false is applied only for declaration
```
+:::
+
### declaration
Examples of **incorrect** code for this rule with the `"declaration"` option:
+::: incorrect
+
```js
/*eslint func-style: ["error", "declaration"]*/
@@ -106,8 +115,12 @@ var foo = function() {
var foo = () => {};
```
+:::
+
Examples of **correct** code for this rule with the `"declaration"` option:
+::: correct
+
```js
/*eslint func-style: ["error", "declaration"]*/
@@ -121,16 +134,22 @@ SomeObject.foo = function() {
};
```
+:::
+
### allowArrowFunctions
Examples of additional **correct** code for this rule with the `"declaration", { "allowArrowFunctions": true }` options:
+::: correct
+
```js
/*eslint func-style: ["error", "declaration", { "allowArrowFunctions": true }]*/
var foo = () => {};
```
+:::
+
## When Not To Use It
If you want to allow developers to each decide how they want to write functions on their own, then you can disable this rule.
diff --git a/docs/src/rules/function-call-argument-newline.md b/docs/src/rules/function-call-argument-newline.md
index 53c04991560..6a5ffb8c173 100644
--- a/docs/src/rules/function-call-argument-newline.md
+++ b/docs/src/rules/function-call-argument-newline.md
@@ -10,9 +10,7 @@ related_rules:
- array-element-newline
---
-
-Enforces line breaks between arguments of a function call.
A number of style guides require or disallow line breaks between arguments of a function call.
@@ -32,6 +30,8 @@ This rule has a string option:
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint function-call-argument-newline: ["error", "always"]*/
@@ -47,8 +47,12 @@ baz("one", "two", (x) => {
});
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint function-call-argument-newline: ["error", "always"]*/
@@ -82,10 +86,14 @@ baz(
);
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint function-call-argument-newline: ["error", "never"]*/
@@ -110,8 +118,12 @@ baz(
);
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint function-call-argument-newline: ["error", "never"]*/
@@ -133,10 +145,14 @@ baz("one", "two", (x) => {
});
```
+:::
+
### consistent
Examples of **incorrect** code for this rule with the `"consistent"` option:
+::: incorrect
+
```js
/*eslint function-call-argument-newline: ["error", "consistent"]*/
@@ -155,8 +171,12 @@ baz("one", "two",
);
```
+:::
+
Examples of **correct** code for this rule with the `"consistent"` option:
+::: correct
+
```js
/*eslint function-call-argument-newline: ["error", "consistent"]*/
@@ -201,6 +221,8 @@ baz(
);
```
+:::
+
## When Not To Use It
If you don't want to enforce line breaks between arguments, don't enable this rule.
diff --git a/docs/src/rules/function-paren-newline.md b/docs/src/rules/function-paren-newline.md
index 3c3f04d569e..da1743ca9e7 100644
--- a/docs/src/rules/function-paren-newline.md
+++ b/docs/src/rules/function-paren-newline.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/function-pa
rule_type: layout
---
-
-Enforces consistent line breaks inside function parentheses.
Many style guides require or disallow newlines inside of function parentheses.
@@ -46,6 +44,8 @@ Example configurations:
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/* eslint function-paren-newline: ["error", "always"] */
@@ -58,8 +58,12 @@ var foo = (bar, baz) => {};
foo(bar, baz);
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/* eslint function-paren-newline: ["error", "always"] */
@@ -83,8 +87,12 @@ foo(
);
```
+:::
+
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/* eslint function-paren-newline: ["error", "never"] */
@@ -108,8 +116,12 @@ foo(
);
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/* eslint function-paren-newline: ["error", "never"] */
@@ -128,8 +140,12 @@ foo(bar,
baz);
```
+:::
+
Examples of **incorrect** code for this rule with the default `"multiline"` option:
+::: incorrect
+
```js
/* eslint function-paren-newline: ["error", "multiline"] */
@@ -155,8 +171,12 @@ foo(
);
```
+:::
+
Examples of **correct** code for this rule with the default `"multiline"` option:
+::: correct
+
```js
/* eslint function-paren-newline: ["error", "multiline"] */
@@ -182,8 +202,12 @@ foo(function() {
});
```
+:::
+
Examples of **incorrect** code for this rule with the `"consistent"` option:
+::: incorrect
+
```js
/* eslint function-paren-newline: ["error", "consistent"] */
@@ -209,8 +233,12 @@ foo(
});
```
+:::
+
Examples of **correct** code for this rule with the `"consistent"` option:
+::: correct
+
```js
/* eslint function-paren-newline: ["error", "consistent"] */
@@ -235,8 +263,12 @@ foo(
);
```
+:::
+
Examples of **incorrect** code for this rule with the `"multiline-arguments"` option:
+::: incorrect
+
```js
/* eslint function-paren-newline: ["error", "multiline-arguments"] */
@@ -262,8 +294,12 @@ foo(
);
```
+:::
+
Examples of **correct** code for this rule with the consistent `"multiline-arguments"` option:
+::: correct
+
```js
/* eslint function-paren-newline: ["error", "multiline-arguments"] */
@@ -285,8 +321,12 @@ foo(
);
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "minItems": 3 }` option:
+::: incorrect
+
```js
/* eslint function-paren-newline: ["error", { "minItems": 3 }] */
@@ -308,8 +348,12 @@ foo(bar,
baz);
```
+:::
+
Examples of **correct** code for this rule with the `{ "minItems": 3 }` option:
+::: correct
+
```js
/* eslint function-paren-newline: ["error", { "minItems": 3 }] */
@@ -332,6 +376,8 @@ foo(
);
```
+:::
+
## When Not To Use It
If don't want to enforce consistent linebreaks inside function parentheses, do not turn on this rule.
diff --git a/docs/src/rules/generator-star-spacing.md b/docs/src/rules/generator-star-spacing.md
index 0833382a6c8..8525a0879eb 100644
--- a/docs/src/rules/generator-star-spacing.md
+++ b/docs/src/rules/generator-star-spacing.md
@@ -7,9 +7,7 @@ further_reading:
- https://leanpub.com/understandinges6/read/#leanpub-auto-generators
---
-
-Enforces spacing around the `*` in generator functions.
Generators are a new type of function in ECMAScript 6 that can return multiple values over time.
These special functions are indicated by placing an `*` after the `function` keyword.
@@ -113,6 +111,8 @@ Overrides can be either an object with "before" and "after", or a shorthand stri
Examples of **correct** code for this rule with the `"before"` option:
+::: correct
+
```js
/*eslint generator-star-spacing: ["error", {"before": true, "after": false}]*/
/*eslint-env es6*/
@@ -124,10 +124,14 @@ var anonymous = function *() {};
var shorthand = { *generator() {} };
```
+:::
+
### after
Examples of **correct** code for this rule with the `"after"` option:
+::: correct
+
```js
/*eslint generator-star-spacing: ["error", {"before": false, "after": true}]*/
/*eslint-env es6*/
@@ -139,10 +143,14 @@ var anonymous = function* () {};
var shorthand = { * generator() {} };
```
+:::
+
### both
Examples of **correct** code for this rule with the `"both"` option:
+::: correct
+
```js
/*eslint generator-star-spacing: ["error", {"before": true, "after": true}]*/
/*eslint-env es6*/
@@ -154,10 +162,14 @@ var anonymous = function * () {};
var shorthand = { * generator() {} };
```
+:::
+
### neither
Examples of **correct** code for this rule with the `"neither"` option:
+::: correct
+
```js
/*eslint generator-star-spacing: ["error", {"before": false, "after": false}]*/
/*eslint-env es6*/
@@ -169,8 +181,12 @@ var anonymous = function*() {};
var shorthand = { *generator() {} };
```
+:::
+
Examples of **incorrect** code for this rule with overrides present:
+::: incorrect
+
```js
/*eslint generator-star-spacing: ["error", {
"before": false,
@@ -189,8 +205,12 @@ var shorthand = { *generator() {} };
class Class { static* method() {} }
```
+:::
+
Examples of **correct** code for this rule with overrides present:
+::: correct
+
```js
/*eslint generator-star-spacing: ["error", {
"before": false,
@@ -209,6 +229,8 @@ var shorthand = { * generator() {} };
class Class { static * method() {} }
```
+:::
+
## When Not To Use It
If your project will not be using generators or you are not concerned with spacing consistency, you do not need this rule.
diff --git a/docs/src/rules/getter-return.md b/docs/src/rules/getter-return.md
index 4b3770d84e2..31dbd108b70 100644
--- a/docs/src/rules/getter-return.md
+++ b/docs/src/rules/getter-return.md
@@ -8,9 +8,7 @@ further_reading:
- https://leanpub.com/understandinges6/read/#leanpub-auto-accessor-properties
---
-
-Enforces that a `return` statement is present in property getters.
The get syntax binds an object property to a function that will be called when that property is looked up. It was first introduced in ECMAScript 5:
@@ -36,6 +34,8 @@ This rule enforces that a return statement is present in property getters.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint getter-return: "error"*/
@@ -58,8 +58,12 @@ class P{
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint getter-return: "error"*/
@@ -82,6 +86,8 @@ class P{
}
```
+:::
+
## Options
This rule has an object option:
@@ -90,6 +96,8 @@ This rule has an object option:
Examples of **correct** code for the `{ "allowImplicit": true }` option:
+::: correct
+
```js
/*eslint getter-return: ["error", { allowImplicit: true }]*/
p = {
@@ -99,6 +107,8 @@ p = {
};
```
+:::
+
## When Not To Use It
If your project will not be using ES5 property getters you do not need this rule.
diff --git a/docs/src/rules/global-require.md b/docs/src/rules/global-require.md
index 0650cb07eaf..6c07bbbcb7b 100644
--- a/docs/src/rules/global-require.md
+++ b/docs/src/rules/global-require.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/global-requ
rule_type: suggestion
---
-Enforces `require()` on the top-level module scope.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -35,6 +34,8 @@ This rule requires all calls to `require()` to be at the top level of the module
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint global-require: "error"*/
/*eslint-env es6*/
@@ -73,8 +74,12 @@ try {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint global-require: "error"*/
@@ -100,6 +105,8 @@ var x = require("x"),
z = require("z");
```
+:::
+
## When Not To Use It
If you have a module that must be initialized with information that comes from the file-system or if a module is only used in very rare situations and will cause significant overhead to load it may make sense to disable the rule. If you need to `require()` an optional dependency inside of a `try`/`catch`, you can disable this rule for just that dependency using the `// eslint-disable-line global-require` comment.
diff --git a/docs/src/rules/grouped-accessor-pairs.md b/docs/src/rules/grouped-accessor-pairs.md
index 45fd15f862a..a9eaa212415 100644
--- a/docs/src/rules/grouped-accessor-pairs.md
+++ b/docs/src/rules/grouped-accessor-pairs.md
@@ -13,7 +13,6 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
---
-Requires grouped accessor pairs in object literals and classes.
A getter and setter for the same property don't necessarily have to be defined adjacent to each other.
@@ -55,6 +54,8 @@ This rule does not enforce the existence of the pair for a getter or a setter. S
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint grouped-accessor-pairs: "error"*/
@@ -99,8 +100,12 @@ const Bar = class {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint grouped-accessor-pairs: "error"*/
@@ -145,6 +150,8 @@ const Bar = class {
}
```
+:::
+
## Options
This rule has a string option:
@@ -157,6 +164,8 @@ This rule has a string option:
Examples of **incorrect** code for this rule with the `"getBeforeSet"` option:
+::: incorrect
+
```js
/*eslint grouped-accessor-pairs: ["error", "getBeforeSet"]*/
@@ -188,8 +197,12 @@ const Bar = class {
}
```
+:::
+
Examples of **correct** code for this rule with the `"getBeforeSet"` option:
+::: correct
+
```js
/*eslint grouped-accessor-pairs: ["error", "getBeforeSet"]*/
@@ -221,10 +234,14 @@ const Bar = class {
}
```
+:::
+
### setBeforeGet
Examples of **incorrect** code for this rule with the `"setBeforeGet"` option:
+::: incorrect
+
```js
/*eslint grouped-accessor-pairs: ["error", "setBeforeGet"]*/
@@ -256,8 +273,12 @@ const Bar = class {
}
```
+:::
+
Examples of **correct** code for this rule with the `"setBeforeGet"` option:
+::: correct
+
```js
/*eslint grouped-accessor-pairs: ["error", "setBeforeGet"]*/
@@ -289,6 +310,8 @@ const Bar = class {
}
```
+:::
+
## Known Limitations
Due to the limits of static analysis, this rule does not account for possible side effects and in certain cases
diff --git a/docs/src/rules/guard-for-in.md b/docs/src/rules/guard-for-in.md
index dec9df17999..8e3d22e2507 100644
--- a/docs/src/rules/guard-for-in.md
+++ b/docs/src/rules/guard-for-in.md
@@ -10,7 +10,6 @@ further_reading:
- https://2ality.com/2012/01/objects-as-maps.html
---
-Requires `for in` loops to include an `if` statement.
Looping over objects with a `for in` loop will include properties that are inherited through the prototype chain. This behavior can lead to unexpected items in your for loop.
@@ -28,6 +27,8 @@ This rule is aimed at preventing unexpected behavior that could arise from using
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint guard-for-in: "error"*/
@@ -36,8 +37,12 @@ for (key in foo) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint guard-for-in: "error"*/
@@ -53,3 +58,5 @@ for (key in foo) {
}
}
```
+
+:::
diff --git a/docs/src/rules/handle-callback-err.md b/docs/src/rules/handle-callback-err.md
index fb2b7c72b95..210b119c7d4 100644
--- a/docs/src/rules/handle-callback-err.md
+++ b/docs/src/rules/handle-callback-err.md
@@ -8,7 +8,6 @@ further_reading:
- https://web.archive.org/web/20171224042620/https://docs.nodejitsu.com/articles/errors/what-are-the-error-conventions/
---
-Enforces callback error handling.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -32,6 +31,8 @@ The rule takes a single string option: the name of the error parameter. The defa
Examples of **incorrect** code for this rule with the default `"err"` parameter name:
+::: incorrect
+
```js
/*eslint handle-callback-err: "error"*/
@@ -41,8 +42,12 @@ function loadData (err, data) {
```
+:::
+
Examples of **correct** code for this rule with the default `"err"` parameter name:
+::: correct
+
```js
/*eslint handle-callback-err: "error"*/
@@ -58,8 +63,12 @@ function generateError (err) {
}
```
+:::
+
Examples of **correct** code for this rule with a sample `"error"` parameter name:
+::: correct
+
```js
/*eslint handle-callback-err: ["error", "error"]*/
@@ -71,6 +80,8 @@ function loadData (error, data) {
}
```
+:::
+
### regular expression
Sometimes (especially in big projects) the name of the error variable is not consistent across the project,
diff --git a/docs/src/rules/id-blacklist.md b/docs/src/rules/id-blacklist.md
index bfb44e22a55..3c5cce27506 100644
--- a/docs/src/rules/id-blacklist.md
+++ b/docs/src/rules/id-blacklist.md
@@ -5,6 +5,5 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/id-blacklis
rule_type: suggestion
---
-Disallows specified identifiers.
This rule was **deprecated** in ESLint v7.5.0 and replaced by the [id-denylist](id-denylist) rule.
diff --git a/docs/src/rules/id-denylist.md b/docs/src/rules/id-denylist.md
index c5678a50fd5..9a782d613ad 100644
--- a/docs/src/rules/id-denylist.md
+++ b/docs/src/rules/id-denylist.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/id-denylist
rule_type: suggestion
---
-Disallows specified identifiers.
> "There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
@@ -42,6 +41,8 @@ For example, to restrict the use of common generic identifiers:
Examples of **incorrect** code for this rule with sample `"data", "callback"` restricted identifiers:
+::: incorrect
+
```js
/*eslint id-denylist: ["error", "data", "callback"] */
@@ -76,8 +77,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule with sample `"data", "callback"` restricted identifiers:
+::: correct
+
```js
/*eslint id-denylist: ["error", "data", "callback"] */
@@ -118,6 +123,8 @@ class Foo {
}
```
+:::
+
## When Not To Use It
You can turn this rule off if you do not want to restrict the use of certain identifiers.
diff --git a/docs/src/rules/id-length.md b/docs/src/rules/id-length.md
index 318b2be6571..a6b5c1a4d88 100644
--- a/docs/src/rules/id-length.md
+++ b/docs/src/rules/id-length.md
@@ -10,7 +10,6 @@ related_rules:
- camelcase
---
-Enforces minimum and maximum identifier lengths.
Very short identifier names like `e`, `x`, `_t` or very long ones like `hashGeneratorResultOutputContainerObject` can make code harder to read and potentially less maintainable. To prevent this, one may enforce a minimum and/or maximum identifier length.
@@ -26,6 +25,8 @@ This rule enforces a minimum and/or maximum identifier length convention.
Examples of **incorrect** code for this rule with the default options:
+::: incorrect
+
```js
/*eslint id-length: "error"*/ // default is minimum 2-chars ({ "min": 2 })
/*eslint-env es6*/
@@ -55,8 +56,12 @@ var { prop: a} = {};
({ prop: obj.x } = {});
```
+:::
+
Examples of **correct** code for this rule with the default options:
+::: correct
+
```js
/*eslint id-length: "error"*/ // default is minimum 2-chars ({ "min": 2 })
/*eslint-env es6*/
@@ -93,6 +98,8 @@ var data = { "x": 1 }; // excused because of quotes
data["y"] = 3; // excused because of calculated property access
```
+:::
+
This rule has an object option:
* `"min"` (default: 2) enforces a minimum identifier length
@@ -106,6 +113,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the `{ "min": 4 }` option:
+::: incorrect
+
```js
/*eslint id-length: ["error", { "min": 4 }]*/
/*eslint-env es6*/
@@ -130,8 +139,12 @@ var { prop: [x]} = {};
({ prop: obj.x } = {});
```
+:::
+
Examples of **correct** code for this rule with the `{ "min": 4 }` option:
+::: correct
+
```js
/*eslint id-length: ["error", { "min": 4 }]*/
/*eslint-env es6*/
@@ -160,10 +173,14 @@ var data = { "x": 1 }; // excused because of quotes
data["y"] = 3; // excused because of calculated property access
```
+:::
+
### max
Examples of **incorrect** code for this rule with the `{ "max": 10 }` option:
+::: incorrect
+
```js
/*eslint id-length: ["error", { "max": 10 }]*/
/*eslint-env es6*/
@@ -181,8 +198,12 @@ try {
var [reallyLongFirstElementName] = arr;
```
+:::
+
Examples of **correct** code for this rule with the `{ "max": 10 }` option:
+::: correct
+
```js
/*eslint id-length: ["error", { "max": 10 }]*/
/*eslint-env es6*/
@@ -200,10 +221,14 @@ try {
var [first] = arr;
```
+:::
+
### properties
Examples of **correct** code for this rule with the `{ "properties": "never" }` option:
+::: correct
+
```js
/*eslint id-length: ["error", { "properties": "never" }]*/
/*eslint-env es6*/
@@ -213,10 +238,14 @@ var myObj = { a: 1 };
({ prop: obj.i } = {});
```
+:::
+
### exceptions
Examples of additional **correct** code for this rule with the `{ "exceptions": ["x"] }` option:
+::: correct
+
```js
/*eslint id-length: ["error", { "exceptions": ["x"] }]*/
/*eslint-env es6*/
@@ -236,10 +265,14 @@ const { x } = foo;
const { a: x } = foo;
```
+:::
+
### exceptionPatterns
Examples of additional **correct** code for this rule with the `{ "exceptionPatterns": ["E|S", "[x-z]"] }` option:
+::: correct
+
```js
/*eslint id-length: ["error", { "exceptionPatterns": ["E|S", "[x-z]"] }]*/
/*eslint-env es6*/
@@ -258,3 +291,5 @@ var [E] = arr;
const { y } = foo;
const { a: z } = foo;
```
+
+:::
diff --git a/docs/src/rules/id-match.md b/docs/src/rules/id-match.md
index 606a605d400..db43aa80cda 100644
--- a/docs/src/rules/id-match.md
+++ b/docs/src/rules/id-match.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/id-match.md
rule_type: suggestion
---
-Requires identifiers to match a specified regular expression.
> "There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
@@ -32,6 +31,8 @@ For example, to enforce a camelcase naming convention:
Examples of **incorrect** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$"` option:
+::: incorrect
+
```js
/*eslint id-match: ["error", "^[a-z]+([A-Z][a-z]+)*$"]*/
@@ -58,8 +59,12 @@ class myClass {
}
```
+:::
+
Examples of **correct** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$"` option:
+::: correct
+
```js
/*eslint id-match: ["error", "^[a-z]+([A-Z][a-z]+)*$"]*/
@@ -82,6 +87,8 @@ class myClass {
}
```
+:::
+
This rule has an object option:
* `"properties": false` (default) does not check object properties
@@ -97,6 +104,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$", { "properties": true }` options:
+::: incorrect
+
```js
/*eslint id-match: ["error", "^[a-z]+([A-Z][a-z]+)*$", { "properties": true }]*/
@@ -105,10 +114,14 @@ var obj = {
};
```
+:::
+
### classFields
Examples of **incorrect** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$", { "classFields": true }` options:
+::: incorrect
+
```js
/*eslint id-match: ["error", "^[a-z]+([A-Z][a-z]+)*$", { "properties": true }]*/
@@ -121,20 +134,28 @@ class myClass {
}
```
+:::
+
### onlyDeclarations
Examples of **correct** code for this rule with the `"^[a-z]+([A-Z][a-z]+)*$", { "onlyDeclarations": true }` options:
+::: correct
+
```js
/*eslint id-match: [2, "^[a-z]+([A-Z][a-z]+)*$", { "onlyDeclarations": true }]*/
do_something(__dirname);
```
+:::
+
### ignoreDestructuring: false
Examples of **incorrect** code for this rule with the default `"^[^_]+$", { "ignoreDestructuring": false }` option:
+::: incorrect
+
```js
/*eslint id-match: [2, "^[^_]+$", { "ignoreDestructuring": false }]*/
@@ -149,10 +170,14 @@ var { category_id: category_alias } = query;
var { category_id: categoryId, ...other_props } = query;
```
+:::
+
### ignoreDestructuring: true
Examples of **incorrect** code for this rule with the `"^[^_]+$", { "ignoreDestructuring": true }` option:
+::: incorrect
+
```js
/*eslint id-match: [2, "^[^_]+$", { "ignoreDestructuring": true }]*/
@@ -161,8 +186,12 @@ var { category_id: category_alias } = query;
var { category_id, ...other_props } = query;
```
+:::
+
Examples of **correct** code for this rule with the `"^[^_]+$", { "ignoreDestructuring": true }` option:
+::: correct
+
```js
/*eslint id-match: [2, "^[^_]+$", { "ignoreDestructuring": true }]*/
@@ -173,6 +202,8 @@ var { category_id = 1 } = query;
var { category_id: category_id } = query;
```
+:::
+
## When Not To Use It
If you don't want to enforce any particular naming convention for all identifiers, or your naming convention is too complex to be enforced by configuring this rule, then you should not enable this rule.
diff --git a/docs/src/rules/implicit-arrow-linebreak.md b/docs/src/rules/implicit-arrow-linebreak.md
index 1a0941bd1bd..b7887761bad 100644
--- a/docs/src/rules/implicit-arrow-linebreak.md
+++ b/docs/src/rules/implicit-arrow-linebreak.md
@@ -7,9 +7,7 @@ related_rules:
- brace-style
---
-
-Enforces the location of arrow function bodies with implicit returns.
An arrow function body can contain an implicit return as an expression instead of a block body. It can be useful to enforce a consistent location for the implicitly returned expression.
@@ -26,6 +24,8 @@ This rule accepts a string option:
Examples of **incorrect** code for this rule with the default `"beside"` option:
+::: incorrect
+
```js
/* eslint implicit-arrow-linebreak: ["error", "beside"] */
@@ -45,8 +45,12 @@ Examples of **incorrect** code for this rule with the default `"beside"` option:
);
```
+:::
+
Examples of **correct** code for this rule with the default `"beside"` option:
+::: correct
+
```js
/* eslint implicit-arrow-linebreak: ["error", "beside"] */
@@ -72,8 +76,12 @@ Examples of **correct** code for this rule with the default `"beside"` option:
}
```
+:::
+
Examples of **incorrect** code for this rule with the `"below"` option:
+::: incorrect
+
```js
/* eslint implicit-arrow-linebreak: ["error", "below"] */
@@ -84,8 +92,12 @@ Examples of **incorrect** code for this rule with the `"below"` option:
(foo) => bar => baz;
```
+:::
+
Examples of **correct** code for this rule with the `"below"` option:
+::: correct
+
```js
/* eslint implicit-arrow-linebreak: ["error", "below"] */
@@ -100,6 +112,8 @@ Examples of **correct** code for this rule with the `"below"` option:
baz;
```
+:::
+
## When Not To Use It
If you're not concerned about consistent locations of implicitly returned arrow function expressions, you should not turn on this rule.
diff --git a/docs/src/rules/indent-legacy.md b/docs/src/rules/indent-legacy.md
index d63b125a65b..9c887d802a4 100644
--- a/docs/src/rules/indent-legacy.md
+++ b/docs/src/rules/indent-legacy.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/indent-lega
rule_type: layout
---
-
-Enforces consistent indentation.
This rule was **deprecated** in ESLint v4.0.0.
@@ -57,6 +55,8 @@ Or for tabbed indentation:
Examples of **incorrect** code for this rule with the default options:
+::: incorrect
+
```js
/*eslint indent: "error"*/
@@ -68,8 +68,12 @@ if (a) {
}
```
+:::
+
Examples of **correct** code for this rule with the default options:
+::: correct
+
```js
/*eslint indent: "error"*/
@@ -81,6 +85,8 @@ if (a) {
}
```
+:::
+
This rule has an object option:
* `"SwitchCase"` (default: 0) enforces indentation level for `case` clauses in `switch` statements
@@ -119,6 +125,8 @@ Level of indentation denotes the multiple of the indent specified. Example:
Examples of **incorrect** code for this rule with the `"tab"` option:
+::: incorrect
+
```js
/*eslint indent: ["error", "tab"]*/
@@ -130,8 +138,12 @@ function foo(d) {
}
```
+:::
+
Examples of **correct** code for this rule with the `"tab"` option:
+::: correct
+
```js
/*eslint indent: ["error", "tab"]*/
@@ -143,10 +155,14 @@ if (a) {
}
```
+:::
+
### SwitchCase
Examples of **incorrect** code for this rule with the `2, { "SwitchCase": 1 }` options:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/
@@ -158,8 +174,12 @@ case "b":
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "SwitchCase": 1 }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/
@@ -171,10 +191,14 @@ switch(a){
}
```
+:::
+
### VariableDeclarator
Examples of **incorrect** code for this rule with the `2, { "VariableDeclarator": 1 }` options:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]*/
/*eslint-env es6*/
@@ -190,8 +214,12 @@ const a = 1,
c = 3;
```
+:::
+
Examples of **correct** code for this rule with the `2, { "VariableDeclarator": 1 }` options:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]*/
/*eslint-env es6*/
@@ -207,8 +235,12 @@ const a = 1,
c = 3;
```
+:::
+
Examples of **correct** code for this rule with the `2, { "VariableDeclarator": 2 }` options:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": 2 }]*/
/*eslint-env es6*/
@@ -224,8 +256,12 @@ const a = 1,
c = 3;
```
+:::
+
Examples of **correct** code for this rule with the `2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }` options:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }]*/
/*eslint-env es6*/
@@ -241,10 +277,14 @@ const a = 1,
c = 3;
```
+:::
+
### outerIIFEBody
Examples of **incorrect** code for this rule with the options `2, { "outerIIFEBody": 0 }`:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]*/
@@ -261,8 +301,12 @@ console.log('foo');
}
```
+:::
+
Examples of **correct** code for this rule with the options `2, {"outerIIFEBody": 0}`:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]*/
@@ -279,10 +323,14 @@ if(y) {
}
```
+:::
+
### MemberExpression
Examples of **incorrect** code for this rule with the `2, { "MemberExpression": 1 }` options:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "MemberExpression": 1 }]*/
@@ -291,8 +339,12 @@ foo
.baz()
```
+:::
+
Examples of **correct** code for this rule with the `2, { "MemberExpression": 1 }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "MemberExpression": 1 }]*/
@@ -305,10 +357,14 @@ var bip = aardvark.badger
.coyote;
```
+:::
+
### FunctionDeclaration
Examples of **incorrect** code for this rule with the `2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]*/
@@ -319,8 +375,12 @@ function foo(bar,
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]*/
@@ -331,8 +391,12 @@ function foo(bar,
}
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "FunctionDeclaration": {"parameters": "first"} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]*/
@@ -342,8 +406,12 @@ function foo(bar, baz,
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "FunctionDeclaration": {"parameters": "first"} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]*/
@@ -353,10 +421,14 @@ function foo(bar, baz,
}
```
+:::
+
### FunctionExpression
Examples of **incorrect** code for this rule with the `2, { "FunctionExpression": {"body": 1, "parameters": 2} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]*/
@@ -367,8 +439,12 @@ var foo = function(bar,
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "FunctionExpression": {"body": 1, "parameters": 2} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]*/
@@ -379,8 +455,12 @@ var foo = function(bar,
}
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "FunctionExpression": {"parameters": "first"} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]*/
@@ -390,8 +470,12 @@ var foo = function(bar, baz,
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "FunctionExpression": {"parameters": "first"} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]*/
@@ -401,10 +485,14 @@ var foo = function(bar, baz,
}
```
+:::
+
### CallExpression
Examples of **incorrect** code for this rule with the `2, { "CallExpression": {"arguments": 1} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]*/
@@ -414,8 +502,12 @@ foo(bar,
);
```
+:::
+
Examples of **correct** code for this rule with the `2, { "CallExpression": {"arguments": 1} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]*/
@@ -425,8 +517,12 @@ foo(bar,
);
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "CallExpression": {"arguments": "first"} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]*/
@@ -434,8 +530,12 @@ foo(bar, baz,
baz, boop, beep);
```
+:::
+
Examples of **correct** code for this rule with the `2, { "CallExpression": {"arguments": "first"} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]*/
@@ -443,10 +543,14 @@ foo(bar, baz,
baz, boop, beep);
```
+:::
+
### ArrayExpression
Examples of **incorrect** code for this rule with the `2, { "ArrayExpression": 1 }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "ArrayExpression": 1 }]*/
@@ -457,8 +561,12 @@ baz,
];
```
+:::
+
Examples of **correct** code for this rule with the `2, { "ArrayExpression": 1 }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "ArrayExpression": 1 }]*/
@@ -469,8 +577,12 @@ var foo = [
];
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "ArrayExpression": "first" }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"ArrayExpression": "first"}]*/
@@ -480,8 +592,12 @@ var foo = [bar,
];
```
+:::
+
Examples of **correct** code for this rule with the `2, { "ArrayExpression": "first" }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"ArrayExpression": "first"}]*/
@@ -491,10 +607,14 @@ var foo = [bar,
];
```
+:::
+
### ObjectExpression
Examples of **incorrect** code for this rule with the `2, { "ObjectExpression": 1 }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "ObjectExpression": 1 }]*/
@@ -505,8 +625,12 @@ baz: 2,
};
```
+:::
+
Examples of **correct** code for this rule with the `2, { "ObjectExpression": 1 }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "ObjectExpression": 1 }]*/
@@ -517,8 +641,12 @@ var foo = {
};
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "ObjectExpression": "first" }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"ObjectExpression": "first"}]*/
@@ -526,8 +654,12 @@ var foo = { bar: 1,
baz: 2 };
```
+:::
+
Examples of **correct** code for this rule with the `2, { "ObjectExpression": "first" }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"ObjectExpression": "first"}]*/
@@ -535,6 +667,8 @@ var foo = { bar: 1,
baz: 2 };
```
+:::
+
## Compatibility
* **JSHint**: `indent`
diff --git a/docs/src/rules/indent.md b/docs/src/rules/indent.md
index 2b83a5d3d11..dbe4f9bbc3f 100644
--- a/docs/src/rules/indent.md
+++ b/docs/src/rules/indent.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/indent.md
rule_type: layout
---
-
-Enforces consistent indentation.
There are several common guidelines which require specific indentation of nested blocks and statements, like:
@@ -51,6 +49,8 @@ Or for tabbed indentation:
Examples of **incorrect** code for this rule with the default options:
+::: incorrect
+
```js
/*eslint indent: "error"*/
@@ -62,8 +62,12 @@ if (a) {
}
```
+:::
+
Examples of **correct** code for this rule with the default options:
+::: correct
+
```js
/*eslint indent: "error"*/
@@ -75,6 +79,8 @@ if (a) {
}
```
+:::
+
This rule has an object option:
* `"ignoredNodes"` can be used to disable indentation checking for any AST node. This accepts an array of [selectors](/docs/developer-guide/selectors). If an AST node is matched by any of the selectors, the indentation of tokens which are direct children of that node will be ignored. This can be used as an escape hatch to relax the rule if you disagree with the indentation that it enforces for a particular syntactic pattern.
@@ -120,6 +126,8 @@ Level of indentation denotes the multiple of the indent specified. Example:
Examples of **incorrect** code for this rule with the `"tab"` option:
+::: incorrect
+
```js
/*eslint indent: ["error", "tab"]*/
@@ -131,8 +139,12 @@ function foo(d) {
}
```
+:::
+
Examples of **correct** code for this rule with the `"tab"` option:
+::: correct
+
```js
/*eslint indent: ["error", "tab"]*/
@@ -144,12 +156,16 @@ if (a) {
}
```
+:::
+
### ignoredNodes
The following configuration ignores the indentation of `ConditionalExpression` ("ternary expression") nodes:
Examples of **correct** code for this rule with the `4, { "ignoredNodes": ["ConditionalExpression"] }` option:
+::: correct
+
```js
/*eslint indent: ["error", 4, { "ignoredNodes": ["ConditionalExpression"] }]*/
@@ -162,10 +178,14 @@ var a = foo
: baz;
```
+:::
+
The following configuration ignores indentation in the body of IIFEs.
Examples of **correct** code for this rule with the `4, { "ignoredNodes": ["CallExpression > FunctionExpression.callee > BlockStatement.body"] }` option:
+::: correct
+
```js
/*eslint indent: ["error", 4, { "ignoredNodes": ["CallExpression > FunctionExpression.callee > BlockStatement.body"] }]*/
@@ -177,12 +197,16 @@ bar();
})
```
+:::
+
All AST node types can be found at [ESTree](https://github.com/estree/estree) specification. You can use [AST Explorer](https://astexplorer.net/) with the espree parser to examine AST tree of a code snippet.
### SwitchCase
Examples of **incorrect** code for this rule with the `2, { "SwitchCase": 1 }` options:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/
@@ -194,8 +218,12 @@ case "b":
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "SwitchCase": 1 }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/
@@ -207,10 +235,14 @@ switch(a){
}
```
+:::
+
### VariableDeclarator
Examples of **incorrect** code for this rule with the `2, { "VariableDeclarator": 1 }` options:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]*/
/*eslint-env es6*/
@@ -226,8 +258,12 @@ const a = 1,
c = 3;
```
+:::
+
Examples of **correct** code for this rule with the `2, { "VariableDeclarator": 1 }` options:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]*/
/*eslint-env es6*/
@@ -243,8 +279,12 @@ const a = 1,
c = 3;
```
+:::
+
Examples of **correct** code for this rule with the `2, { "VariableDeclarator": 2 }` options:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": 2 }]*/
/*eslint-env es6*/
@@ -260,8 +300,12 @@ const a = 1,
c = 3;
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "VariableDeclarator": "first" }` options:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": "first" }]*/
/*eslint-env es6*/
@@ -277,8 +321,12 @@ const a = 1,
c = 3;
```
+:::
+
Examples of **correct** code for this rule with the `2, { "VariableDeclarator": "first" }` options:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": "first" }]*/
/*eslint-env es6*/
@@ -294,8 +342,12 @@ const a = 1,
c = 3;
```
+:::
+
Examples of **correct** code for this rule with the `2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }` options:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }]*/
/*eslint-env es6*/
@@ -311,10 +363,14 @@ const a = 1,
c = 3;
```
+:::
+
### outerIIFEBody
Examples of **incorrect** code for this rule with the options `2, { "outerIIFEBody": 0 }`:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]*/
@@ -331,8 +387,12 @@ console.log('foo');
}
```
+:::
+
Examples of **correct** code for this rule with the options `2, { "outerIIFEBody": 0 }`:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]*/
@@ -349,8 +409,12 @@ if (y) {
}
```
+:::
+
Examples of **correct** code for this rule with the options `2, { "outerIIFEBody": "off" }`:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "outerIIFEBody": "off" }]*/
@@ -375,10 +439,14 @@ if (y) {
}
```
+:::
+
### MemberExpression
Examples of **incorrect** code for this rule with the `2, { "MemberExpression": 1 }` options:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "MemberExpression": 1 }]*/
@@ -387,8 +455,12 @@ foo
.baz()
```
+:::
+
Examples of **correct** code for this rule with the `2, { "MemberExpression": 1 }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "MemberExpression": 1 }]*/
@@ -397,10 +469,14 @@ foo
.baz();
```
+:::
+
### FunctionDeclaration
Examples of **incorrect** code for this rule with the `2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]*/
@@ -411,8 +487,12 @@ function foo(bar,
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]*/
@@ -423,8 +503,12 @@ function foo(bar,
}
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "FunctionDeclaration": {"parameters": "first"} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]*/
@@ -434,8 +518,12 @@ function foo(bar, baz,
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "FunctionDeclaration": {"parameters": "first"} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]*/
@@ -445,10 +533,14 @@ function foo(bar, baz,
}
```
+:::
+
### FunctionExpression
Examples of **incorrect** code for this rule with the `2, { "FunctionExpression": {"body": 1, "parameters": 2} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]*/
@@ -459,8 +551,12 @@ var foo = function(bar,
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "FunctionExpression": {"body": 1, "parameters": 2} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]*/
@@ -471,8 +567,12 @@ var foo = function(bar,
}
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "FunctionExpression": {"parameters": "first"} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]*/
@@ -482,8 +582,12 @@ var foo = function(bar, baz,
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "FunctionExpression": {"parameters": "first"} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]*/
@@ -493,10 +597,14 @@ var foo = function(bar, baz,
}
```
+:::
+
### StaticBlock
Examples of **incorrect** code for this rule with the `2, { "StaticBlock": {"body": 1} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "StaticBlock": {"body": 1} }]*/
@@ -507,8 +615,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "StaticBlock": {"body": 1} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "StaticBlock": {"body": 1} }]*/
@@ -519,8 +631,12 @@ class C {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "StaticBlock": {"body": 2} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "StaticBlock": {"body": 2} }]*/
@@ -531,8 +647,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "StaticBlock": {"body": 2} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "StaticBlock": {"body": 2} }]*/
@@ -543,10 +663,14 @@ class C {
}
```
+:::
+
### CallExpression
Examples of **incorrect** code for this rule with the `2, { "CallExpression": {"arguments": 1} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]*/
@@ -556,8 +680,12 @@ foo(bar,
);
```
+:::
+
Examples of **correct** code for this rule with the `2, { "CallExpression": {"arguments": 1} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]*/
@@ -567,8 +695,12 @@ foo(bar,
);
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "CallExpression": {"arguments": "first"} }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]*/
@@ -576,8 +708,12 @@ foo(bar, baz,
baz, boop, beep);
```
+:::
+
Examples of **correct** code for this rule with the `2, { "CallExpression": {"arguments": "first"} }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]*/
@@ -585,10 +721,14 @@ foo(bar, baz,
baz, boop, beep);
```
+:::
+
### ArrayExpression
Examples of **incorrect** code for this rule with the `2, { "ArrayExpression": 1 }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "ArrayExpression": 1 }]*/
@@ -599,8 +739,12 @@ baz,
];
```
+:::
+
Examples of **correct** code for this rule with the `2, { "ArrayExpression": 1 }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "ArrayExpression": 1 }]*/
@@ -611,8 +755,12 @@ var foo = [
];
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "ArrayExpression": "first" }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"ArrayExpression": "first"}]*/
@@ -622,8 +770,12 @@ var foo = [bar,
];
```
+:::
+
Examples of **correct** code for this rule with the `2, { "ArrayExpression": "first" }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"ArrayExpression": "first"}]*/
@@ -633,10 +785,14 @@ var foo = [bar,
];
```
+:::
+
### ObjectExpression
Examples of **incorrect** code for this rule with the `2, { "ObjectExpression": 1 }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "ObjectExpression": 1 }]*/
@@ -647,8 +803,12 @@ baz: 2,
};
```
+:::
+
Examples of **correct** code for this rule with the `2, { "ObjectExpression": 1 }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "ObjectExpression": 1 }]*/
@@ -659,8 +819,12 @@ var foo = {
};
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "ObjectExpression": "first" }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, {"ObjectExpression": "first"}]*/
@@ -668,8 +832,12 @@ var foo = { bar: 1,
baz: 2 };
```
+:::
+
Examples of **correct** code for this rule with the `2, { "ObjectExpression": "first" }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, {"ObjectExpression": "first"}]*/
@@ -677,10 +845,14 @@ var foo = { bar: 1,
baz: 2 };
```
+:::
+
### ImportDeclaration
Examples of **correct** code for this rule with the `4, { "ImportDeclaration": 1 }` option (the default):
+::: correct
+
```js
/*eslint indent: ["error", 4, { "ImportDeclaration": 1 }]*/
@@ -696,8 +868,12 @@ import {
} from 'qux';
```
+:::
+
Examples of **incorrect** code for this rule with the `4, { "ImportDeclaration": "first" }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 4, { "ImportDeclaration": "first" }]*/
@@ -707,8 +883,12 @@ import { foo,
} from 'qux';
```
+:::
+
Examples of **correct** code for this rule with the `4, { "ImportDeclaration": "first" }` option:
+::: correct
+
```js
/*eslint indent: ["error", 4, { "ImportDeclaration": "first" }]*/
@@ -718,10 +898,14 @@ import { foo,
} from 'qux';
```
+:::
+
### flatTernaryExpressions
Examples of **incorrect** code for this rule with the default `4, { "flatTernaryExpressions": false }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 4, { "flatTernaryExpressions": false }]*/
@@ -731,8 +915,12 @@ var a =
boop;
```
+:::
+
Examples of **correct** code for this rule with the default `4, { "flatTernaryExpressions": false }` option:
+::: correct
+
```js
/*eslint indent: ["error", 4, { "flatTernaryExpressions": false }]*/
@@ -742,8 +930,12 @@ var a =
boop;
```
+:::
+
Examples of **incorrect** code for this rule with the `4, { "flatTernaryExpressions": true }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 4, { "flatTernaryExpressions": true }]*/
@@ -753,8 +945,12 @@ var a =
boop;
```
+:::
+
Examples of **correct** code for this rule with the `4, { "flatTernaryExpressions": true }` option:
+::: correct
+
```js
/*eslint indent: ["error", 4, { "flatTernaryExpressions": true }]*/
@@ -764,10 +960,14 @@ var a =
boop;
```
+:::
+
### offsetTernaryExpressions
Examples of **incorrect** code for this rule with the default `2, { "offsetTernaryExpressions": false }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "offsetTernaryExpressions": false }]*/
@@ -780,8 +980,12 @@ condition
}
```
+:::
+
Examples of **correct** code for this rule with the default `2, { "offsetTernaryExpressions": false }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "offsetTernaryExpressions": false }]*/
@@ -798,8 +1002,12 @@ condition
}
```
+:::
+
Examples of **incorrect** code for this rule with the `2, { "offsetTernaryExpressions": true }` option:
+::: incorrect
+
```js
/*eslint indent: ["error", 2, { "offsetTernaryExpressions": true }]*/
@@ -816,8 +1024,12 @@ condition
}
```
+:::
+
Examples of **correct** code for this rule with the `2, { "offsetTernaryExpressions": true }` option:
+::: correct
+
```js
/*eslint indent: ["error", 2, { "offsetTernaryExpressions": true }]*/
@@ -834,10 +1046,14 @@ condition
}
```
+:::
+
### ignoreComments
Examples of additional **correct** code for this rule with the `4, { "ignoreComments": true }` option:
+::: correct
+
```js
/*eslint indent: ["error", 4, { "ignoreComments": true }] */
@@ -849,6 +1065,8 @@ if (foo) {
}
```
+:::
+
## Compatibility
* **JSHint**: `indent`
diff --git a/docs/src/rules/init-declarations.md b/docs/src/rules/init-declarations.md
index c5d5c88be34..d5ccaef69aa 100644
--- a/docs/src/rules/init-declarations.md
+++ b/docs/src/rules/init-declarations.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/init-declar
rule_type: suggestion
---
-Requires or disallows initialization in variable declarations.
In JavaScript, variables can be assigned during declaration, or at any point afterwards using an assignment statement. For example, in the following code, `foo` is initialized during declaration, while `bar` is initialized later.
@@ -70,6 +69,8 @@ Variables must not be initialized at declaration, except in for loops, where it
Examples of **incorrect** code for the default `"always"` option:
+::: incorrect
+
```js
/*eslint init-declarations: ["error", "always"]*/
/*eslint-env es6*/
@@ -80,8 +81,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for the default `"always"` option:
+::: correct
+
```js
/*eslint init-declarations: ["error", "always"]*/
/*eslint-env es6*/
@@ -93,10 +98,14 @@ function foo() {
}
```
+:::
+
### never
Examples of **incorrect** code for the `"never"` option:
+::: incorrect
+
```js
/*eslint init-declarations: ["error", "never"]*/
/*eslint-env es6*/
@@ -109,8 +118,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for the `"never"` option:
+::: correct
+
```js
/*eslint init-declarations: ["error", "never"]*/
/*eslint-env es6*/
@@ -122,17 +135,23 @@ function foo() {
}
```
+:::
+
The `"never"` option ignores `const` variable initializations.
### ignoreForLoopInit
Examples of **correct** code for the `"never", { "ignoreForLoopInit": true }` options:
+::: correct
+
```js
/*eslint init-declarations: ["error", "never", { "ignoreForLoopInit": true }]*/
for (var i = 0; i < 1; i++) {}
```
+:::
+
## When Not To Use It
When you are indifferent as to how your variables are initialized.
diff --git a/docs/src/rules/jsx-quotes.md b/docs/src/rules/jsx-quotes.md
index 14d0aa533dc..5196e66790d 100644
--- a/docs/src/rules/jsx-quotes.md
+++ b/docs/src/rules/jsx-quotes.md
@@ -7,9 +7,7 @@ related_rules:
- quotes
---
-
-Enforces the consistent use of either double or single quotes in JSX attributes.
JSX attribute values can contain string literals, which are delimited with single or double quotes.
@@ -41,14 +39,20 @@ This rule has a string option:
Examples of **incorrect** code for this rule with the default `"prefer-double"` option:
+:::incorrect
+
```xml
/*eslint jsx-quotes: ["error", "prefer-double"]*/
```
+:::
+
Examples of **correct** code for this rule with the default `"prefer-double"` option:
+:::correct
+
```xml
/*eslint jsx-quotes: ["error", "prefer-double"]*/
@@ -56,18 +60,26 @@ Examples of **correct** code for this rule with the default `"prefer-double"` op
```
+:::
+
### prefer-single
Examples of **incorrect** code for this rule with the `"prefer-single"` option:
+:::incorrect
+
```xml
/*eslint jsx-quotes: ["error", "prefer-single"]*/
```
+:::
+
Examples of **correct** code for this rule with the `"prefer-single"` option:
+:::correct
+
```xml
/*eslint jsx-quotes: ["error", "prefer-single"]*/
@@ -75,6 +87,8 @@ Examples of **correct** code for this rule with the `"prefer-single"` option:
```
+:::
+
## When Not To Use It
You can turn this rule off if you don’t use JSX or if you aren’t concerned with a consistent usage of quotes within JSX attributes.
diff --git a/docs/src/rules/key-spacing.md b/docs/src/rules/key-spacing.md
index 59de8f0a296..1810ab1739e 100644
--- a/docs/src/rules/key-spacing.md
+++ b/docs/src/rules/key-spacing.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/key-spacing
rule_type: layout
---
-
-Enforces consistent spacing between keys and values in object literal properties.
This rule enforces spacing around the colon in object literal properties. It can verify each property individually, or it can ensure horizontal alignment of adjacent properties in an object literal.
@@ -41,74 +39,108 @@ Please note that you can either use the top-level options or the grouped options
Examples of **incorrect** code for this rule with the default `{ "beforeColon": false }` option:
+::: incorrect
+
```js
/*eslint key-spacing: ["error", { "beforeColon": false }]*/
var obj = { "foo" : 42 };
```
+:::
+
Examples of **correct** code for this rule with the default `{ "beforeColon": false }` option:
+::: correct
+
```js
/*eslint key-spacing: ["error", { "beforeColon": false }]*/
var obj = { "foo": 42 };
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "beforeColon": true }` option:
+::: incorrect
+
```js
/*eslint key-spacing: ["error", { "beforeColon": true }]*/
var obj = { "foo": 42 };
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeColon": true }` option:
+::: correct
+
```js
/*eslint key-spacing: ["error", { "beforeColon": true }]*/
var obj = { "foo" : 42 };
```
+:::
+
### afterColon
Examples of **incorrect** code for this rule with the default `{ "afterColon": true }` option:
+::: incorrect
+
```js
/*eslint key-spacing: ["error", { "afterColon": true }]*/
var obj = { "foo":42 };
```
+:::
+
Examples of **correct** code for this rule with the default `{ "afterColon": true }` option:
+::: correct
+
```js
/*eslint key-spacing: ["error", { "afterColon": true }]*/
var obj = { "foo": 42 };
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "afterColon": false }` option:
+::: incorrect
+
```js
/*eslint key-spacing: ["error", { "afterColon": false }]*/
var obj = { "foo": 42 };
```
+:::
+
Examples of **correct** code for this rule with the `{ "afterColon": false }` option:
+::: correct
+
```js
/*eslint key-spacing: ["error", { "afterColon": false }]*/
var obj = { "foo":42 };
```
+:::
+
### mode
Examples of **incorrect** code for this rule with the default `{ "mode": "strict" }` option:
+::: incorrect
+
```js
/*eslint key-spacing: ["error", { "mode": "strict" }]*/
@@ -118,8 +150,12 @@ call({
});
```
+:::
+
Examples of **correct** code for this rule with the default `{ "mode": "strict" }` option:
+::: correct
+
```js
/*eslint key-spacing: ["error", { "mode": "strict" }]*/
@@ -129,8 +165,12 @@ call({
});
```
+:::
+
Examples of **correct** code for this rule with the `{ "mode": "minimum" }` option:
+::: correct
+
```js
/*eslint key-spacing: ["error", { "mode": "minimum" }]*/
@@ -140,10 +180,14 @@ call({
});
```
+:::
+
### align
Examples of **incorrect** code for this rule with the `{ "align": "value" }` option:
+::: incorrect
+
```js
/*eslint key-spacing: ["error", { "align": "value" }]*/
@@ -154,8 +198,12 @@ var obj = {
};
```
+:::
+
Examples of **correct** code for this rule with the `{ "align": "value" }` option:
+::: correct
+
```js
/*eslint key-spacing: ["error", { "align": "value" }]*/
@@ -173,8 +221,12 @@ var obj = {
var obj = { a: "foo", longPropertyName: "bar" };
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "align": "colon" }` option:
+::: incorrect
+
```js
/*eslint key-spacing: ["error", { "align": "colon" }]*/
@@ -184,8 +236,12 @@ call({
});
```
+:::
+
Examples of **correct** code for this rule with the `{ "align": "colon" }` option:
+::: correct
+
```js
/*eslint key-spacing: ["error", { "align": "colon" }]*/
@@ -195,6 +251,8 @@ call({
});
```
+:::
+
### align
The `align` option can take additional configuration through the `beforeColon`, `afterColon`, `mode`, and `on` options.
@@ -213,6 +271,8 @@ align: {
Examples of **correct** code for this rule with sample `{ "align": { } }` options:
+::: correct
+
```js
/*eslint key-spacing: ["error", {
"align": {
@@ -228,6 +288,10 @@ var obj = {
}
```
+:::
+
+::: correct
+
```js
/*eslint key-spacing: ["error", {
"align": {
@@ -243,6 +307,8 @@ var obj = {
}
```
+:::
+
### align and multiLine
The `multiLine` and `align` options can differ, which allows for fine-tuned control over the `key-spacing` of your files. `align` will **not** inherit from `multiLine` if `align` is configured as an object.
@@ -263,6 +329,8 @@ var myObj = {
Examples of **incorrect** code for this rule with sample `{ "align": { }, "multiLine": { } }` options:
+::: incorrect
+
```js
/*eslint key-spacing: ["error", {
"multiLine": {
@@ -285,8 +353,12 @@ var obj = {
}
```
+:::
+
Examples of **correct** code for this rule with sample `{ "align": { }, "multiLine": { } }` options:
+::: correct
+
```js
/*eslint key-spacing: ["error", {
"multiLine": {
@@ -305,16 +377,20 @@ var obj = {
"myObjectFunction": function() {
// Do something
//
- }, // These are two separate groups, so no alignment between `myObjectFuction` and `one`
+ }, // These are two separate groups, so no alignment between `myObjectFunction` and `one`
"one" : 1,
"seven" : 7 // `one` and `seven` are in their own group, and therefore aligned
}
```
+:::
+
### singleLine and multiLine
Examples of **correct** code for this rule with sample `{ "singleLine": { }, "multiLine": { } }` options:
+::: correct
+
```js
/*eslint "key-spacing": [2, {
"singleLine": {
@@ -334,6 +410,8 @@ var obj2 = {
};
```
+:::
+
## When Not To Use It
If you have another convention for property spacing that might not be consistent with the available options, or if you want to permit multiple styles concurrently you can safely disable this rule.
diff --git a/docs/src/rules/keyword-spacing.md b/docs/src/rules/keyword-spacing.md
index d48990c31e6..e90244cd618 100644
--- a/docs/src/rules/keyword-spacing.md
+++ b/docs/src/rules/keyword-spacing.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/keyword-spa
rule_type: layout
---
-
-Enforces consistent spacing before and after keywords.
Keywords are syntax elements of JavaScript, such as `try` and `if`.
These keywords have special meaning to the language and so often appear in a different color in code editors.
@@ -44,6 +42,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "before": true }` option:
+::: incorrect
+
```js
/*eslint keyword-spacing: ["error", { "before": true }]*/
@@ -56,8 +56,12 @@ if (foo) {
}
```
+:::
+
Examples of **correct** code for this rule with the default `{ "before": true }` option:
+::: correct
+
```js
/*eslint keyword-spacing: ["error", { "before": true }]*/
/*eslint-env es6*/
@@ -111,8 +115,12 @@ if (10+this.foo<= this.bar) {}
let a =
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "before": false }` option:
+::: incorrect
+
```js
/*eslint keyword-spacing: ["error", { "before": false }]*/
@@ -125,8 +133,12 @@ if (foo) {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "before": false }` option:
+::: correct
+
```js
/*eslint keyword-spacing: ["error", { "before": false }]*/
@@ -139,10 +151,14 @@ if (foo) {
}
```
+:::
+
### after
Examples of **incorrect** code for this rule with the default `{ "after": true }` option:
+::: incorrect
+
```js
/*eslint keyword-spacing: ["error", { "after": true }]*/
@@ -155,8 +171,12 @@ if(foo) {
}
```
+:::
+
Examples of **correct** code for this rule with the default `{ "after": true }` option:
+::: correct
+
```js
/*eslint keyword-spacing: ["error", { "after": true }]*/
@@ -222,8 +242,12 @@ function* foo(a) {
let a =
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "after": false }` option:
+::: incorrect
+
```js
/*eslint keyword-spacing: ["error", { "after": false }]*/
@@ -236,8 +260,12 @@ if (foo) {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "after": false }` option:
+::: correct
+
```js
/*eslint keyword-spacing: ["error", { "after": false }]*/
@@ -250,10 +278,14 @@ if(foo) {
}
```
+:::
+
### overrides
Examples of **correct** code for this rule with the `{ "overrides": { "if": { "after": false }, "for": { "after": false }, "while": { "after": false }, "static": { "after": false }, "as": { "after": false } } }` option:
+::: correct
+
```js
/*eslint keyword-spacing: ["error", { "overrides": {
"if": { "after": false },
@@ -286,6 +318,8 @@ class C {
export { C as"my class" };
```
+:::
+
## When Not To Use It
If you don't want to enforce consistency on keyword spacing, then it's safe to disable this rule.
diff --git a/docs/src/rules/line-comment-position.md b/docs/src/rules/line-comment-position.md
index 7c033e398b5..a49fd00ae5a 100644
--- a/docs/src/rules/line-comment-position.md
+++ b/docs/src/rules/line-comment-position.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/line-commen
rule_type: layout
---
-Enforces position of line comments.
Line comments can be positioned above or beside code. This rule helps teams maintain a consistent style.
@@ -33,72 +32,104 @@ The `position` option has two settings:
Examples of **correct** code for the `{ "position": "above" }` option:
+::: correct
+
```js
/*eslint line-comment-position: ["error", { "position": "above" }]*/
// valid comment
1 + 1;
```
+:::
+
Examples of **incorrect** code for the `{ "position": "above" }` option:
+::: incorrect
+
```js
/*eslint line-comment-position: ["error", { "position": "above" }]*/
1 + 1; // invalid comment
```
+:::
+
#### position: beside
Examples of **correct** code for the `{ "position": "beside" }` option:
+::: correct
+
```js
/*eslint line-comment-position: ["error", { "position": "beside" }]*/
1 + 1; // valid comment
```
+:::
+
Examples of **incorrect** code for the `{ "position": "beside" }` option:
+::: incorrect
+
```js
/*eslint line-comment-position: ["error", { "position": "beside" }]*/
// invalid comment
1 + 1;
```
+:::
+
### ignorePattern
By default this rule ignores comments starting with the following words: `eslint`, `jshint`, `jslint`, `istanbul`, `global`, `exported`, `jscs`, `falls through`. An alternative regular expression can be provided.
Examples of **correct** code for the `ignorePattern` option:
+::: correct
+
```js
/*eslint line-comment-position: ["error", { "ignorePattern": "pragma" }]*/
1 + 1; // pragma valid comment
```
+:::
+
Examples of **incorrect** code for the `ignorePattern` option:
+::: incorrect
+
```js
/*eslint line-comment-position: ["error", { "ignorePattern": "pragma" }]*/
1 + 1; // invalid comment
```
+:::
+
### applyDefaultIgnorePatterns
Default ignore patterns are applied even when `ignorePattern` is provided. If you want to omit default patterns, set this option to `false`.
Examples of **correct** code for the `{ "applyDefaultIgnorePatterns": false }` option:
+::: correct
+
```js
/*eslint line-comment-position: ["error", { "ignorePattern": "pragma", "applyDefaultIgnorePatterns": false }]*/
1 + 1; // pragma valid comment
```
+:::
+
Examples of **incorrect** code for the `{ "applyDefaultIgnorePatterns": false }` option:
+::: incorrect
+
```js
/*eslint line-comment-position: ["error", { "ignorePattern": "pragma", "applyDefaultIgnorePatterns": false }]*/
1 + 1; // falls through
```
+:::
+
**Deprecated:** the object property `applyDefaultPatterns` is deprecated. Please use the property `applyDefaultIgnorePatterns` instead.
## When Not To Use It
diff --git a/docs/src/rules/linebreak-style.md b/docs/src/rules/linebreak-style.md
index c1a8a0a83dd..ef3c071a079 100644
--- a/docs/src/rules/linebreak-style.md
+++ b/docs/src/rules/linebreak-style.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/linebreak-s
rule_type: layout
---
-
-Enforces consistent linebreak style.
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that
different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
@@ -32,6 +30,8 @@ This rule has a string option:
Examples of **incorrect** code for this rule with the default `"unix"` option:
+::: incorrect
+
```js
/*eslint linebreak-style: ["error", "unix"]*/
@@ -39,8 +39,12 @@ var a = 'a'; // \r\n
```
+:::
+
Examples of **correct** code for this rule with the default `"unix"` option:
+::: correct
+
```js
/*eslint linebreak-style: ["error", "unix"]*/
@@ -52,18 +56,26 @@ function foo(params) { // \n
}// \n
```
+:::
+
### windows
Examples of **incorrect** code for this rule with the `"windows"` option:
+::: incorrect
+
```js
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a'; // \n
```
+:::
+
Examples of **correct** code for this rule with the `"windows"` option:
+::: correct
+
```js
/*eslint linebreak-style: ["error", "windows"]*/
@@ -75,6 +87,8 @@ function foo(params) { // \r\n
} // \r\n
```
+:::
+
### Using this rule with version control systems
Version control systems sometimes have special behavior for linebreaks. To make it easy for developers to contribute to your codebase from different platforms, you may want to configure your VCS to handle linebreaks appropriately.
diff --git a/docs/src/rules/lines-around-comment.md b/docs/src/rules/lines-around-comment.md
index 100cd2daf2c..44051246faa 100644
--- a/docs/src/rules/lines-around-comment.md
+++ b/docs/src/rules/lines-around-comment.md
@@ -8,9 +8,7 @@ related_rules:
- spaced-comment
---
-
-Requires empty lines around comments.
Many style guides require empty lines before or after comments. The primary goal
of these rules is to make the comments easier to read and improve readability of the code.
@@ -27,8 +25,8 @@ This rule has an object option:
* `"afterBlockComment": true` requires an empty line after block comments
* `"beforeLineComment": true` requires an empty line before line comments
* `"afterLineComment": true` requires an empty line after line comments
-* `"allowBlockStart": true` allows comments to appear at the start of block statements, function bodies, classes, and class static blocks
-* `"allowBlockEnd": true` allows comments to appear at the end of block statements, function bodies, classes, and class static blocks
+* `"allowBlockStart": true` allows comments to appear at the start of block statements, function bodies, classes, switch statements, and class static blocks
+* `"allowBlockEnd": true` allows comments to appear at the end of block statements, function bodies, classes, switch statements, and class static blocks
* `"allowObjectStart": true` allows comments to appear at the start of object literals
* `"allowObjectEnd": true` allows comments to appear at the end of object literals
* `"allowArrayStart": true` allows comments to appear at the start of array literals
@@ -42,6 +40,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "beforeBlockComment": true }` option:
+::: incorrect
+
```js
/*eslint lines-around-comment: ["error", { "beforeBlockComment": true }]*/
@@ -50,8 +50,12 @@ var night = "long";
var day = "great"
```
+:::
+
Examples of **correct** code for this rule with the default `{ "beforeBlockComment": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeBlockComment": true }]*/
@@ -61,10 +65,14 @@ var night = "long";
var day = "great"
```
+:::
+
### afterBlockComment
Examples of **incorrect** code for this rule with the `{ "afterBlockComment": true }` option:
+::: incorrect
+
```js
/*eslint lines-around-comment: ["error", { "afterBlockComment": true }]*/
@@ -74,8 +82,12 @@ var night = "long";
var day = "great"
```
+:::
+
Examples of **correct** code for this rule with the `{ "afterBlockComment": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterBlockComment": true }]*/
@@ -86,10 +98,14 @@ var night = "long";
var day = "great"
```
+:::
+
### beforeLineComment
Examples of **incorrect** code for this rule with the `{ "beforeLineComment": true }` option:
+::: incorrect
+
```js
/*eslint lines-around-comment: ["error", { "beforeLineComment": true }]*/
@@ -98,8 +114,12 @@ var night = "long";
var day = "great"
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeLineComment": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeLineComment": true }]*/
@@ -109,10 +129,14 @@ var night = "long";
var day = "great"
```
+:::
+
### afterLineComment
Examples of **incorrect** code for this rule with the `{ "afterLineComment": true }` option:
+::: incorrect
+
```js
/*eslint lines-around-comment: ["error", { "afterLineComment": true }]*/
@@ -121,8 +145,12 @@ var night = "long";
var day = "great"
```
+:::
+
Examples of **correct** code for this rule with the `{ "afterLineComment": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterLineComment": true }]*/
@@ -132,10 +160,14 @@ var night = "long";
var day = "great"
```
+:::
+
### allowBlockStart
Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowBlockStart": true }` options:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowBlockStart": true }]*/
@@ -165,8 +197,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowBlockStart": true }` options:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowBlockStart": true }]*/
@@ -194,12 +230,24 @@ class C {
foo();
}
}
+
+switch (foo) {
+ /* what a great and wonderful day */
+
+ case 1:
+ bar();
+ break;
+}
```
+:::
+
### allowBlockEnd
Examples of **correct** code for this rule with the `{ "afterLineComment": true, "allowBlockEnd": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterLineComment": true, "allowBlockEnd": true }]*/
@@ -230,8 +278,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "afterBlockComment": true, "allowBlockEnd": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterBlockComment": true, "allowBlockEnd": true }]*/
@@ -264,12 +316,24 @@ class C {
/* what a great and wonderful day */
}
+
+switch (foo) {
+ case 1:
+ bar();
+ break;
+
+ /* what a great and wonderful day */
+}
```
+:::
+
### allowClassStart
Examples of **incorrect** code for this rule with the `{ "beforeLineComment": true, "allowClassStart": false }` option:
+::: incorrect
+
```js
/*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowClassStart": false }]*/
@@ -279,8 +343,12 @@ class foo {
};
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowClassStart": false }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowClassStart": false }]*/
@@ -291,8 +359,12 @@ class foo {
};
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowClassStart": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowClassStart": true }]*/
@@ -302,8 +374,12 @@ class foo {
};
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "beforeBlockComment": true, "allowClassStart": false }` option:
+::: incorrect
+
```js
/*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowClassStart": false }]*/
@@ -313,8 +389,12 @@ class foo {
};
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowClassStart": false }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowClassStart": false }]*/
@@ -325,8 +405,12 @@ class foo {
};
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowClassStart": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowClassStart": true }]*/
@@ -336,10 +420,14 @@ class foo {
};
```
+:::
+
### allowClassEnd
Examples of **correct** code for this rule with the `{ "afterLineComment": true, "allowClassEnd": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterLineComment": true, "allowClassEnd": true }]*/
@@ -349,8 +437,12 @@ class foo {
};
```
+:::
+
Examples of **correct** code for this rule with the `{ "afterBlockComment": true, "allowClassEnd": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterBlockComment": true, "allowClassEnd": true }]*/
@@ -361,10 +453,14 @@ class foo {
};
```
+:::
+
### allowObjectStart
Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowObjectStart": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowObjectStart": true }]*/
@@ -384,8 +480,12 @@ const {
} = {day: "great"};
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowObjectStart": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowObjectStart": true }]*/
@@ -405,10 +505,14 @@ const {
} = {day: "great"};
```
+:::
+
### allowObjectEnd
Examples of **correct** code for this rule with the `{ "afterLineComment": true, "allowObjectEnd": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterLineComment": true, "allowObjectEnd": true }]*/
@@ -428,8 +532,12 @@ const {
} = {day: "great"};
```
+:::
+
Examples of **correct** code for this rule with the `{ "afterBlockComment": true, "allowObjectEnd": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterBlockComment": true, "allowObjectEnd": true }]*/
@@ -452,10 +560,14 @@ const {
} = {day: "great"};
```
+:::
+
### allowArrayStart
Examples of **correct** code for this rule with the `{ "beforeLineComment": true, "allowArrayStart": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowArrayStart": true }]*/
@@ -471,8 +583,12 @@ const [
] = ["great", "not great"];
```
+:::
+
Examples of **correct** code for this rule with the `{ "beforeBlockComment": true, "allowArrayStart": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowArrayStart": true }]*/
@@ -488,10 +604,14 @@ const [
] = ["great", "not great"];
```
+:::
+
### allowArrayEnd
Examples of **correct** code for this rule with the `{ "afterLineComment": true, "allowArrayEnd": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterLineComment": true, "allowArrayEnd": true }]*/
@@ -507,8 +627,12 @@ const [
] = ["great", "not great"];
```
+:::
+
Examples of **correct** code for this rule with the `{ "afterBlockComment": true, "allowArrayEnd": true }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "afterBlockComment": true, "allowArrayEnd": true }]*/
@@ -526,12 +650,16 @@ const [
] = ["great", "not great"];
```
+:::
+
### ignorePattern
By default this rule ignores comments starting with the following words: `eslint`, `jshint`, `jslint`, `istanbul`, `global`, `exported`, `jscs`. To ignore more comments in addition to the defaults, set the `ignorePattern` option to a string pattern that will be passed to the [`RegExp` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp).
Examples of **correct** code for the `ignorePattern` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error"]*/
@@ -545,8 +673,12 @@ foo();
/* a valid comment using pragma in it */
```
+:::
+
Examples of **incorrect** code for the `ignorePattern` option:
+::: incorrect
+
```js
/*eslint lines-around-comment: ["error", { "ignorePattern": "pragma" }] */
@@ -554,12 +686,16 @@ Examples of **incorrect** code for the `ignorePattern` option:
/* something else */
```
+:::
+
### applyDefaultIgnorePatterns
Default ignore patterns are applied even when `ignorePattern` is provided. If you want to omit default patterns, set this option to `false`.
Examples of **correct** code for the `{ "applyDefaultIgnorePatterns": false }` option:
+::: correct
+
```js
/*eslint lines-around-comment: ["error", { "ignorePattern": "pragma", applyDefaultIgnorePatterns: false }] */
@@ -567,8 +703,12 @@ foo();
/* a valid comment using pragma in it */
```
+:::
+
Examples of **incorrect** code for the `{ "applyDefaultIgnorePatterns": false }` option:
+::: incorrect
+
```js
/*eslint lines-around-comment: ["error", { "applyDefaultIgnorePatterns": false }] */
@@ -577,6 +717,8 @@ foo();
```
+:::
+
## When Not To Use It
Many people enjoy a terser code style and don't mind comments bumping up against code. If you fall into that category this rule is not for you.
diff --git a/docs/src/rules/lines-around-directive.md b/docs/src/rules/lines-around-directive.md
index 6c31f436885..d3697545668 100644
--- a/docs/src/rules/lines-around-directive.md
+++ b/docs/src/rules/lines-around-directive.md
@@ -8,9 +8,7 @@ related_rules:
- padded-blocks
---
-
-Requires or disallow newlines around directives.
This rule was **deprecated** in ESLint v4.0.0 and replaced by the [padding-line-between-statements](padding-line-between-statements) rule.
@@ -64,6 +62,8 @@ This is the default option.
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/* eslint lines-around-directive: ["error", "always"] */
@@ -90,8 +90,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/* eslint lines-around-directive: ["error", "always"] */
@@ -124,10 +128,14 @@ function foo() {
}
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/* eslint lines-around-directive: ["error", "never"] */
@@ -161,8 +169,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/* eslint lines-around-directive: ["error", "never"] */
@@ -189,10 +201,14 @@ function foo() {
}
```
+:::
+
### before & after
Examples of **incorrect** code for this rule with the `{ "before": "never", "after": "always" }` option:
+::: incorrect
+
```js
/* eslint lines-around-directive: ["error", { "before": "never", "after": "always" }] */
@@ -222,8 +238,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "before": "never", "after": "always" }` option:
+::: correct
+
```js
/* eslint lines-around-directive: ["error", { "before": "never", "after": "always" }] */
@@ -254,8 +274,12 @@ function foo() {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "before": "always", "after": "never" }` option:
+::: incorrect
+
```js
/* eslint lines-around-directive: ["error", { "before": "always", "after": "never" }] */
@@ -286,8 +310,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "before": "always", "after": "never" }` option:
+::: correct
+
```js
/* eslint lines-around-directive: ["error", { "before": "always", "after": "never" }] */
@@ -316,6 +344,8 @@ function foo() {
}
```
+:::
+
## When Not To Use It
You can safely disable this rule if you do not have any strict conventions about whether or not directive prologues should have blank newlines before or after them.
diff --git a/docs/src/rules/lines-between-class-members.md b/docs/src/rules/lines-between-class-members.md
index 0a798eb6af6..42ebf9d2a83 100644
--- a/docs/src/rules/lines-between-class-members.md
+++ b/docs/src/rules/lines-between-class-members.md
@@ -8,9 +8,7 @@ related_rules:
- padding-line-between-statements
---
-
-Requires or disallows an empty line between class members.
This rule improves readability by enforcing lines between class members. It will not check empty lines before the first member and after the last member, since that is already taken care of by padded-blocks.
@@ -18,6 +16,8 @@ This rule improves readability by enforcing lines between class members. It will
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/* eslint lines-between-class-members: ["error", "always"]*/
class MyClass {
@@ -31,8 +31,12 @@ class MyClass {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/* eslint lines-between-class-members: ["error", "always"]*/
class MyClass {
@@ -48,8 +52,12 @@ class MyClass {
}
```
+:::
+
Examples of additional **correct** code for this rule:
+::: correct
+
```js
/* eslint lines-between-class-members: ["error", "always"]*/
class MyClass {
@@ -59,6 +67,8 @@ class MyClass {
}
```
+:::
+
### Options
This rule has a string option and an object option.
@@ -75,6 +85,8 @@ Object option:
Examples of **incorrect** code for this rule with the string option:
+::: incorrect
+
```js
/* eslint lines-between-class-members: ["error", "always"]*/
class Foo{
@@ -93,8 +105,12 @@ class Foo{
}
```
+:::
+
Examples of **correct** code for this rule with the string option:
+::: correct
+
```js
/* eslint lines-between-class-members: ["error", "always"]*/
class Foo{
@@ -113,8 +129,12 @@ class Foo{
}
```
+:::
+
Examples of **correct** code for this rule with the object option:
+::: correct
+
```js
/* eslint lines-between-class-members: ["error", "always", { "exceptAfterSingleLine": true }]*/
class Foo{
@@ -128,6 +148,8 @@ class Foo{
}
```
+:::
+
## When Not To Use It
If you don't want to enforce empty lines between class members, you can disable this rule.
diff --git a/docs/src/rules/max-classes-per-file.md b/docs/src/rules/max-classes-per-file.md
index 5752d540ae9..ef02619fe5b 100644
--- a/docs/src/rules/max-classes-per-file.md
+++ b/docs/src/rules/max-classes-per-file.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/max-classes
rule_type: suggestion
---
-Enforces a maximum number of classes per file.
Files containing multiple classes can often result in a less navigable
and poorly structured codebase. Best practice is to keep each file
@@ -18,6 +17,8 @@ of classes and no more.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint max-classes-per-file: "error"*/
@@ -25,14 +26,20 @@ class Foo {}
class Bar {}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint max-classes-per-file: "error"*/
class Foo {}
```
+:::
+
## Options
This rule may be configured with either an object or a number.
@@ -61,6 +68,8 @@ For example:
Examples of **correct** code for this rule with the `max` option set to `2`:
+::: correct
+
```js
/* eslint max-classes-per-file: ["error", 2] */
@@ -68,8 +77,12 @@ class Foo {}
class Bar {}
```
+:::
+
Examples of **correct** code for this rule with the `ignoreExpressions` option set to `true`:
+::: correct
+
```js
/* eslint max-classes-per-file: ["error", { ignoreExpressions: true }] */
@@ -83,3 +96,5 @@ class VisitorFactory {
}
}
```
+
+:::
diff --git a/docs/src/rules/max-depth.md b/docs/src/rules/max-depth.md
index 0263e343a87..1a31c279a38 100644
--- a/docs/src/rules/max-depth.md
+++ b/docs/src/rules/max-depth.md
@@ -13,7 +13,6 @@ related_rules:
- max-statements
---
-Enforces a maximum depth that blocks can be nested.
Many developers consider code difficult to read if blocks are nested beyond a certain depth.
@@ -33,6 +32,8 @@ This rule has a number or object option:
Examples of **incorrect** code for this rule with the default `{ "max": 4 }` option:
+::: incorrect
+
```js
/*eslint max-depth: ["error", 4]*/
@@ -50,8 +51,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the default `{ "max": 4 }` option:
+::: correct
+
```js
/*eslint max-depth: ["error", 4]*/
@@ -67,10 +72,14 @@ function foo() {
}
```
+:::
+
Note that class static blocks do not count as nested blocks, and that the depth in them is calculated separately from the enclosing context.
Examples of **incorrect** code for this rule with `{ "max": 2 }` option:
+::: incorrect
+
```js
/*eslint max-depth: ["error", 2]*/
@@ -90,8 +99,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with `{ "max": 2 }` option:
+::: correct
+
```js
/*eslint max-depth: ["error", 2]*/
@@ -108,3 +121,5 @@ function foo() {
}
}
```
+
+:::
diff --git a/docs/src/rules/max-len.md b/docs/src/rules/max-len.md
index a52cefbba70..216b48d80ac 100644
--- a/docs/src/rules/max-len.md
+++ b/docs/src/rules/max-len.md
@@ -11,7 +11,6 @@ related_rules:
- max-statements
---
-Enforces a maximum line length.
Very long lines of code in any language can be difficult to read. In order to aid in readability and maintainability many coders have developed a convention to limit lines of code to X number of characters (traditionally 80 characters).
@@ -42,14 +41,20 @@ This rule has a number or object option:
Examples of **incorrect** code for this rule with the default `{ "code": 80 }` option:
+::: incorrect
+
```js
/*eslint max-len: ["error", { "code": 80 }]*/
var foo = { "bar": "This is a bar.", "baz": { "qux": "This is a qux" }, "difficult": "to read" };
```
+:::
+
Examples of **correct** code for this rule with the default `{ "code": 80 }` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "code": 80 }]*/
@@ -60,18 +65,26 @@ var foo = {
};
```
+:::
+
### tabWidth
Examples of **incorrect** code for this rule with the default `{ "tabWidth": 4 }` option:
+::: incorrect
+
```js
/*eslint max-len: ["error", { "code": 80, "tabWidth": 4 }]*/
\t \t var foo = { "bar": "This is a bar.", "baz": { "qux": "This is a qux" } };
```
+:::
+
Examples of **correct** code for this rule with the default `{ "tabWidth": 4 }` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "code": 80, "tabWidth": 4 }]*/
@@ -81,10 +94,14 @@ Examples of **correct** code for this rule with the default `{ "tabWidth": 4 }`
\t \t };
```
+:::
+
### comments
Examples of **incorrect** code for this rule with the `{ "comments": 65 }` option:
+::: incorrect
+
```js
/*eslint max-len: ["error", { "comments": 65 }]*/
@@ -93,10 +110,14 @@ Examples of **incorrect** code for this rule with the `{ "comments": 65 }` optio
**/
```
+:::
+
### ignoreComments
Examples of **correct** code for this rule with the `{ "ignoreComments": true }` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "ignoreComments": true }]*/
@@ -105,62 +126,88 @@ Examples of **correct** code for this rule with the `{ "ignoreComments": true }`
**/
```
+:::
+
### ignoreTrailingComments
Examples of **correct** code for this rule with the `{ "ignoreTrailingComments": true }` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "ignoreTrailingComments": true }]*/
var foo = 'bar'; // This is a really really really really really really really long comment
```
+:::
+
### ignoreUrls
Examples of **correct** code for this rule with the `{ "ignoreUrls": true }` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "ignoreUrls": true }]*/
var url = 'https://www.example.com/really/really/really/really/really/really/really/long';
```
+:::
+
### ignoreStrings
Examples of **correct** code for this rule with the `{ "ignoreStrings": true }` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "ignoreStrings": true }]*/
var longString = 'this is a really really really really really long string!';
```
+:::
+
### ignoreTemplateLiterals
Examples of **correct** code for this rule with the `{ "ignoreTemplateLiterals": true }` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "ignoreTemplateLiterals": true }]*/
var longTemplateLiteral = `this is a really really really really really long template literal!`;
```
+:::
+
### ignoreRegExpLiterals
Examples of **correct** code for this rule with the `{ "ignoreRegExpLiterals": true }` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "ignoreRegExpLiterals": true }]*/
var longRegExpLiteral = /this is a really really really really really long regular expression!/;
```
+:::
+
### ignorePattern
Examples of **correct** code for this rule with the `ignorePattern` option:
+::: correct
+
```js
/*eslint max-len: ["error", { "ignorePattern": "^\\s*var\\s.+=\\s*require\\s*\\(" }]*/
var dep = require('really/really/really/really/really/really/really/really/long/module');
```
+
+:::
diff --git a/docs/src/rules/max-lines-per-function.md b/docs/src/rules/max-lines-per-function.md
index daf6f389d14..66eeb481b55 100644
--- a/docs/src/rules/max-lines-per-function.md
+++ b/docs/src/rules/max-lines-per-function.md
@@ -13,7 +13,6 @@ related_rules:
- max-statements-per-line
---
-Enforces a maximum function length.
Some people consider large functions a code smell. Large functions tend to do a lot of things and can make it hard following what's going on. Many coding style guides dictate a limit of the number of lines that a function can comprise of. This rule can help enforce that style.
@@ -77,6 +76,8 @@ is equivalent to
Examples of **incorrect** code for this rule with a max value of `2`:
+::: incorrect
+
```js
/*eslint max-lines-per-function: ["error", 2]*/
function foo() {
@@ -84,6 +85,10 @@ function foo() {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint max-lines-per-function: ["error", 2]*/
function foo() {
@@ -92,6 +97,10 @@ function foo() {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint max-lines-per-function: ["error", 2]*/
function foo() {
@@ -101,8 +110,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with a max value of `3`:
+::: correct
+
```js
/*eslint max-lines-per-function: ["error", 3]*/
function foo() {
@@ -110,6 +123,10 @@ function foo() {
}
```
+:::
+
+::: correct
+
```js
/*eslint max-lines-per-function: ["error", 3]*/
function foo() {
@@ -118,6 +135,10 @@ function foo() {
}
```
+:::
+
+::: correct
+
```js
/*eslint max-lines-per-function: ["error", 3]*/
function foo() {
@@ -127,10 +148,14 @@ function foo() {
}
```
+:::
+
### skipBlankLines
Examples of **incorrect** code for this rule with the `{ "skipBlankLines": true }` option:
+::: incorrect
+
```js
/*eslint max-lines-per-function: ["error", {"max": 2, "skipBlankLines": true}]*/
function foo() {
@@ -139,8 +164,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "skipBlankLines": true }` option:
+::: correct
+
```js
/*eslint max-lines-per-function: ["error", {"max": 3, "skipBlankLines": true}]*/
function foo() {
@@ -149,10 +178,14 @@ function foo() {
}
```
+:::
+
### skipComments
Examples of **incorrect** code for this rule with the `{ "skipComments": true }` option:
+::: incorrect
+
```js
/*eslint max-lines-per-function: ["error", {"max": 2, "skipComments": true}]*/
function foo() {
@@ -161,8 +194,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "skipComments": true }` option:
+::: correct
+
```js
/*eslint max-lines-per-function: ["error", {"max": 3, "skipComments": true}]*/
function foo() {
@@ -171,10 +208,14 @@ function foo() {
}
```
+:::
+
### IIFEs
Examples of **incorrect** code for this rule with the `{ "IIFEs": true }` option:
+::: incorrect
+
```js
/*eslint max-lines-per-function: ["error", {"max": 2, "IIFEs": true}]*/
(function(){
@@ -186,8 +227,12 @@ Examples of **incorrect** code for this rule with the `{ "IIFEs": true }` option
})();
```
+:::
+
Examples of **correct** code for this rule with the `{ "IIFEs": true }` option:
+::: correct
+
```js
/*eslint max-lines-per-function: ["error", {"max": 3, "IIFEs": true}]*/
(function(){
@@ -199,6 +244,8 @@ Examples of **correct** code for this rule with the `{ "IIFEs": true }` option:
})();
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the number of lines in your functions.
diff --git a/docs/src/rules/max-lines.md b/docs/src/rules/max-lines.md
index 2ce5e5813fb..d33153b0e3b 100644
--- a/docs/src/rules/max-lines.md
+++ b/docs/src/rules/max-lines.md
@@ -14,7 +14,6 @@ further_reading:
- https://web.archive.org/web/20160725154648/http://www.mind2b.com/component/content/article/24-software-module-size-and-file-size
---
-Enforces a maximum file length.
Some people consider large files a code smell. Large files tend to do a lot of things and can make it hard following what's going. While there is not an objective maximum number of lines considered acceptable in a file, most people would agree it should not be in the thousands. Recommendations usually range from 100 to 500 lines.
@@ -38,6 +37,8 @@ This rule has a number or object option:
Examples of **incorrect** code for this rule with a max value of `2`:
+::: incorrect
+
```js
/*eslint max-lines: ["error", 2]*/
var a,
@@ -45,6 +46,10 @@ var a,
c;
```
+:::
+
+::: incorrect
+
```js
/*eslint max-lines: ["error", 2]*/
@@ -52,6 +57,10 @@ var a,
b,c;
```
+:::
+
+::: incorrect
+
```js
/*eslint max-lines: ["error", 2]*/
// a comment
@@ -59,30 +68,46 @@ var a,
b,c;
```
+:::
+
Examples of **correct** code for this rule with a max value of `2`:
+::: correct
+
```js
/*eslint max-lines: ["error", 2]*/
var a,
b, c;
```
+:::
+
+::: correct
+
```js
/*eslint max-lines: ["error", 2]*/
var a, b, c;
```
+:::
+
+::: correct
+
```js
/*eslint max-lines: ["error", 2]*/
// a comment
var a, b, c;
```
+:::
+
### skipBlankLines
Examples of **incorrect** code for this rule with the `{ "skipBlankLines": true }` option:
+::: incorrect
+
```js
/*eslint max-lines: ["error", {"max": 2, "skipBlankLines": true}]*/
@@ -91,8 +116,12 @@ var a,
c;
```
+:::
+
Examples of **correct** code for this rule with the `{ "skipBlankLines": true }` option:
+::: correct
+
```js
/*eslint max-lines: ["error", {"max": 2, "skipBlankLines": true}]*/
@@ -100,10 +129,14 @@ var a,
b, c;
```
+:::
+
### skipComments
Examples of **incorrect** code for this rule with the `{ "skipComments": true }` option:
+::: incorrect
+
```js
/*eslint max-lines: ["error", {"max": 2, "skipComments": true}]*/
// a comment
@@ -112,8 +145,12 @@ var a,
c;
```
+:::
+
Examples of **correct** code for this rule with the `{ "skipComments": true }` option:
+::: correct
+
```js
/*eslint max-lines: ["error", {"max": 2, "skipComments": true}]*/
// a comment
@@ -121,6 +158,8 @@ var a,
b, c;
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the number of lines in your files.
diff --git a/docs/src/rules/max-nested-callbacks.md b/docs/src/rules/max-nested-callbacks.md
index a541eb7a50f..4bdc36be86f 100644
--- a/docs/src/rules/max-nested-callbacks.md
+++ b/docs/src/rules/max-nested-callbacks.md
@@ -17,7 +17,6 @@ further_reading:
- https://web.archive.org/web/20220127215850/https://howtonode.org/control-flow-part-ii
---
-Enforces a maximum depth that callbacks can be nested.
Many JavaScript libraries use the callback pattern to manage asynchronous operations. A program of any complexity will most likely need to manage several asynchronous operations at various levels of concurrency. A common pitfall that is easy to fall into is nesting callbacks, which makes code more difficult to read the deeper the callbacks are nested.
@@ -49,6 +48,8 @@ This rule has a number or object option:
Examples of **incorrect** code for this rule with the `{ "max": 3 }` option:
+::: incorrect
+
```js
/*eslint max-nested-callbacks: ["error", 3]*/
@@ -63,8 +64,12 @@ foo1(function() {
});
```
+:::
+
Examples of **correct** code for this rule with the `{ "max": 3 }` option:
+::: correct
+
```js
/*eslint max-nested-callbacks: ["error", 3]*/
@@ -86,3 +91,5 @@ function handleFoo4() {
foo5();
}
```
+
+:::
diff --git a/docs/src/rules/max-params.md b/docs/src/rules/max-params.md
index ad45082ec65..5a3a4ed8a2f 100644
--- a/docs/src/rules/max-params.md
+++ b/docs/src/rules/max-params.md
@@ -13,7 +13,6 @@ related_rules:
- max-statements
---
-Enforces a maximum number of parameters in function definitions.
Functions that take numerous parameters can be difficult to read and write because it requires the memorization of what each parameter is, its type, and the order they should appear in. As a result, many coders adhere to a convention that caps the number of parameters a function can take.
@@ -39,6 +38,8 @@ This rule has a number or object option:
Examples of **incorrect** code for this rule with the default `{ "max": 3 }` option:
+:::incorrect
+
```js
/*eslint max-params: ["error", 3]*/
/*eslint-env es6*/
@@ -52,8 +53,12 @@ let foo = (bar, baz, qux, qxx) => {
};
```
+:::
+
Examples of **correct** code for this rule with the default `{ "max": 3 }` option:
+:::correct
+
```js
/*eslint max-params: ["error", 3]*/
/*eslint-env es6*/
@@ -66,3 +71,5 @@ let foo = (bar, baz, qux) => {
doSomething();
};
```
+
+:::
diff --git a/docs/src/rules/max-statements-per-line.md b/docs/src/rules/max-statements-per-line.md
index 8d34246ea9a..ee5a9b730ff 100644
--- a/docs/src/rules/max-statements-per-line.md
+++ b/docs/src/rules/max-statements-per-line.md
@@ -13,7 +13,6 @@ related_rules:
- max-statements
---
-Enforces a maximum number of statements allowed per line.
A line of code containing too many statements can be difficult to read. Code is generally read from the top down, especially when scanning, so limiting the number of statements allowed on a single line can be very beneficial for readability and maintainability.
@@ -33,6 +32,8 @@ The "max" object property is optional (default: 1).
Examples of **incorrect** code for this rule with the default `{ "max": 1 }` option:
+::: incorrect
+
```js
/*eslint max-statements-per-line: ["error", { "max": 1 }]*/
@@ -45,8 +46,12 @@ var foo = function foo() { bar = 1; };
(function foo() { bar = 1; })();
```
+:::
+
Examples of **correct** code for this rule with the default `{ "max": 1 }` option:
+::: correct
+
```js
/*eslint max-statements-per-line: ["error", { "max": 1 }]*/
@@ -59,8 +64,12 @@ var foo = function foo() { };
(function foo() { })();
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "max": 2 }` option:
+::: incorrect
+
```js
/*eslint max-statements-per-line: ["error", { "max": 2 }]*/
@@ -73,8 +82,12 @@ var foo = function foo() { bar = 1; };
(function foo() { bar = 1; baz = 2; })();
```
+:::
+
Examples of **correct** code for this rule with the `{ "max": 2 }` option:
+::: correct
+
```js
/*eslint max-statements-per-line: ["error", { "max": 2 }]*/
@@ -87,6 +100,8 @@ var foo = function foo() { bar = 1; };
(function foo() { var bar = 1; })();
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the number of statements on each line.
diff --git a/docs/src/rules/max-statements.md b/docs/src/rules/max-statements.md
index 2d18021f34a..ec981ba424c 100644
--- a/docs/src/rules/max-statements.md
+++ b/docs/src/rules/max-statements.md
@@ -13,7 +13,6 @@ related_rules:
- max-params
---
-Enforces a maximum number of statements allowed in function blocks.
The `max-statements` rule allows you to specify the maximum number of statements allowed in a function.
@@ -45,6 +44,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "max": 10 }` option:
+::: incorrect
+
```js
/*eslint max-statements: ["error", 10]*/
/*eslint-env es6*/
@@ -80,8 +81,12 @@ let foo = () => {
};
```
+:::
+
Examples of **correct** code for this rule with the default `{ "max": 10 }` option:
+::: correct
+
```js
/*eslint max-statements: ["error", 10]*/
/*eslint-env es6*/
@@ -127,10 +132,14 @@ let foo = () => {
}
```
+:::
+
Note that this rule does not apply to class static blocks, and that statements in class static blocks do not count as statements in the enclosing function.
Examples of **correct** code for this rule with `{ "max": 2 }` option:
+::: correct
+
```js
/*eslint max-statements: ["error", 2]*/
@@ -151,10 +160,14 @@ function foo() {
}
```
+:::
+
### ignoreTopLevelFunctions
Examples of additional **correct** code for this rule with the `{ "max": 10 }, { "ignoreTopLevelFunctions": true }` options:
+::: correct
+
```js
/*eslint max-statements: ["error", 10, { "ignoreTopLevelFunctions": true }]*/
@@ -172,3 +185,5 @@ function foo() {
var foo11 = 11;
}
```
+
+:::
diff --git a/docs/src/rules/multiline-comment-style.md b/docs/src/rules/multiline-comment-style.md
index fca714605aa..243cbc58cfc 100644
--- a/docs/src/rules/multiline-comment-style.md
+++ b/docs/src/rules/multiline-comment-style.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/multiline-c
rule_type: suggestion
---
-
-Enforces a particular style for multiline comments.
Many style guides require a particular style for comments that span multiple lines. For example, some style guides prefer the use of a single block comment for multiline comments, whereas other style guides prefer consecutive line comments.
@@ -27,6 +25,8 @@ The rule always ignores directive comments such as `/* eslint-disable */`. Addit
Examples of **incorrect** code for this rule with the default `"starred-block"` option:
+::: incorrect
+
```js
/* eslint multiline-comment-style: ["error", "starred-block"] */
@@ -57,8 +57,12 @@ foo();
```
+:::
+
Examples of **correct** code for this rule with the default `"starred-block"` option:
+::: correct
+
```js
/* eslint multiline-comment-style: ["error", "starred-block"] */
@@ -71,8 +75,12 @@ foo();
// single-line comment
```
+:::
+
Examples of **incorrect** code for this rule with the `"bare-block"` option:
+::: incorrect
+
```js
/* eslint multiline-comment-style: ["error", "bare-block"] */
@@ -87,8 +95,12 @@ foo();
foo();
```
+:::
+
Examples of **correct** code for this rule with the `"bare-block"` option:
+::: correct
+
```js
/* eslint multiline-comment-style: ["error", "bare-block"] */
@@ -97,8 +109,12 @@ Examples of **correct** code for this rule with the `"bare-block"` option:
foo();
```
+:::
+
Examples of **incorrect** code for this rule with the `"separate-lines"` option:
+::: incorrect
+
```js
/* eslint multiline-comment-style: ["error", "separate-lines"] */
@@ -115,8 +131,12 @@ foo();
```
+:::
+
Examples of **correct** code for this rule with the `"separate-lines"` option:
+::: correct
+
```js
/* eslint multiline-comment-style: ["error", "separate-lines"] */
@@ -126,6 +146,8 @@ foo();
```
+:::
+
## When Not To Use It
If you don't want to enforce a particular style for multiline comments, you can disable the rule.
diff --git a/docs/src/rules/multiline-ternary.md b/docs/src/rules/multiline-ternary.md
index f92d6715f41..9f309efba45 100644
--- a/docs/src/rules/multiline-ternary.md
+++ b/docs/src/rules/multiline-ternary.md
@@ -7,9 +7,7 @@ related_rules:
- operator-linebreak
---
-
-Enforces or disallows newlines between operands of ternary expressions.
JavaScript allows operands of ternary expressions to be separated by newlines, which can improve the readability of your program.
@@ -46,6 +44,8 @@ This is the default option.
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint multiline-ternary: ["error", "always"]*/
@@ -58,8 +58,12 @@ foo > bar ?
value : value2;
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint multiline-ternary: ["error", "always"]*/
@@ -74,10 +78,14 @@ foo > bar ?
value3;
```
+:::
+
### always-multiline
Examples of **incorrect** code for this rule with the `"always-multiline"` option:
+::: incorrect
+
```js
/*eslint multiline-ternary: ["error", "always-multiline"]*/
@@ -91,8 +99,12 @@ foo > bar &&
bar > baz ? value1 : value2;
```
+:::
+
Examples of **correct** code for this rule with the `"always-multiline"` option:
+::: correct
+
```js
/*eslint multiline-ternary: ["error", "always-multiline"]*/
@@ -118,10 +130,14 @@ foo > bar &&
value2;
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint multiline-ternary: ["error", "never"]*/
@@ -137,8 +153,12 @@ foo >
value2;
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint multiline-ternary: ["error", "never"]*/
@@ -151,6 +171,8 @@ foo > bar ? (
) : value3;
```
+:::
+
## When Not To Use It
You can safely disable this rule if you do not have any strict conventions about whether the operands of a ternary expression should be separated by newlines.
diff --git a/docs/src/rules/new-cap.md b/docs/src/rules/new-cap.md
index 8bca67c9e73..1309ee821f7 100644
--- a/docs/src/rules/new-cap.md
+++ b/docs/src/rules/new-cap.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/new-cap.md
rule_type: suggestion
---
-Requires constructor names to begin with a capital letter.
The `new` operator in JavaScript creates a new instance of a particular type of object. That type of object is represented by a constructor function. Since constructor functions are just regular functions, the only defining characteristic is that `new` is being used as part of the call. Native JavaScript functions begin with an uppercase letter to distinguish those functions that are to be used as constructors from functions that are not. Many style guides recommend following this pattern to more easily determine which functions are to be used as constructors.
@@ -30,6 +29,8 @@ This rule requires constructor names to begin with a capital letter. Certain bui
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint new-cap: "error"*/
@@ -38,6 +39,8 @@ function foo(arg) {
}
```
+:::
+
## Options
This rule has an object option:
@@ -57,58 +60,84 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "newIsCap": true }` option:
+::: incorrect
+
```js
/*eslint new-cap: ["error", { "newIsCap": true }]*/
var friend = new person();
```
+:::
+
Examples of **correct** code for this rule with the default `{ "newIsCap": true }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "newIsCap": true }]*/
var friend = new Person();
```
+:::
+
Examples of **correct** code for this rule with the `{ "newIsCap": false }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "newIsCap": false }]*/
var friend = new person();
```
+:::
+
### capIsNew
Examples of **incorrect** code for this rule with the default `{ "capIsNew": true }` option:
+::: incorrect
+
```js
/*eslint new-cap: ["error", { "capIsNew": true }]*/
var colleague = Person();
```
+:::
+
Examples of **correct** code for this rule with the default `{ "capIsNew": true }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "capIsNew": true }]*/
var colleague = new Person();
```
+:::
+
Examples of **correct** code for this rule with the `{ "capIsNew": false }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "capIsNew": false }]*/
var colleague = Person();
```
+:::
+
### newIsCapExceptions
Examples of additional **correct** code for this rule with the `{ "newIsCapExceptions": ["events"] }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "newIsCapExceptions": ["events"] }]*/
@@ -117,10 +146,14 @@ var events = require('events');
var emitter = new events();
```
+:::
+
### newIsCapExceptionPattern
Examples of additional **correct** code for this rule with the `{ "newIsCapExceptionPattern": "^person\\.." }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "newIsCapExceptionPattern": "^person\\.." }]*/
@@ -129,18 +162,26 @@ var friend = new person.acquaintance();
var bestFriend = new person.friend();
```
+:::
+
Examples of additional **correct** code for this rule with the `{ "newIsCapExceptionPattern": "\\.bar$" }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "newIsCapExceptionPattern": "\\.bar$" }]*/
var friend = new person.bar();
```
+:::
+
### capIsNewExceptions
Examples of additional **correct** code for this rule with the `{ "capIsNewExceptions": ["Person"] }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "capIsNewExceptions": ["Person"] }]*/
@@ -149,10 +190,14 @@ function foo(arg) {
}
```
+:::
+
### capIsNewExceptionPattern
Examples of additional **correct** code for this rule with the `{ "capIsNewExceptionPattern": "^person\\.." }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "capIsNewExceptionPattern": "^person\\.." }]*/
@@ -160,16 +205,24 @@ var friend = person.Acquaintance();
var bestFriend = person.Friend();
```
+:::
+
Examples of additional **correct** code for this rule with the `{ "capIsNewExceptionPattern": "\\.Bar$" }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "capIsNewExceptionPattern": "\\.Bar$" }]*/
foo.Bar();
```
+:::
+
Examples of additional **correct** code for this rule with the `{ "capIsNewExceptionPattern": "^Foo" }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "capIsNewExceptionPattern": "^Foo" }]*/
@@ -180,32 +233,46 @@ var y = Foobar(42);
var z = Foo.Bar(42);
```
+:::
+
### properties
Examples of **incorrect** code for this rule with the default `{ "properties": true }` option:
+::: incorrect
+
```js
/*eslint new-cap: ["error", { "properties": true }]*/
var friend = new person.acquaintance();
```
+:::
+
Examples of **correct** code for this rule with the default `{ "properties": true }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "properties": true }]*/
var friend = new person.Acquaintance();
```
+:::
+
Examples of **correct** code for this rule with the `{ "properties": false }` option:
+::: correct
+
```js
/*eslint new-cap: ["error", { "properties": false }]*/
var friend = new person.acquaintance();
```
+:::
+
## When Not To Use It
If you have conventions that don't require an uppercase letter for constructors, or don't require capitalized functions be only used as constructors, turn this rule off.
diff --git a/docs/src/rules/new-parens.md b/docs/src/rules/new-parens.md
index 0d7cefcd62b..b51bdfe52d2 100644
--- a/docs/src/rules/new-parens.md
+++ b/docs/src/rules/new-parens.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/new-parens.
rule_type: layout
---
-
-Requires parentheses when invoking a constructor with no arguments.
JavaScript allows the omission of parentheses when invoking a function via the `new` keyword and the constructor has no arguments. However, some coders believe that omitting the parentheses is inconsistent with the rest of the language and thus makes code less clear.
@@ -30,6 +28,8 @@ This rule takes one option.
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint new-parens: "error"*/
@@ -37,8 +37,12 @@ var person = new Person;
var person = new (Person);
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint new-parens: "error"*/
@@ -46,10 +50,14 @@ var person = new Person();
var person = new (Person)();
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint new-parens: ["error", "never"]*/
@@ -57,8 +65,12 @@ var person = new Person();
var person = new (Person)();
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint new-parens: ["error", "never"]*/
@@ -66,3 +78,5 @@ var person = new Person;
var person = (new Person);
var person = new Person("Name");
```
+
+:::
diff --git a/docs/src/rules/newline-after-var.md b/docs/src/rules/newline-after-var.md
index 9cb5c7a48b8..da6f6e22cb0 100644
--- a/docs/src/rules/newline-after-var.md
+++ b/docs/src/rules/newline-after-var.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/newline-aft
rule_type: layout
---
-
-Requires or disallows an empty line after variable declarations.
This rule was **deprecated** in ESLint v4.0.0 and replaced by the [padding-line-between-statements](padding-line-between-statements) rule.
@@ -46,6 +44,8 @@ This rule has a string option:
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint newline-after-var: ["error", "always"]*/
/*eslint-env es6*/
@@ -68,8 +68,12 @@ var name = "world";
console.log(greet, name);
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint newline-after-var: ["error", "always"]*/
/*eslint-env es6*/
@@ -96,10 +100,14 @@ var name = "world";
console.log(greet, name);
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint newline-after-var: ["error", "never"]*/
/*eslint-env es6*/
@@ -126,8 +134,12 @@ var name = "world";
console.log(greet, name);
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint newline-after-var: ["error", "never"]*/
/*eslint-env es6*/
@@ -149,3 +161,5 @@ var name = "world";
// var name = require("world");
console.log(greet, name);
```
+
+:::
diff --git a/docs/src/rules/newline-before-return.md b/docs/src/rules/newline-before-return.md
index 261b8619ffb..62f12881a57 100644
--- a/docs/src/rules/newline-before-return.md
+++ b/docs/src/rules/newline-before-return.md
@@ -7,9 +7,7 @@ related_rules:
- newline-after-var
---
-
-Requires an empty line before `return` statements.
This rule was **deprecated** in ESLint v4.0.0 and replaced by the [padding-line-between-statements](padding-line-between-statements) rule.
@@ -48,6 +46,8 @@ This rule requires an empty line before `return` statements to increase code cla
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint newline-before-return: "error"*/
@@ -68,8 +68,12 @@ function foo(bar) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint newline-before-return: "error"*/
@@ -118,6 +122,8 @@ function foo() {
}
```
+:::
+
## When Not To Use It
You can safely disable this rule if you do not have any strict conventions about whitespace before `return` statements.
diff --git a/docs/src/rules/newline-per-chained-call.md b/docs/src/rules/newline-per-chained-call.md
index 6aaab2ca9c5..88d677c9598 100644
--- a/docs/src/rules/newline-per-chained-call.md
+++ b/docs/src/rules/newline-per-chained-call.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/newline-per
rule_type: layout
---
-
-Requires a newline after each call in a method chain.
Chained method calls on a single line without line breaks are harder to read, so some developers place a newline character after each method call in the chain to make it more readable and easy to maintain.
@@ -71,6 +69,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "ignoreChainWithDepth": 2 }` option:
+::: incorrect
+
```js
/*eslint newline-per-chained-call: ["error", { "ignoreChainWithDepth": 2 }]*/
@@ -88,8 +88,12 @@ _
obj.method().method2().method3();
```
+:::
+
Examples of **correct** code for this rule with the default `{ "ignoreChainWithDepth": 2 }` option:
+::: correct
+
```js
/*eslint newline-per-chained-call: ["error", { "ignoreChainWithDepth": 2 }]*/
@@ -122,6 +126,8 @@ obj
.method3().prop;
```
+:::
+
## When Not To Use It
If you have conflicting rules or when you are fine with chained calls on one line, you can safely turn this rule off.
diff --git a/docs/src/rules/no-alert.md b/docs/src/rules/no-alert.md
index 414cce09d12..4dcfdf97286 100644
--- a/docs/src/rules/no-alert.md
+++ b/docs/src/rules/no-alert.md
@@ -8,7 +8,6 @@ related_rules:
- no-debugger
---
-Disallows the use of `alert`, `confirm`, and `prompt`.
JavaScript's `alert`, `confirm`, and `prompt` functions are widely considered to be obtrusive as UI elements and should be replaced by a more appropriate custom UI implementation. Furthermore, `alert` is often used while debugging code, which should be removed before deployment to production.
@@ -22,6 +21,8 @@ This rule is aimed at catching debugging code that should be removed and popup U
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint no-alert: "error"*/
@@ -32,8 +33,12 @@ confirm("Are you sure?");
prompt("What's your name?", "John Doe");
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint no-alert: "error"*/
@@ -48,3 +53,5 @@ function foo() {
alert();
}
```
+
+:::
diff --git a/docs/src/rules/no-array-constructor.md b/docs/src/rules/no-array-constructor.md
index da49901c4f4..9a96c5cc6a0 100644
--- a/docs/src/rules/no-array-constructor.md
+++ b/docs/src/rules/no-array-constructor.md
@@ -8,7 +8,6 @@ related_rules:
- no-new-wrappers
---
-Disallows `Array` constructors.
Use of the `Array` constructor to construct a new array is generally
discouraged in favor of array literal notation because of the single-argument
@@ -22,6 +21,8 @@ This rule disallows `Array` constructors.
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint no-array-constructor: "error"*/
@@ -30,8 +31,12 @@ Array(0, 1, 2)
new Array(0, 1, 2)
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint no-array-constructor: "error"*/
@@ -42,6 +47,8 @@ new Array(someOtherArray.length)
[0, 1, 2]
```
+:::
+
## When Not To Use It
This rule enforces a nearly universal stylistic concern. That being said, this
diff --git a/docs/src/rules/no-arrow-condition.md b/docs/src/rules/no-arrow-condition.md
index ad15b469848..a6ef8f21348 100644
--- a/docs/src/rules/no-arrow-condition.md
+++ b/docs/src/rules/no-arrow-condition.md
@@ -39,6 +39,8 @@ var x = a <= 1 ? 2 : 3
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint no-arrow-condition: "error"*/
/*eslint-env es6*/
@@ -51,3 +53,5 @@ a => 1 ? 2 : 3
var x = a => 1 ? 2 : 3
var x = (a) => 1 ? 2 : 3
```
+
+:::
diff --git a/docs/src/rules/no-async-promise-executor.md b/docs/src/rules/no-async-promise-executor.md
index 6627f5b8be7..b32f137caee 100644
--- a/docs/src/rules/no-async-promise-executor.md
+++ b/docs/src/rules/no-async-promise-executor.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-async-pr
rule_type: problem
---
-
-Disallows using an async function as a Promise executor.
The `new Promise` constructor accepts an *executor* function as an argument, which has `resolve` and `reject` parameters that can be used to control the state of the created Promise. For example:
@@ -34,6 +32,8 @@ This rule aims to disallow async Promise executor functions.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
const foo = new Promise(async (resolve, reject) => {
readFile('foo.txt', function(err, result) {
@@ -50,8 +50,12 @@ const result = new Promise(async (resolve, reject) => {
});
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
const foo = new Promise((resolve, reject) => {
readFile('foo.txt', function(err, result) {
@@ -66,6 +70,8 @@ const foo = new Promise((resolve, reject) => {
const result = Promise.resolve(foo);
```
+:::
+
## When Not To Use It
If your codebase doesn't support async function syntax, there's no need to enable this rule.
diff --git a/docs/src/rules/no-await-in-loop.md b/docs/src/rules/no-await-in-loop.md
index 5e759e60cc2..6c2c1041992 100644
--- a/docs/src/rules/no-await-in-loop.md
+++ b/docs/src/rules/no-await-in-loop.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-await-in
rule_type: problem
---
-Disallows `await` inside of loops.
Performing an operation on each element of an iterable is a common task. However, performing an
`await` as part of each operation is an indication that the program is not taking full advantage of
@@ -48,6 +47,8 @@ This rule disallows the use of `await` within loop bodies.
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint no-await-in-loop: "error"*/
@@ -62,8 +63,12 @@ async function foo(things) {
}
```
+:::
+
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint no-await-in-loop: "error"*/
@@ -77,6 +82,8 @@ async function foo(things) {
}
```
+:::
+
## When Not To Use It
In many cases the iterations of a loop are not actually independent of each-other. For example, the
diff --git a/docs/src/rules/no-bitwise.md b/docs/src/rules/no-bitwise.md
index b2721bac59f..1cdbb60d9a7 100644
--- a/docs/src/rules/no-bitwise.md
+++ b/docs/src/rules/no-bitwise.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-bitwise.
rule_type: suggestion
---
-Disallows bitwise operators.
The use of bitwise operators in JavaScript is very rare and often `&` or `|` is simply a mistyped `&&` or `||`, which will lead to unexpected behavior.
@@ -19,6 +18,8 @@ This rule disallows bitwise operators.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-bitwise: "error"*/
@@ -49,8 +50,12 @@ x >>= y;
x >>>= y;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-bitwise: "error"*/
@@ -65,6 +70,8 @@ var x = y < z;
x += y;
```
+:::
+
## Options
This rule has an object option:
@@ -76,18 +83,26 @@ This rule has an object option:
Examples of **correct** code for this rule with the `{ "allow": ["~"] }` option:
+::: correct
+
```js
/*eslint no-bitwise: ["error", { "allow": ["~"] }] */
~[1,2,3].indexOf(1) === -1;
```
+:::
+
### int32Hint
Examples of **correct** code for this rule with the `{ "int32Hint": true }` option:
+::: correct
+
```js
/*eslint no-bitwise: ["error", { "int32Hint": true }] */
var b = a|0;
```
+
+:::
diff --git a/docs/src/rules/no-buffer-constructor.md b/docs/src/rules/no-buffer-constructor.md
index 93dde30184d..96da4d15644 100644
--- a/docs/src/rules/no-buffer-constructor.md
+++ b/docs/src/rules/no-buffer-constructor.md
@@ -9,7 +9,6 @@ further_reading:
- https://github.com/nodejs/node/issues/4660
---
-Disallows use of the `Buffer()` constructor.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -21,6 +20,8 @@ This rule disallows calling and constructing the `Buffer()` constructor.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
new Buffer(5);
new Buffer([1, 2, 3]);
@@ -32,8 +33,12 @@ new Buffer(res.body.amount);
new Buffer(res.body.values);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
Buffer.alloc(5);
Buffer.allocUnsafe(5);
@@ -43,6 +48,8 @@ Buffer.alloc(res.body.amount);
Buffer.from(res.body.values);
```
+:::
+
## When Not To Use It
If you don't use Node.js, or you still need to support versions of Node.js that lack methods like `Buffer.from`, then you should not enable this rule.
diff --git a/docs/src/rules/no-caller.md b/docs/src/rules/no-caller.md
index f7be8267288..2dfabff100b 100644
--- a/docs/src/rules/no-caller.md
+++ b/docs/src/rules/no-caller.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-caller.m
rule_type: suggestion
---
-Disallows use of `caller`/`callee`.
The use of `arguments.caller` and `arguments.callee` make several code optimizations impossible. They have been deprecated in future versions of JavaScript and their use is forbidden in ECMAScript 5 while in strict mode.
@@ -21,6 +20,8 @@ This rule is aimed at discouraging the use of deprecated and sub-optimal code by
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-caller: "error"*/
@@ -37,8 +38,12 @@ function foo(n) {
});
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-caller: "error"*/
@@ -54,3 +59,5 @@ function foo(n) {
return !(n > 1) ? 1 : factorial(n - 1) * n;
});
```
+
+:::
diff --git a/docs/src/rules/no-case-declarations.md b/docs/src/rules/no-case-declarations.md
index feeb25499f5..589c84ec3f5 100644
--- a/docs/src/rules/no-case-declarations.md
+++ b/docs/src/rules/no-case-declarations.md
@@ -7,9 +7,7 @@ related_rules:
- no-fallthrough
---
-
-Disallows lexical declarations in case/default clauses.
This rule disallows lexical declarations (`let`, `const`, `function` and `class`)
in `case`/`default` clauses. The reason is that the lexical declaration is visible
@@ -25,6 +23,8 @@ This rule aims to prevent access to uninitialized lexical bindings as well as ac
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-case-declarations: "error"*/
/*eslint-env es6*/
@@ -44,8 +44,12 @@ switch (foo) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-case-declarations: "error"*/
/*eslint-env es6*/
@@ -77,6 +81,8 @@ switch (foo) {
}
```
+:::
+
## When Not To Use It
If you depend on fall through behavior and want access to bindings introduced in the case block.
diff --git a/docs/src/rules/no-catch-shadow.md b/docs/src/rules/no-catch-shadow.md
index 3ed3b038161..08a484fb047 100644
--- a/docs/src/rules/no-catch-shadow.md
+++ b/docs/src/rules/no-catch-shadow.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-catch-sh
rule_type: suggestion
---
-Disallows shadowing of variables inside of catch.
This rule was **deprecated** in ESLint v5.1.0.
@@ -29,6 +28,8 @@ This rule is aimed at preventing unexpected behavior in your program that may ar
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-catch-shadow: "error"*/
@@ -51,8 +52,12 @@ try {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-catch-shadow: "error"*/
@@ -75,6 +80,8 @@ try {
}
```
+:::
+
## When Not To Use It
If you do not need to support IE 8 and earlier, you should turn this rule off.
diff --git a/docs/src/rules/no-class-assign.md b/docs/src/rules/no-class-assign.md
index 9666f8ce7aa..6c8c9c9658b 100644
--- a/docs/src/rules/no-class-assign.md
+++ b/docs/src/rules/no-class-assign.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-class-as
rule_type: problem
---
-
-Disallows modifying variables of class declarations.
`ClassDeclaration` creates a variable, and we can modify the variable.
@@ -26,6 +24,8 @@ This rule is aimed to flag modifying variables of class declarations.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-class-assign: "error"*/
/*eslint-env es6*/
@@ -34,6 +34,10 @@ class A { }
A = 0;
```
+:::
+
+::: incorrect
+
```js
/*eslint no-class-assign: "error"*/
/*eslint-env es6*/
@@ -42,6 +46,10 @@ A = 0;
class A { }
```
+:::
+
+::: incorrect
+
```js
/*eslint no-class-assign: "error"*/
/*eslint-env es6*/
@@ -53,6 +61,10 @@ class A {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint no-class-assign: "error"*/
/*eslint-env es6*/
@@ -65,8 +77,12 @@ let A = class A {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-class-assign: "error"*/
/*eslint-env es6*/
@@ -75,6 +91,10 @@ let A = class A { }
A = 0; // A is a variable.
```
+:::
+
+::: correct
+
```js
/*eslint no-class-assign: "error"*/
/*eslint-env es6*/
@@ -86,6 +106,10 @@ let A = class {
}
```
+:::
+
+::: correct
+
```js
/*eslint no-class-assign: 2*/
/*eslint-env es6*/
@@ -97,6 +121,8 @@ class A {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about modifying variables of class declarations, you can safely disable this rule.
diff --git a/docs/src/rules/no-comma-dangle.md b/docs/src/rules/no-comma-dangle.md
index 6498c1045b3..3227dbded87 100644
--- a/docs/src/rules/no-comma-dangle.md
+++ b/docs/src/rules/no-comma-dangle.md
@@ -24,6 +24,8 @@ This rule is aimed at detecting trailing commas in object literals. As such, it
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
var foo = {
bar: "baz",
@@ -38,8 +40,12 @@ foo({
});
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
var foo = {
bar: "baz",
@@ -54,6 +60,8 @@ foo({
});
```
+:::
+
## When Not To Use It
If your code will not be run in IE8 or below (a Node.js application, for example) and you'd prefer to allow trailing commas, turn this rule off.
diff --git a/docs/src/rules/no-compare-neg-zero.md b/docs/src/rules/no-compare-neg-zero.md
index bbfea3d8f60..04a88170c0a 100644
--- a/docs/src/rules/no-compare-neg-zero.md
+++ b/docs/src/rules/no-compare-neg-zero.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-compare-
rule_type: problem
---
-
-Disallows comparing against `-0`.
## Rule Details
@@ -15,6 +13,8 @@ The rule should warn against code that tries to compare against `-0`, since that
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/* eslint no-compare-neg-zero: "error" */
@@ -23,8 +23,12 @@ if (x === -0) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/* eslint no-compare-neg-zero: "error" */
@@ -33,6 +37,10 @@ if (x === 0) {
}
```
+:::
+
+::: correct
+
```js
/* eslint no-compare-neg-zero: "error" */
@@ -40,3 +48,5 @@ if (Object.is(x, -0)) {
// doSomething()...
}
```
+
+:::
diff --git a/docs/src/rules/no-cond-assign.md b/docs/src/rules/no-cond-assign.md
index a1e61504ba8..f223ee7ec39 100644
--- a/docs/src/rules/no-cond-assign.md
+++ b/docs/src/rules/no-cond-assign.md
@@ -7,9 +7,7 @@ related_rules:
- no-extra-parens
---
-
-Disallows assignment operators in conditional statements.
In conditional statements, it is very easy to mistype a comparison operator (such as `==`) as an assignment operator (such as `=`). For example:
@@ -37,6 +35,8 @@ This rule has a string option:
Examples of **incorrect** code for this rule with the default `"except-parens"` option:
+::: incorrect
+
```js
/*eslint no-cond-assign: "error"*/
@@ -55,8 +55,12 @@ function setHeight(someNode) {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"except-parens"` option:
+::: correct
+
```js
/*eslint no-cond-assign: "error"*/
@@ -83,10 +87,14 @@ function setHeight(someNode) {
}
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint no-cond-assign: ["error", "always"]*/
@@ -121,8 +129,12 @@ function setHeight(someNode) {
}
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint no-cond-assign: ["error", "always"]*/
@@ -132,3 +144,5 @@ if (x === 0) {
var b = 1;
}
```
+
+:::
diff --git a/docs/src/rules/no-confusing-arrow.md b/docs/src/rules/no-confusing-arrow.md
index 094497135ec..be4bb96fd5a 100644
--- a/docs/src/rules/no-confusing-arrow.md
+++ b/docs/src/rules/no-confusing-arrow.md
@@ -8,9 +8,7 @@ related_rules:
- arrow-parens
---
-
-Disallows arrow functions where they could be confused with comparisons.
Arrow functions (`=>`) are similar in syntax to some comparison operators (`>`, `<`, `<=`, and `>=`). This rule warns against using the arrow function syntax in places where it could be confused with a comparison operator.
@@ -31,6 +29,8 @@ var x = a <= 1 ? 2 : 3;
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-confusing-arrow: "error"*/
/*eslint-env es6*/
@@ -39,8 +39,12 @@ var x = a => 1 ? 2 : 3;
var x = (a) => 1 ? 2 : 3;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-confusing-arrow: "error"*/
/*eslint-env es6*/
@@ -52,6 +56,8 @@ var x = (a) => {
var x = a => { return 1 ? 2 : 3; };
```
+:::
+
## Options
This rule accepts two options argument with the following defaults:
@@ -74,6 +80,8 @@ This rule accepts two options argument with the following defaults:
Examples of **incorrect** code for this rule with the `{"allowParens": false}` option:
+::: incorrect
+
```js
/*eslint no-confusing-arrow: ["error", {"allowParens": false}]*/
/*eslint-env es6*/
@@ -81,6 +89,8 @@ var x = a => (1 ? 2 : 3);
var x = (a) => (1 ? 2 : 3);
```
+:::
+
`onlyOneSimpleParam` is a boolean setting that can be `true` or `false`(default):
1. `true` relaxes the rule and doesn't report errors if the arrow function has 0 or more than 1 parameters, or the parameter is not an identifier.
@@ -88,6 +98,8 @@ var x = (a) => (1 ? 2 : 3);
Examples of **correct** code for this rule with the `{"onlyOneSimpleParam": true}` option:
+::: correct
+
```js
/*eslint no-confusing-arrow: ["error", {"onlyOneSimpleParam": true}]*/
/*eslint-env es6*/
@@ -98,3 +110,5 @@ Examples of **correct** code for this rule with the `{"onlyOneSimpleParam": true
([a]) => 1 ? 2 : 3;
(...a) => 1 ? 2 : 3;
```
+
+:::
diff --git a/docs/src/rules/no-console.md b/docs/src/rules/no-console.md
index 1b258a3d8a5..5fdfbae020c 100644
--- a/docs/src/rules/no-console.md
+++ b/docs/src/rules/no-console.md
@@ -8,7 +8,6 @@ related_rules:
- no-debugger
---
-Disallows the use of `console`.
In JavaScript that is designed to be executed in the browser, it's considered a best practice to avoid using methods on `console`. Such messages are considered to be for debugging purposes and therefore not suitable to ship to the client. In general, calls using `console` should be stripped before being pushed to production.
@@ -23,6 +22,8 @@ This rule disallows calls or assignments to methods of the `console` object.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/* eslint no-console: "error" */
@@ -32,8 +33,12 @@ console.error("Log an error level message.");
console.log = foo();
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/* eslint no-console: "error" */
@@ -41,6 +46,8 @@ Examples of **correct** code for this rule:
Console.log("Hello world!");
```
+:::
+
## Options
This rule has an object option for exceptions:
@@ -49,6 +56,8 @@ This rule has an object option for exceptions:
Examples of additional **correct** code for this rule with a sample `{ "allow": ["warn", "error"] }` option:
+::: correct
+
```js
/* eslint no-console: ["error", { allow: ["warn", "error"] }] */
@@ -56,6 +65,8 @@ console.warn("Log a warn level message.");
console.error("Log an error level message.");
```
+:::
+
## When Not To Use It
If you're using Node.js, however, `console` is used to output information to the user and so is not strictly used for debugging purposes. If you are developing for Node.js then you most likely do not want this rule enabled.
diff --git a/docs/src/rules/no-const-assign.md b/docs/src/rules/no-const-assign.md
index 74921f96919..a0df9d6a276 100644
--- a/docs/src/rules/no-const-assign.md
+++ b/docs/src/rules/no-const-assign.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-const-as
rule_type: problem
---
-
-Disallows modifying variables that are declared using `const`.
We cannot modify variables that are declared using `const` keyword.
It will raise a runtime error.
@@ -20,6 +18,8 @@ This rule is aimed to flag modifying variables that are declared using `const` k
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/
@@ -28,6 +28,10 @@ const a = 0;
a = 1;
```
+:::
+
+::: incorrect
+
```js
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/
@@ -36,6 +40,10 @@ const a = 0;
a += 1;
```
+:::
+
+::: incorrect
+
```js
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/
@@ -44,8 +52,12 @@ const a = 0;
++a;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/
@@ -54,6 +66,10 @@ const a = 0;
console.log(a);
```
+:::
+
+::: correct
+
```js
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/
@@ -63,6 +79,10 @@ for (const a in [1, 2, 3]) { // `a` is re-defined (not modified) on each loop st
}
```
+:::
+
+::: correct
+
```js
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/
@@ -72,6 +92,8 @@ for (const a of [1, 2, 3]) { // `a` is re-defined (not modified) on each loop st
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about modifying variables that are declared using `const` keyword, you can safely disable this rule.
diff --git a/docs/src/rules/no-constant-binary-expression.md b/docs/src/rules/no-constant-binary-expression.md
index 5f3c42aa4a0..1d0bf89d7b1 100644
--- a/docs/src/rules/no-constant-binary-expression.md
+++ b/docs/src/rules/no-constant-binary-expression.md
@@ -5,9 +5,10 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-constant
rule_type: problem
related_rules:
- no-constant-condition
+further_reading:
+- https://eslint.org/blog/2022/07/interesting-bugs-caught-by-no-constant-binary-expression/
---
-Disallows expressions where the operation doesn't affect the value.
Comparisons which will always evaluate to true or false and logical expressions (`||`, `&&`, `??`) which either always short-circuit or never short-circuit are both likely indications of programmer error.
@@ -38,6 +39,8 @@ It also identifies `||`, `&&` and `??` logical expressions which will either alw
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-constant-binary-expression: "error"*/
@@ -54,8 +57,12 @@ const objIsEmpty = someObj === {};
const arrIsEmpty = someArr === [];
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-constant-binary-expression: "error"*/
@@ -71,3 +78,5 @@ const objIsEmpty = Object.keys(someObj).length === 0;
const arrIsEmpty = someArr.length === 0;
```
+
+:::
diff --git a/docs/src/rules/no-constant-condition.md b/docs/src/rules/no-constant-condition.md
index a2b4e025aac..959e3d6c87e 100644
--- a/docs/src/rules/no-constant-condition.md
+++ b/docs/src/rules/no-constant-condition.md
@@ -7,9 +7,7 @@ related_rules:
- no-constant-binary-expression
---
-
-Disallows constant expressions in conditions.
A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. For example, the following code looks as if it is not ready for production.
@@ -28,6 +26,8 @@ This rule disallows constant expressions in the test condition of:
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-constant-condition: "error"*/
@@ -78,8 +78,12 @@ do {
var result = 0 ? a : b;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-constant-condition: "error"*/
@@ -102,6 +106,8 @@ do {
var result = x !== 0 ? a : b;
```
+:::
+
## Options
### checkLoops
@@ -110,6 +116,8 @@ Set to `true` by default. Setting this option to `false` allows constant express
Examples of **correct** code for when `checkLoops` is `false`:
+::: correct
+
```js
/*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
@@ -134,3 +142,5 @@ do {
}
} while (true)
```
+
+:::
diff --git a/docs/src/rules/no-constructor-return.md b/docs/src/rules/no-constructor-return.md
index 4be5f30bedd..f6e941b1b96 100644
--- a/docs/src/rules/no-constructor-return.md
+++ b/docs/src/rules/no-constructor-return.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-construc
rule_type: problem
---
-Disallows returning values in constructor.
In JavaScript, returning a value in the constructor of a class may be a mistake. Forbidding this pattern prevents mistakes resulting from unfamiliarity with the language or a copy-paste error.
@@ -15,6 +14,8 @@ This rule disallows return statements in the constructor of a class. Note that r
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-constructor-return: "error"*/
@@ -34,8 +35,12 @@ class B {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-constructor-return: "error"*/
@@ -55,3 +60,5 @@ class D {
}
}
```
+
+:::
diff --git a/docs/src/rules/no-continue.md b/docs/src/rules/no-continue.md
index fff6611a3e6..4ab311d6b61 100644
--- a/docs/src/rules/no-continue.md
+++ b/docs/src/rules/no-continue.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-continue
rule_type: suggestion
---
-Disallows `continue` statements.
The `continue` statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. When used incorrectly it makes code less testable, less readable and less maintainable. Structured control flow statements such as `if` should be used instead.
@@ -28,6 +27,8 @@ This rule disallows `continue` statements.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-continue: "error"*/
@@ -43,6 +44,10 @@ for(i = 0; i < 10; i++) {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint no-continue: "error"*/
@@ -58,8 +63,12 @@ labeledLoop: for(i = 0; i < 10; i++) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-continue: "error"*/
@@ -73,6 +82,8 @@ for(i = 0; i < 10; i++) {
}
```
+:::
+
## Compatibility
* **JSLint**: `continue`
diff --git a/docs/src/rules/no-control-regex.md b/docs/src/rules/no-control-regex.md
index 57e85e470d3..3e957063222 100644
--- a/docs/src/rules/no-control-regex.md
+++ b/docs/src/rules/no-control-regex.md
@@ -8,9 +8,7 @@ related_rules:
- no-regex-spaces
---
-
-Disallows control characters in regular expressions.
Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing elements that explicitly match these characters is most likely a mistake.
@@ -22,12 +20,15 @@ The following elements of regular expression patterns are considered possible er
* Hexadecimal character escapes from `\x00` to `\x1F`.
* Unicode character escapes from `\u0000` to `\u001F`.
+* Unicode code point escapes from `\u{0}` to `\u{1F}`.
* Unescaped raw characters from U+0000 to U+001F.
Control escapes such as `\t` and `\n` are allowed by this rule.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-control-regex: "error"*/
@@ -35,24 +36,32 @@ var pattern1 = /\x00/;
var pattern2 = /\x0C/;
var pattern3 = /\x1F/;
var pattern4 = /\u000C/;
-var pattern5 = new RegExp("\x0C"); // raw U+000C character in the pattern
-var pattern6 = new RegExp("\\x0C"); // \x0C pattern
+var pattern5 = /\u{C}/u;
+var pattern6 = new RegExp("\x0C"); // raw U+000C character in the pattern
+var pattern7 = new RegExp("\\x0C"); // \x0C pattern
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-control-regex: "error"*/
var pattern1 = /\x20/;
var pattern2 = /\u0020/;
-var pattern3 = /\t/;
-var pattern4 = /\n/;
-var pattern5 = new RegExp("\x20");
-var pattern6 = new RegExp("\\t");
-var pattern7 = new RegExp("\\n");
+var pattern3 = /\u{20}/u;
+var pattern4 = /\t/;
+var pattern5 = /\n/;
+var pattern6 = new RegExp("\x20");
+var pattern7 = new RegExp("\\t");
+var pattern8 = new RegExp("\\n");
```
+:::
+
## Known Limitations
When checking `RegExp` constructor calls, this rule examines evaluated regular expression patterns. Therefore, although this rule intends to allow syntax such as `\t`, it doesn't allow `new RegExp("\t")` since the evaluated pattern (string value of `"\t"`) contains a raw control character (the TAB character).
diff --git a/docs/src/rules/no-debugger.md b/docs/src/rules/no-debugger.md
index 67588f209d0..f9bd8b31f95 100644
--- a/docs/src/rules/no-debugger.md
+++ b/docs/src/rules/no-debugger.md
@@ -10,9 +10,7 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger
---
-
-Disallows the use of `debugger`.
The `debugger` statement is used to tell the executing JavaScript environment to stop execution and start up a debugger at the current point in the code. This has fallen out of favor as a good practice with the advent of modern debugging and development tools. Production code should definitely not contain `debugger`, as it will cause the browser to stop executing code and open an appropriate debugger.
@@ -22,6 +20,8 @@ This rule disallows `debugger` statements.
Example of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-debugger: "error"*/
@@ -31,8 +31,12 @@ function isTruthy(x) {
}
```
+:::
+
Example of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-debugger: "error"*/
@@ -41,6 +45,8 @@ function isTruthy(x) {
}
```
+:::
+
## When Not To Use It
If your code is still very much in development and don't want to worry about stripping `debugger` statements, then turn this rule off. You'll generally want to turn it back on when testing code prior to deployment.
diff --git a/docs/src/rules/no-delete-var.md b/docs/src/rules/no-delete-var.md
index b14dd57f536..6abedd7f1e4 100644
--- a/docs/src/rules/no-delete-var.md
+++ b/docs/src/rules/no-delete-var.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-delete-v
rule_type: suggestion
---
-
-Disallows deleting variables.
The purpose of the `delete` operator is to remove a property from an object. Using the `delete` operator on a variable might lead to unexpected behavior.
@@ -19,9 +17,13 @@ If ESLint parses code in strict mode, the parser (instead of this rule) reports
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-delete-var: "error"*/
var x;
delete x;
```
+
+:::
diff --git a/docs/src/rules/no-div-regex.md b/docs/src/rules/no-div-regex.md
index 60a1440a284..31653a94208 100644
--- a/docs/src/rules/no-div-regex.md
+++ b/docs/src/rules/no-div-regex.md
@@ -8,9 +8,7 @@ related_rules:
- no-regex-spaces
---
-
-Disallows regular expressions that look like division.
Require regex literals to escape division operators.
@@ -24,16 +22,24 @@ This is used to disambiguate the division operator to not confuse users.
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint no-div-regex: "error"*/
function bar() { return /=foo/; }
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint no-div-regex: "error"*/
function bar() { return /[=]foo/; }
```
+
+:::
diff --git a/docs/src/rules/no-dupe-args.md b/docs/src/rules/no-dupe-args.md
index c28f5cd5fd4..0556d70e9a0 100644
--- a/docs/src/rules/no-dupe-args.md
+++ b/docs/src/rules/no-dupe-args.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-dupe-arg
rule_type: problem
---
-
-Disallows duplicate arguments in `function` definitions.
If more than one parameter has the same name in a function definition, the last occurrence "shadows" the preceding occurrences. A duplicated name might be a typing error.
@@ -19,6 +17,8 @@ If ESLint parses code in strict mode, the parser (instead of this rule) reports
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-dupe-args: "error"*/
@@ -31,8 +31,12 @@ var bar = function (a, b, a) {
};
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-dupe-args: "error"*/
@@ -44,3 +48,5 @@ var bar = function (a, b, c) {
console.log(a, b, c);
};
```
+
+:::
diff --git a/docs/src/rules/no-dupe-class-members.md b/docs/src/rules/no-dupe-class-members.md
index f50088b0da8..cc32d47085a 100644
--- a/docs/src/rules/no-dupe-class-members.md
+++ b/docs/src/rules/no-dupe-class-members.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-dupe-cla
rule_type: problem
---
-
-Disallows duplicate name in class members.
If there are declarations of the same name in class members, the last declaration overwrites other declarations silently.
It can cause unexpected behaviors.
@@ -32,6 +30,8 @@ This rule is aimed to flag the use of duplicate names in class members.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-dupe-class-members: "error"*/
@@ -61,8 +61,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-dupe-class-members: "error"*/
@@ -92,6 +96,8 @@ class Foo {
}
```
+:::
+
## When Not To Use It
This rule should not be used in ES3/5 environments.
diff --git a/docs/src/rules/no-dupe-else-if.md b/docs/src/rules/no-dupe-else-if.md
index 38a9c969114..b0010189e9f 100644
--- a/docs/src/rules/no-dupe-else-if.md
+++ b/docs/src/rules/no-dupe-else-if.md
@@ -8,9 +8,7 @@ related_rules:
- no-lonely-if
---
-
-Disallows duplicate conditions in `if-else-if` chains.
`if-else-if` chains are commonly used when there is a need to execute only one branch (or at most one branch) out of several possible branches, based on certain conditions.
@@ -44,6 +42,8 @@ This rule disallows duplicate conditions in the same `if-else-if` chain.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-dupe-else-if: "error"*/
@@ -78,8 +78,12 @@ if (n === 1) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-dupe-else-if: "error"*/
@@ -114,10 +118,14 @@ if (n === 1) {
}
```
+:::
+
This rule can also detect some cases where the conditions are not identical, but the branch can never execute due to the logic of `||` and `&&` operators.
Examples of additional **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-dupe-else-if: "error"*/
@@ -162,6 +170,8 @@ if (a) {
}
```
+:::
+
Please note that this rule does not compare conditions from the chain with conditions inside statements, and will not warn in the cases such as follows:
```js
diff --git a/docs/src/rules/no-dupe-keys.md b/docs/src/rules/no-dupe-keys.md
index a5bfda0ec1b..45c8bbf3449 100644
--- a/docs/src/rules/no-dupe-keys.md
+++ b/docs/src/rules/no-dupe-keys.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-dupe-key
rule_type: problem
---
-
-Disallows duplicate keys in object literals.
Multiple properties with the same key in object literals can cause unexpected behavior in your application.
@@ -24,6 +22,8 @@ This rule disallows duplicate keys in object literals.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-dupe-keys: "error"*/
@@ -43,8 +43,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-dupe-keys: "error"*/
@@ -53,3 +57,5 @@ var foo = {
quxx: "qux"
};
```
+
+:::
diff --git a/docs/src/rules/no-duplicate-case.md b/docs/src/rules/no-duplicate-case.md
index 455689f33d9..5f221fabdc3 100644
--- a/docs/src/rules/no-duplicate-case.md
+++ b/docs/src/rules/no-duplicate-case.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-duplicat
rule_type: problem
---
-
-Disallows duplicate `case` labels.
If a `switch` statement has duplicate test expressions in `case` clauses, it is likely that a programmer copied a `case` clause but forgot to change the test expression.
@@ -17,6 +15,8 @@ This rule disallows duplicate test expressions in `case` clauses of `switch` sta
Examples of **incorrect** code for this rule:
+:::incorrect
+
```js
/*eslint no-duplicate-case: "error"*/
@@ -57,8 +57,12 @@ switch (a) {
}
```
+:::
+
Examples of **correct** code for this rule:
+:::correct
+
```js
/*eslint no-duplicate-case: "error"*/
@@ -99,6 +103,8 @@ switch (a) {
}
```
+:::
+
## When Not To Use It
In rare cases where identical test expressions in `case` clauses produce different values, which necessarily means that the expressions are causing and relying on side effects, you will have to disable this rule.
diff --git a/docs/src/rules/no-duplicate-imports.md b/docs/src/rules/no-duplicate-imports.md
index 88d7a2d8706..f029093e7fe 100644
--- a/docs/src/rules/no-duplicate-imports.md
+++ b/docs/src/rules/no-duplicate-imports.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-duplicat
rule_type: problem
---
-Disallows duplicate imports.
Using a single `import` statement per module will make the code clearer because you can see everything being imported from that module on one line.
@@ -23,6 +22,8 @@ This rule requires that all imports from a single module that can be merged exis
Example of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-duplicate-imports: "error"*/
@@ -31,8 +32,12 @@ import something from 'another-module';
import { find } from 'module';
```
+:::
+
Example of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-duplicate-imports: "error"*/
@@ -40,8 +45,12 @@ import { merge, find } from 'module';
import something from 'another-module';
```
+:::
+
Example of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-duplicate-imports: "error"*/
@@ -50,6 +59,8 @@ import { merge } from 'module';
import * as something from 'module';
```
+:::
+
## Options
This rule takes one optional argument, an object with a single key, `includeExports` which is a `boolean`. It defaults to `false`.
@@ -58,6 +69,8 @@ If re-exporting from an imported module, you should add the imports to the `impo
Example of **incorrect** code for this rule with the `{ "includeExports": true }` option:
+::: incorrect
+
```js
/*eslint no-duplicate-imports: ["error", { "includeExports": true }]*/
@@ -66,8 +79,12 @@ import { merge } from 'module';
export { find } from 'module';
```
+:::
+
Example of **correct** code for this rule with the `{ "includeExports": true }` option:
+::: correct
+
```js
/*eslint no-duplicate-imports: ["error", { "includeExports": true }]*/
@@ -76,8 +93,12 @@ import { merge, find } from 'module';
export { find };
```
+:::
+
Example of **correct** code for this rule with the `{ "includeExports": true }` option:
+::: correct
+
```js
/*eslint no-duplicate-imports: ["error", { "includeExports": true }]*/
@@ -89,3 +110,5 @@ export * as something from 'module';
// cannot be written differently
export * from 'module';
```
+
+:::
diff --git a/docs/src/rules/no-else-return.md b/docs/src/rules/no-else-return.md
index 8903c4a6082..8380d5a7b2e 100644
--- a/docs/src/rules/no-else-return.md
+++ b/docs/src/rules/no-else-return.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-else-ret
rule_type: suggestion
---
-
-Disallows `return` before `else`.
If an `if` block contains a `return` statement, the `else` block becomes unnecessary. Its contents can be placed outside of the block.
@@ -36,6 +34,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-else-return: "error"*/
@@ -91,8 +91,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-else-return: "error"*/
@@ -133,10 +137,14 @@ function foo() {
}
```
+:::
+
### `allowElseIf: false`
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
@@ -149,8 +157,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-else-return: ["error", {allowElseIf: false}]*/
@@ -164,3 +176,5 @@ function foo() {
}
}
```
+
+:::
diff --git a/docs/src/rules/no-empty-character-class.md b/docs/src/rules/no-empty-character-class.md
index 146e0cdf876..3d8f544e6ba 100644
--- a/docs/src/rules/no-empty-character-class.md
+++ b/docs/src/rules/no-empty-character-class.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-empty-ch
rule_type: problem
---
-
-Disallows empty character classes in regular expressions.
Because empty character classes in regular expressions do not match anything, they might be typing mistakes.
@@ -21,6 +19,8 @@ This rule disallows empty character classes in regular expressions.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-empty-character-class: "error"*/
@@ -28,8 +28,12 @@ Examples of **incorrect** code for this rule:
"abcdefg".match(/^abc[]/); // null
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-empty-character-class: "error"*/
@@ -40,6 +44,8 @@ Examples of **correct** code for this rule:
"abcdefg".match(/^abc[a-z]/); // ["abcd"]
```
+:::
+
## Known Limitations
This rule does not report empty character classes in the string argument of calls to the `RegExp` constructor.
diff --git a/docs/src/rules/no-empty-class.md b/docs/src/rules/no-empty-class.md
index 0673cd3f7ed..e9431716084 100644
--- a/docs/src/rules/no-empty-class.md
+++ b/docs/src/rules/no-empty-class.md
@@ -21,6 +21,8 @@ This rule is aimed at highlighting possible typos and unexpected behavior in reg
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
var foo = /^abc[]/;
@@ -29,8 +31,12 @@ var foo = /^abc[]/;
bar.match(/^abc[]/);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
var foo = /^abc/;
@@ -38,3 +44,5 @@ var foo = /^abc[a-z]/;
var bar = new RegExp("^abc[]");
```
+
+:::
diff --git a/docs/src/rules/no-empty-function.md b/docs/src/rules/no-empty-function.md
index e80566c189d..192de97a3e7 100644
--- a/docs/src/rules/no-empty-function.md
+++ b/docs/src/rules/no-empty-function.md
@@ -7,7 +7,6 @@ related_rules:
- no-empty
---
-Disallows empty functions.
Empty functions can reduce readability because readers need to guess whether it's intentional or not.
So writing a clear comment for empty functions is a good practice.
@@ -33,6 +32,8 @@ A function will not be considered a problem if it contains a comment.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-empty-function: "error"*/
/*eslint-env es6*/
@@ -82,8 +83,12 @@ class A {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-empty-function: "error"*/
/*eslint-env es6*/
@@ -173,6 +178,8 @@ class A {
}
```
+:::
+
## Options
This rule has an option to allow specific kinds of functions to be empty.
@@ -193,6 +200,8 @@ This rule has an option to allow specific kinds of functions to be empty.
Examples of **correct** code for the `{ "allow": ["functions"] }` option:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["functions"] }]*/
@@ -205,10 +214,14 @@ var obj = {
};
```
+:::
+
### allow: arrowFunctions
Examples of **correct** code for the `{ "allow": ["arrowFunctions"] }` option:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["arrowFunctions"] }]*/
/*eslint-env es6*/
@@ -216,10 +229,14 @@ Examples of **correct** code for the `{ "allow": ["arrowFunctions"] }` option:
var foo = () => {};
```
+:::
+
### allow: generatorFunctions
Examples of **correct** code for the `{ "allow": ["generatorFunctions"] }` option:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["generatorFunctions"] }]*/
/*eslint-env es6*/
@@ -233,10 +250,14 @@ var obj = {
};
```
+:::
+
### allow: methods
Examples of **correct** code for the `{ "allow": ["methods"] }` option:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["methods"] }]*/
/*eslint-env es6*/
@@ -251,10 +272,14 @@ class A {
}
```
+:::
+
### allow: generatorMethods
Examples of **correct** code for the `{ "allow": ["generatorMethods"] }` option:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["generatorMethods"] }]*/
/*eslint-env es6*/
@@ -269,10 +294,14 @@ class A {
}
```
+:::
+
### allow: getters
Examples of **correct** code for the `{ "allow": ["getters"] }` option:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["getters"] }]*/
/*eslint-env es6*/
@@ -287,10 +316,14 @@ class A {
}
```
+:::
+
### allow: setters
Examples of **correct** code for the `{ "allow": ["setters"] }` option:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["setters"] }]*/
/*eslint-env es6*/
@@ -305,10 +338,14 @@ class A {
}
```
+:::
+
### allow: constructors
Examples of **correct** code for the `{ "allow": ["constructors"] }` option:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["constructors"] }]*/
/*eslint-env es6*/
@@ -318,10 +355,14 @@ class A {
}
```
+:::
+
### allow: asyncFunctions
Examples of **correct** code for the `{ "allow": ["asyncFunctions"] }` options:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["asyncFunctions"] }]*/
/*eslint-env es2017*/
@@ -329,10 +370,14 @@ Examples of **correct** code for the `{ "allow": ["asyncFunctions"] }` options:
async function a(){}
```
+:::
+
### allow: asyncMethods
Examples of **correct** code for the `{ "allow": ["asyncMethods"] }` options:
+::: correct
+
```js
/*eslint no-empty-function: ["error", { "allow": ["asyncMethods"] }]*/
/*eslint-env es2017*/
@@ -347,6 +392,8 @@ class A {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about empty functions, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-empty-label.md b/docs/src/rules/no-empty-label.md
index 72ef07f7587..b12d403aeec 100644
--- a/docs/src/rules/no-empty-label.md
+++ b/docs/src/rules/no-empty-label.md
@@ -21,6 +21,8 @@ This error occurs when a label is used to mark a statement that is not an iterat
Example of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-empty-label: "error"*/
@@ -28,8 +30,12 @@ labeled:
var x = 10;
```
+:::
+
Example of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-empty-label: "error"*/
@@ -39,6 +45,8 @@ for (var i=10; i; i--) {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about usage of labels, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-empty-pattern.md b/docs/src/rules/no-empty-pattern.md
index 93b0865b677..a259bf22b07 100644
--- a/docs/src/rules/no-empty-pattern.md
+++ b/docs/src/rules/no-empty-pattern.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-empty-pa
rule_type: problem
---
-
-Disallows empty destructuring patterns.
When using destructuring, it's possible to create a pattern that has no effect. This happens when empty curly braces are used to the right of an embedded object destructuring pattern, such as:
@@ -38,6 +36,8 @@ This rule aims to flag any empty patterns in destructured objects and arrays, an
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-empty-pattern: "error"*/
@@ -51,8 +51,12 @@ function foo({a: {}}) {}
function foo({a: []}) {}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-empty-pattern: "error"*/
@@ -61,3 +65,5 @@ var {a = []} = foo;
function foo({a = {}}) {}
function foo({a = []}) {}
```
+
+:::
diff --git a/docs/src/rules/no-empty.md b/docs/src/rules/no-empty.md
index 4b1d428a105..70935afb3b6 100644
--- a/docs/src/rules/no-empty.md
+++ b/docs/src/rules/no-empty.md
@@ -7,9 +7,7 @@ related_rules:
- no-empty-function
---
-
-Disallows empty block statements.
Empty block statements, while not technically errors, usually occur due to refactoring that wasn't completed. They can cause confusion when reading code.
@@ -19,6 +17,8 @@ This rule disallows empty block statements. This rule ignores block statements w
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-empty: "error"*/
@@ -40,8 +40,12 @@ try {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-empty: "error"*/
@@ -66,6 +70,8 @@ try {
}
```
+:::
+
## Options
This rule has an object option for exceptions:
@@ -76,6 +82,8 @@ This rule has an object option for exceptions:
Examples of additional **correct** code for this rule with the `{ "allowEmptyCatch": true }` option:
+::: correct
+
```js
/* eslint no-empty: ["error", { "allowEmptyCatch": true }] */
try {
@@ -91,6 +99,8 @@ finally {
}
```
+:::
+
## When Not To Use It
If you intentionally use empty block statements then you can disable this rule.
diff --git a/docs/src/rules/no-eq-null.md b/docs/src/rules/no-eq-null.md
index fdacac401ad..f2e17ac66c1 100644
--- a/docs/src/rules/no-eq-null.md
+++ b/docs/src/rules/no-eq-null.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-eq-null.
rule_type: suggestion
---
-Disallows `null` comparisons without type-checking operators,
Comparing to `null` without a type-checking operator (`==` or `!=`), can have unintended results as the comparison will evaluate to true when comparing to not just a `null`, but also an `undefined` value.
@@ -21,6 +20,8 @@ The `no-eq-null` rule aims reduce potential bug and unwanted behavior by ensurin
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-eq-null: "error"*/
@@ -33,8 +34,12 @@ while (qux != null) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-eq-null: "error"*/
@@ -47,6 +52,8 @@ while (qux !== null) {
}
```
+:::
+
## When Not To Use It
If you want to enforce type-checking operations in general, use the more powerful [eqeqeq](./eqeqeq) instead.
diff --git a/docs/src/rules/no-eval.md b/docs/src/rules/no-eval.md
index f559ebe6641..1488c1132ce 100644
--- a/docs/src/rules/no-eval.md
+++ b/docs/src/rules/no-eval.md
@@ -10,7 +10,6 @@ further_reading:
- https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
---
-Disallows eval().
JavaScript's `eval()` function is potentially dangerous and is often misused. Using `eval()` on untrusted code can open a program up to several different injection attacks. The use of `eval()` in most contexts can be substituted for a better, alternative approach to a problem.
@@ -26,6 +25,8 @@ This rule is aimed at preventing potentially dangerous, unnecessary, and slow co
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-eval: "error"*/
@@ -42,8 +43,12 @@ foo("var a = 0");
this.eval("var a = 0");
```
+:::
+
Example of additional **incorrect** code for this rule when `browser` environment is set to `true`:
+::: incorrect
+
```js
/*eslint no-eval: "error"*/
/*eslint-env browser*/
@@ -51,8 +56,12 @@ Example of additional **incorrect** code for this rule when `browser` environmen
window.eval("var a = 0");
```
+:::
+
Example of additional **incorrect** code for this rule when `node` environment is set to `true`:
+::: incorrect
+
```js
/*eslint no-eval: "error"*/
/*eslint-env node*/
@@ -60,8 +69,12 @@ Example of additional **incorrect** code for this rule when `node` environment i
global.eval("var a = 0");
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-eval: "error"*/
/*eslint-env es6*/
@@ -89,6 +102,8 @@ class A {
}
```
+:::
+
## Options
This rule has an option to allow indirect calls to `eval`.
@@ -102,6 +117,8 @@ Indirect calls to `eval` are less dangerous than direct calls to `eval` because
Example of **incorrect** code for this rule with the `{"allowIndirect": true}` option:
+::: incorrect
+
```js
/*eslint no-eval: "error"*/
@@ -110,8 +127,12 @@ var obj = { x: "foo" },
value = eval("obj." + key);
```
+:::
+
Examples of **correct** code for this rule with the `{"allowIndirect": true}` option:
+::: correct
+
```js
/*eslint no-eval: "error"*/
@@ -123,6 +144,10 @@ foo("var a = 0");
this.eval("var a = 0");
```
+:::
+
+::: correct
+
```js
/*eslint no-eval: "error"*/
/*eslint-env browser*/
@@ -130,6 +155,10 @@ this.eval("var a = 0");
window.eval("var a = 0");
```
+:::
+
+::: correct
+
```js
/*eslint no-eval: "error"*/
/*eslint-env node*/
@@ -137,6 +166,8 @@ window.eval("var a = 0");
global.eval("var a = 0");
```
+:::
+
## Known Limitations
* This rule is warning every `eval()` even if the `eval` is not global's.
diff --git a/docs/src/rules/no-ex-assign.md b/docs/src/rules/no-ex-assign.md
index a4e186626df..9835a658bee 100644
--- a/docs/src/rules/no-ex-assign.md
+++ b/docs/src/rules/no-ex-assign.md
@@ -7,9 +7,7 @@ further_reading:
- https://bocoup.com/blog/the-catch-with-try-catch
---
-
-Disallows reassigning exceptions in `catch` clauses.
If a `catch` clause in a `try` statement accidentally (or purposely) assigns another value to the exception parameter, it is impossible to refer to the error from that point on.
Since there is no `arguments` object to offer alternative access to this data, assignment of the parameter is absolutely destructive.
@@ -20,6 +18,8 @@ This rule disallows reassigning exceptions in `catch` clauses.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-ex-assign: "error"*/
@@ -30,8 +30,12 @@ try {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-ex-assign: "error"*/
@@ -41,3 +45,5 @@ try {
var foo = 10;
}
```
+
+:::
diff --git a/docs/src/rules/no-extend-native.md b/docs/src/rules/no-extend-native.md
index eef3c34a0bd..065b214cbc0 100644
--- a/docs/src/rules/no-extend-native.md
+++ b/docs/src/rules/no-extend-native.md
@@ -7,7 +7,6 @@ related_rules:
- no-global-assign
---
-Disallows extending of native objects.
In JavaScript, you can extend any object, including builtin or "native" objects. Sometimes people change the behavior of these native objects in ways that break the assumptions made about them in other parts of the code.
@@ -37,6 +36,8 @@ Disallows directly modifying the prototype of builtin objects.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-extend-native: "error"*/
@@ -44,6 +45,8 @@ Object.prototype.a = "a";
Object.defineProperty(Array.prototype, "times", { value: 999 });
```
+:::
+
## Options
This rule accepts an `exceptions` option, which can be used to specify a list of builtins for which extensions will be allowed.
@@ -52,12 +55,16 @@ This rule accepts an `exceptions` option, which can be used to specify a list of
Examples of **correct** code for the sample `{ "exceptions": ["Object"] }` option:
+::: correct
+
```js
/*eslint no-extend-native: ["error", { "exceptions": ["Object"] }]*/
Object.prototype.a = "a";
```
+:::
+
## Known Limitations
This rule *does not* report any of the following less obvious approaches to modify the prototype of builtin objects:
diff --git a/docs/src/rules/no-extra-bind.md b/docs/src/rules/no-extra-bind.md
index eebe43a4f6a..a783de9de28 100644
--- a/docs/src/rules/no-extra-bind.md
+++ b/docs/src/rules/no-extra-bind.md
@@ -8,9 +8,7 @@ further_reading:
- https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/
---
-
-Disallows unnecessary function binding.
The `bind()` method is used to create functions with specific `this` values and, optionally, binds arguments to specific values. When used to specify the value of `this`, it's important that the function actually uses `this` in its function body. For example:
@@ -45,6 +43,8 @@ This rule is aimed at avoiding the unnecessary use of `bind()` and as such will
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-extra-bind: "error"*/
/*eslint-env es6*/
@@ -74,8 +74,12 @@ var x = function () {
}.bind(baz);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-extra-bind: "error"*/
@@ -88,6 +92,8 @@ var x = function (a) {
}.bind(foo, bar);
```
+:::
+
## When Not To Use It
If you are not concerned about unnecessary calls to `bind()`, you can safely disable this rule.
diff --git a/docs/src/rules/no-extra-boolean-cast.md b/docs/src/rules/no-extra-boolean-cast.md
index 550f6985afd..5429d8c6fc3 100644
--- a/docs/src/rules/no-extra-boolean-cast.md
+++ b/docs/src/rules/no-extra-boolean-cast.md
@@ -5,11 +5,9 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-extra-bo
rule_type: suggestion
---
-
-
-Disallows unnecessary boolean casts.
+
In contexts such as an `if` statement's test where the result of the expression will already be coerced to a Boolean, casting to a Boolean via double negation (`!!`) or a `Boolean` call is unnecessary. For example, these `if` statements are equivalent:
@@ -33,6 +31,8 @@ This rule disallows unnecessary boolean casts.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-extra-boolean-cast: "error"*/
@@ -65,8 +65,12 @@ for (; !!foo; ) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-extra-boolean-cast: "error"*/
@@ -80,6 +84,8 @@ function foo() {
var foo = bar ? !!baz : !!bat;
```
+:::
+
## Options
This rule has an object option:
@@ -90,6 +96,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with `"enforceForLogicalOperands"` option set to `true`:
+::: incorrect
+
```js
/*eslint no-extra-boolean-cast: ["error", {"enforceForLogicalOperands": true}]*/
@@ -110,8 +118,12 @@ foo && Boolean(bar) ? baz : bat
var foo = new Boolean(!!bar || baz)
```
+:::
+
Examples of **correct** code for this rule with `"enforceForLogicalOperands"` option set to `true`:
+::: correct
+
```js
/*eslint no-extra-boolean-cast: ["error", {"enforceForLogicalOperands": true}]*/
@@ -133,3 +145,5 @@ var foo = new Boolean(bar || baz)
var foo = !!bar || baz;
```
+
+:::
diff --git a/docs/src/rules/no-extra-label.md b/docs/src/rules/no-extra-label.md
index c5dda3f8d0a..30a0ea2dcf7 100644
--- a/docs/src/rules/no-extra-label.md
+++ b/docs/src/rules/no-extra-label.md
@@ -9,9 +9,7 @@ related_rules:
- no-unused-labels
---
-
-Disallows unnecessary labels.
If a loop contains no nested loops or switches, labeling the loop is unnecessary.
@@ -30,6 +28,8 @@ This rule is aimed at eliminating unnecessary labels.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-extra-label: "error"*/
@@ -47,8 +47,12 @@ C: switch (a) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-extra-label: "error"*/
@@ -84,6 +88,8 @@ C: switch (a) {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about usage of labels, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-extra-parens.md b/docs/src/rules/no-extra-parens.md
index d5afd39a306..669130cb074 100644
--- a/docs/src/rules/no-extra-parens.md
+++ b/docs/src/rules/no-extra-parens.md
@@ -11,9 +11,7 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
---
-
-Disallows unnecessary parentheses.
This rule restricts the use of parentheses to only where they are necessary.
@@ -47,6 +45,8 @@ This rule has an object option for exceptions to the `"all"` option:
Examples of **incorrect** code for this rule with the default `"all"` option:
+::: incorrect
+
```js
/* eslint no-extra-parens: "error" */
@@ -73,8 +73,12 @@ class B {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"all"` option:
+::: correct
+
```js
/* eslint no-extra-parens: "error" */
@@ -105,10 +109,14 @@ class B {
}
```
+:::
+
### conditionalAssign
Examples of **correct** code for this rule with the `"all"` and `{ "conditionalAssign": false }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { "conditionalAssign": false }] */
@@ -121,10 +129,14 @@ do; while ((foo = bar()))
for (;(a = b););
```
+:::
+
### returnAssign
Examples of **correct** code for this rule with the `"all"` and `{ "returnAssign": false }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { "returnAssign": false }] */
@@ -141,10 +153,14 @@ b => (b = 1);
b => b ? (c = d) : (c = e);
```
+:::
+
### nestedBinaryExpressions
Examples of **correct** code for this rule with the `"all"` and `{ "nestedBinaryExpressions": false }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { "nestedBinaryExpressions": false }] */
@@ -153,10 +169,14 @@ x = a + (b * c);
x = (a * b) / c;
```
+:::
+
### ignoreJSX
Examples of **correct** code for this rule with the `all` and `{ "ignoreJSX": "all" }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { ignoreJSX: "all" }] */
const Component = ()
@@ -167,16 +187,24 @@ const Component = (
)
```
+:::
+
Examples of **incorrect** code for this rule with the `all` and `{ "ignoreJSX": "multi-line" }` options:
+::: incorrect
+
```js
/* eslint no-extra-parens: ["error", "all", { ignoreJSX: "multi-line" }] */
const Component = ()
const Component = ()
```
+:::
+
Examples of **correct** code for this rule with the `all` and `{ "ignoreJSX": "multi-line" }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { ignoreJSX: "multi-line" }] */
const Component = (
@@ -191,8 +219,12 @@ const Component = (
)
```
+:::
+
Examples of **incorrect** code for this rule with the `all` and `{ "ignoreJSX": "single-line" }` options:
+::: incorrect
+
```js
/* eslint no-extra-parens: ["error", "all", { ignoreJSX: "single-line" }] */
const Component = (
@@ -207,18 +239,26 @@ const Component = (
)
```
+:::
+
Examples of **correct** code for this rule with the `all` and `{ "ignoreJSX": "single-line" }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { ignoreJSX: "single-line" }] */
const Component = ()
const Component = ()
```
+:::
+
### enforceForArrowConditionals
Examples of **correct** code for this rule with the `"all"` and `{ "enforceForArrowConditionals": false }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { "enforceForArrowConditionals": false }] */
@@ -226,10 +266,14 @@ const b = a => 1 ? 2 : 3;
const d = c => (1 ? 2 : 3);
```
+:::
+
### enforceForSequenceExpressions
Examples of **correct** code for this rule with the `"all"` and `{ "enforceForSequenceExpressions": false }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { "enforceForSequenceExpressions": false }] */
@@ -240,10 +284,14 @@ if ((val = foo(), val < 10)) {}
while ((val = foo(), val < 10));
```
+:::
+
### enforceForNewInMemberExpressions
Examples of **correct** code for this rule with the `"all"` and `{ "enforceForNewInMemberExpressions": false }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { "enforceForNewInMemberExpressions": false }] */
@@ -254,10 +302,14 @@ const quux = (new Bar())[baz];
(new Bar()).doSomething();
```
+:::
+
### enforceForFunctionPrototypeMethods
Examples of **correct** code for this rule with the `"all"` and `{ "enforceForFunctionPrototypeMethods": false }` options:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "all", { "enforceForFunctionPrototypeMethods": false }] */
@@ -270,10 +322,14 @@ const baz = (function () {}.call());
const quux = (function () {}.apply());
```
+:::
+
### functions
Examples of **incorrect** code for this rule with the `"functions"` option:
+::: incorrect
+
```js
/* eslint no-extra-parens: ["error", "functions"] */
@@ -282,8 +338,12 @@ Examples of **incorrect** code for this rule with the `"functions"` option:
var y = (function () {return 1;});
```
+:::
+
Examples of **correct** code for this rule with the `"functions"` option:
+::: correct
+
```js
/* eslint no-extra-parens: ["error", "functions"] */
@@ -303,3 +363,5 @@ a = (b * c);
typeof (a);
```
+
+:::
diff --git a/docs/src/rules/no-extra-semi.md b/docs/src/rules/no-extra-semi.md
index ae7b65e3697..65d32df2833 100644
--- a/docs/src/rules/no-extra-semi.md
+++ b/docs/src/rules/no-extra-semi.md
@@ -8,11 +8,9 @@ related_rules:
- semi-spacing
---
-
-
-Disallows unnecessary semicolons.
+
Typing mistakes and misunderstandings about where semicolons are required can lead to semicolons that are unnecessary. While not technically an error, extra semicolons can cause confusion when reading code.
@@ -22,6 +20,8 @@ This rule disallows unnecessary semicolons.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-extra-semi: "error"*/
@@ -44,8 +44,12 @@ class C {
};
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-extra-semi: "error"*/
@@ -72,6 +76,8 @@ class C {
}
```
+:::
+
## When Not To Use It
If you intentionally use extra semicolons then you can disable this rule.
diff --git a/docs/src/rules/no-extra-strict.md b/docs/src/rules/no-extra-strict.md
index 28dba6d8a97..4aa4fdcdc5c 100644
--- a/docs/src/rules/no-extra-strict.md
+++ b/docs/src/rules/no-extra-strict.md
@@ -28,6 +28,8 @@ This rule is aimed at preventing unnecessary `"use strict";` directives. As such
Example of **incorrect** code for this rule:
+::: incorrect
+
```js
"use strict";
@@ -37,8 +39,12 @@ Example of **incorrect** code for this rule:
}());
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
"use strict";
@@ -47,9 +53,15 @@ Examples of **correct** code for this rule:
}());
```
+:::
+
+::: correct
+
```js
(function () {
"use strict";
var foo = true;
}());
```
+
+:::
diff --git a/docs/src/rules/no-fallthrough.md b/docs/src/rules/no-fallthrough.md
index 96b92d8e1bb..446a8748093 100644
--- a/docs/src/rules/no-fallthrough.md
+++ b/docs/src/rules/no-fallthrough.md
@@ -7,9 +7,7 @@ related_rules:
- default-case
---
-
-Disallows case statement fallthroughs.
The `switch` statement in JavaScript is one of the more error-prone constructs of the language thanks in part to the ability to "fall through" from one `case` to the next. For example:
@@ -86,6 +84,8 @@ This rule is aimed at eliminating unintentional fallthrough of one case to the o
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-fallthrough: "error"*/
@@ -98,8 +98,12 @@ switch(foo) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-fallthrough: "error"*/
@@ -159,6 +163,8 @@ switch(foo) {
}
```
+:::
+
Note that the last `case` statement in these examples does not cause a warning because there is nothing to fall through into.
## Options
@@ -173,6 +179,8 @@ This rule has an object option:
Examples of **correct** code for the `{ "commentPattern": "break[\\s\\w]*omitted" }` option:
+::: correct
+
```js
/*eslint no-fallthrough: ["error", { "commentPattern": "break[\\s\\w]*omitted" }]*/
@@ -217,6 +225,7 @@ switch(foo){
}
```
+:::
## When Not To Use It
diff --git a/docs/src/rules/no-floating-decimal.md b/docs/src/rules/no-floating-decimal.md
index da348a152ac..02dea7d2060 100644
--- a/docs/src/rules/no-floating-decimal.md
+++ b/docs/src/rules/no-floating-decimal.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-floating
rule_type: suggestion
---
-
-Disallows leading or trailing decimal points in numeric literals.
Float values in JavaScript contain a decimal point, and there is no requirement that the decimal point be preceded or followed by a number. For example, the following are all valid JavaScript numbers:
@@ -25,6 +23,8 @@ This rule is aimed at eliminating floating decimal points and will warn whenever
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-floating-decimal: "error"*/
@@ -33,8 +33,12 @@ var num = 2.;
var num = -.7;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-floating-decimal: "error"*/
@@ -43,6 +47,8 @@ var num = 2.0;
var num = -0.7;
```
+:::
+
## When Not To Use It
If you aren't concerned about misinterpreting floating decimal point values, then you can safely turn this rule off.
diff --git a/docs/src/rules/no-func-assign.md b/docs/src/rules/no-func-assign.md
index cbd56279286..b98652c3aa1 100644
--- a/docs/src/rules/no-func-assign.md
+++ b/docs/src/rules/no-func-assign.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-func-ass
rule_type: problem
---
-
-Disallows reassigning `function` declarations.
JavaScript functions can be written as a FunctionDeclaration `function foo() { ... }` or as a FunctionExpression `var foo = function() { ... };`. While a JavaScript interpreter might tolerate it, overwriting/reassigning a function written as a FunctionDeclaration is often indicative of a mistake or issue.
@@ -22,6 +20,8 @@ This rule disallows reassigning `function` declarations.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-func-assign: "error"*/
@@ -37,8 +37,12 @@ var a = function hello() {
};
```
+:::
+
Examples of **incorrect** code for this rule, unlike the corresponding rule in JSHint:
+::: incorrect
+
```js
/*eslint no-func-assign: "error"*/
@@ -46,8 +50,12 @@ foo = bar;
function foo() {}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-func-assign: "error"*/
@@ -62,3 +70,5 @@ function foo() {
var foo = bar; // `foo` is shadowed.
}
```
+
+:::
diff --git a/docs/src/rules/no-global-assign.md b/docs/src/rules/no-global-assign.md
index 4e10466d272..e29789dc625 100644
--- a/docs/src/rules/no-global-assign.md
+++ b/docs/src/rules/no-global-assign.md
@@ -9,9 +9,7 @@ related_rules:
- no-shadow
---
-
-Disallows assignment to native objects or read-only global variables.
JavaScript environments contain a number of built-in global variables, such as `window` in browsers and `process` in Node.js. In almost all cases, you don't want to assign a value to these global variables as doing so could result in losing access to important functionality. For example, you probably don't want to do this in browser code:
@@ -32,6 +30,8 @@ ESLint has the capability to configure global variables as read-only.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-global-assign: "error"*/
@@ -39,6 +39,10 @@ Object = null
undefined = 1
```
+:::
+
+::: incorrect
+
```js
/*eslint no-global-assign: "error"*/
/*eslint-env browser*/
@@ -48,6 +52,10 @@ length = 1
top = 1
```
+:::
+
+::: incorrect
+
```js
/*eslint no-global-assign: "error"*/
/*global a:readonly*/
@@ -55,8 +63,12 @@ top = 1
a = 1
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-global-assign: "error"*/
@@ -65,6 +77,10 @@ var b = 1
b = 2
```
+:::
+
+::: correct
+
```js
/*eslint no-global-assign: "error"*/
/*eslint-env browser*/
@@ -72,6 +88,10 @@ b = 2
onload = function() {}
```
+:::
+
+::: correct
+
```js
/*eslint no-global-assign: "error"*/
/*global a:writable*/
@@ -79,6 +99,8 @@ onload = function() {}
a = 1
```
+:::
+
## Options
This rule accepts an `exceptions` option, which can be used to specify a list of builtins for which reassignments will be allowed:
diff --git a/docs/src/rules/no-implicit-coercion.md b/docs/src/rules/no-implicit-coercion.md
index cc1338c72fe..2739292eceb 100644
--- a/docs/src/rules/no-implicit-coercion.md
+++ b/docs/src/rules/no-implicit-coercion.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-implicit
rule_type: suggestion
---
-
-Disallows shorthand type conversions.
In JavaScript, there are a lot of different ways to convert value types.
Some of them might be hard to read and understand.
@@ -54,6 +52,8 @@ Note that operator `+` in `allow` list would allow `+foo` (number coercion) as w
Examples of **incorrect** code for the default `{ "boolean": true }` option:
+::: incorrect
+
```js
/*eslint no-implicit-coercion: "error"*/
@@ -62,8 +62,12 @@ var b = ~foo.indexOf(".");
// bitwise not is incorrect only with `indexOf`/`lastIndexOf` method calling.
```
+:::
+
Examples of **correct** code for the default `{ "boolean": true }` option:
+::: correct
+
```js
/*eslint no-implicit-coercion: "error"*/
@@ -73,10 +77,14 @@ var b = foo.indexOf(".") !== -1;
var n = ~foo; // This is a just bitwise not.
```
+:::
+
### number
Examples of **incorrect** code for the default `{ "number": true }` option:
+::: incorrect
+
```js
/*eslint no-implicit-coercion: "error"*/
@@ -84,8 +92,12 @@ var n = +foo;
var n = 1 * foo;
```
+:::
+
Examples of **correct** code for the default `{ "number": true }` option:
+::: correct
+
```js
/*eslint no-implicit-coercion: "error"*/
@@ -94,10 +106,14 @@ var n = parseFloat(foo);
var n = parseInt(foo, 10);
```
+:::
+
### string
Examples of **incorrect** code for the default `{ "string": true }` option:
+::: incorrect
+
```js
/*eslint no-implicit-coercion: "error"*/
@@ -107,8 +123,12 @@ foo += "";
foo += ``;
```
+:::
+
Examples of **correct** code for the default `{ "string": true }` option:
+::: correct
+
```js
/*eslint no-implicit-coercion: "error"*/
@@ -116,20 +136,28 @@ var s = String(foo);
foo = String(foo);
```
+:::
+
### disallowTemplateShorthand
This option is **not** affected by the `string` option.
Examples of **incorrect** code for the `{ "disallowTemplateShorthand": true }` option:
+::: incorrect
+
```js
/*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": true }]*/
var s = `${foo}`;
```
+:::
+
Examples of **correct** code for the `{ "disallowTemplateShorthand": true }` option:
+::: correct
+
```js
/*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": true }]*/
@@ -144,20 +172,28 @@ var s = `${foo}${bar}`;
var s = tag`${foo}`;
```
+:::
+
Examples of **correct** code for the default `{ "disallowTemplateShorthand": false }` option:
+::: correct
+
```js
/*eslint no-implicit-coercion: ["error", { "disallowTemplateShorthand": false }]*/
var s = `${foo}`;
```
+:::
+
### allow
Using `allow` list, we can override and allow specific operators.
Examples of **correct** code for the sample `{ "allow": ["!!", "~"] }` option:
+::: correct
+
```js
/*eslint no-implicit-coercion: [2, { "allow": ["!!", "~"] } ]*/
@@ -165,6 +201,8 @@ var b = !!foo;
var b = ~foo.indexOf(".");
```
+:::
+
## When Not To Use It
If you don't want to be notified about shorter notations for the type conversion, you can safely disable this rule.
diff --git a/docs/src/rules/no-implicit-globals.md b/docs/src/rules/no-implicit-globals.md
index 8c075ab62f7..ce942e91c8f 100644
--- a/docs/src/rules/no-implicit-globals.md
+++ b/docs/src/rules/no-implicit-globals.md
@@ -12,7 +12,6 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone
---
-Disallows declarations in the global scope.
It is the best practice to avoid 'polluting' the global scope with variables that are intended to be local to the script.
@@ -46,6 +45,8 @@ This rule disallows `var` and `function` declarations at the top-level script sc
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-implicit-globals: "error"*/
@@ -54,8 +55,12 @@ var foo = 1;
function bar() {}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-implicit-globals: "error"*/
@@ -71,8 +76,12 @@ window.bar = function() {};
})();
```
+:::
+
Examples of **correct** code for this rule with `"parserOptions": { "sourceType": "module" }` in the ESLint configuration:
+::: correct
+
```js
/*eslint no-implicit-globals: "error"*/
@@ -81,6 +90,8 @@ var foo = 1;
function bar() {}
```
+:::
+
### Global variable leaks
When the code is not in `strict` mode, an assignment to an undeclared variable creates
@@ -90,6 +101,8 @@ This does not apply to ES modules since the module code is implicitly in `strict
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-implicit-globals: "error"*/
@@ -100,6 +113,8 @@ Bar.prototype.baz = function () {
};
```
+:::
+
### Read-only global variables
This rule also disallows redeclarations of read-only global variables and assignments to read-only global variables.
@@ -113,6 +128,8 @@ or in a `/*global */` comment.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-implicit-globals: "error"*/
@@ -124,6 +141,8 @@ Array = [];
var Object;
```
+:::
+
### `const`, `let` and `class` declarations
Lexical declarations `const` and `let`, as well as `class` declarations, create variables that are block-scoped.
@@ -137,6 +156,8 @@ If the variable is intended to be local to the script, wrap the code with a bloc
Examples of **correct** code for this rule with `"lexicalBindings"` option set to `false` (default):
+::: correct
+
```js
/*eslint no-implicit-globals: ["error", {"lexicalBindings": false}]*/
@@ -147,8 +168,12 @@ let baz;
class Bar {}
```
+:::
+
Examples of **incorrect** code for this rule with `"lexicalBindings"` option set to `true`:
+::: incorrect
+
```js
/*eslint no-implicit-globals: ["error", {"lexicalBindings": true}]*/
@@ -159,8 +184,12 @@ let baz;
class Bar {}
```
+:::
+
Examples of **correct** code for this rule with `"lexicalBindings"` option set to `true`:
+::: correct
+
```js
/*eslint no-implicit-globals: ["error", {"lexicalBindings": true}]*/
@@ -177,6 +206,8 @@ Examples of **correct** code for this rule with `"lexicalBindings"` option set t
}());
```
+:::
+
If you intend to create a global `const` or `let` variable or a global `class` declaration, to be used from other scripts,
be aware that there are certain differences when compared to the traditional methods, which are `var` declarations and assigning to a property of the global `window` object:
@@ -191,6 +222,8 @@ Even the `typeof` check is not safe from TDZ reference exceptions.
Examples of **incorrect** code for this rule with `"lexicalBindings"` option set to `true`:
+::: incorrect
+
```js
/*eslint no-implicit-globals: ["error", {"lexicalBindings": true}]*/
@@ -203,8 +236,12 @@ const MyGlobalFunction = (function() {
}());
```
+:::
+
Examples of **correct** code for this rule with `"lexicalBindings"` option set to `true`:
+::: correct
+
```js
/*eslint no-implicit-globals: ["error", {"lexicalBindings": true}]*/
@@ -217,6 +254,8 @@ window.MyGlobalFunction = (function() {
}());
```
+:::
+
## When Not To Use It
In the case of a browser script, if you want to be able to explicitly declare variables and functions in the global scope,
diff --git a/docs/src/rules/no-implied-eval.md b/docs/src/rules/no-implied-eval.md
index 66596a9e56f..433c28360b3 100644
--- a/docs/src/rules/no-implied-eval.md
+++ b/docs/src/rules/no-implied-eval.md
@@ -7,7 +7,6 @@ related_rules:
- no-eval
---
-Disallows the use of `eval()`-like methods.
It's considered a good practice to avoid using `eval()` in JavaScript. There are security and performance implications involved with doing so, which is why many linters (including ESLint) recommend disallowing `eval()`. However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns.
@@ -34,6 +33,8 @@ This rule aims to eliminate implied `eval()` through the use of `setTimeout()`,
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-implied-eval: "error"*/
@@ -48,8 +49,12 @@ window.setTimeout("count = 5", 10);
window.setInterval("foo = bar", 10);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-implied-eval: "error"*/
@@ -62,6 +67,8 @@ setInterval(function() {
}, 100);
```
+:::
+
## When Not To Use It
If you want to allow `setTimeout()` and `setInterval()` with string arguments, then you can safely disable this rule.
diff --git a/docs/src/rules/no-import-assign.md b/docs/src/rules/no-import-assign.md
index 56844f47727..980d230a501 100644
--- a/docs/src/rules/no-import-assign.md
+++ b/docs/src/rules/no-import-assign.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-import-a
rule_type: problem
---
-
-Disallows assigning to imported bindings.
The updates of imported bindings by ES Modules cause runtime errors.
@@ -17,6 +15,8 @@ This rule warns the assignments, increments, and decrements of imported bindings
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-import-assign: "error"*/
@@ -31,8 +31,12 @@ mod_ns = {} // ERROR: 'mod_ns' is readonly.
Object.assign(mod_ns, { foo: "foo" }) // ERROR: The members of 'mod_ns' are readonly.
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-import-assign: "error"*/
@@ -50,6 +54,8 @@ function test(obj) {
test(mod_ns) // Not errored because it doesn't know that 'test' updates the member of the argument.
```
+:::
+
## When Not To Use It
If you don't want to be notified about modifying imported bindings, you can disable this rule.
diff --git a/docs/src/rules/no-inline-comments.md b/docs/src/rules/no-inline-comments.md
index 4ef95d8f154..4b2d9c3f92d 100644
--- a/docs/src/rules/no-inline-comments.md
+++ b/docs/src/rules/no-inline-comments.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-inline-c
rule_type: suggestion
---
-Disallows inline comments after code.
Some style guides disallow comments on the same line as code. Code can become difficult to read if comments immediately follow the code on the same line.
On the other hand, it is sometimes faster and more obvious to put comments immediately following code.
@@ -16,6 +15,8 @@ This rule disallows comments on the same line as code.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-inline-comments: "error"*/
@@ -31,8 +32,12 @@ function getRandomNumber(){
var c = 3; /* A block comment after code */
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-inline-comments: "error"*/
@@ -43,12 +48,16 @@ var bar = 5;
//This is a comment below a line of code
```
+:::
+
### JSX exception
Comments inside the curly braces in JSX are allowed to be on the same line as the braces, but only if they are not on the same line with other code, and the braces do not enclose an actual expression.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-inline-comments: "error"*/
@@ -63,8 +72,12 @@ var bar = (
);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-inline-comments: "error"*/
@@ -95,6 +108,8 @@ var quux = (
)
```
+:::
+
## Options
### ignorePattern
@@ -103,16 +118,24 @@ To make this rule ignore specific comments, set the `ignorePattern` option to a
Examples of **correct** code for the `ignorePattern` option:
+::: correct
+
```js
/*eslint no-inline-comments: ["error", { "ignorePattern": "webpackChunkName:\\s.+" }]*/
import(/* webpackChunkName: "my-chunk-name" */ './locale/en');
```
+:::
+
Examples of **incorrect** code for the `ignorePattern` option:
+::: incorrect
+
```js
/*eslint no-inline-comments: ["error", { "ignorePattern": "something" }] */
var foo = 4; // other thing
```
+
+:::
diff --git a/docs/src/rules/no-inner-declarations.md b/docs/src/rules/no-inner-declarations.md
index 5753d4107f5..3f126f4344d 100644
--- a/docs/src/rules/no-inner-declarations.md
+++ b/docs/src/rules/no-inner-declarations.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-inner-de
rule_type: problem
---
-
-Disallows variable or `function` declarations in nested blocks.
In JavaScript, prior to ES6, a function declaration is only allowed in the first level of a program or the body of another function, though parsers sometimes [erroneously accept them elsewhere](https://code.google.com/p/esprima/issues/detail?id=422). This only applies to function declarations; named or anonymous function expressions can occur anywhere an expression is permitted.
@@ -78,6 +76,8 @@ This rule has a string option:
Examples of **incorrect** code for this rule with the default `"functions"` option:
+::: incorrect
+
```js
/*eslint no-inner-declarations: "error"*/
@@ -102,8 +102,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"functions"` option:
+::: correct
+
```js
/*eslint no-inner-declarations: "error"*/
@@ -131,10 +135,14 @@ if (test) {
if (foo) var a;
```
+:::
+
### both
Examples of **incorrect** code for this rule with the `"both"` option:
+::: incorrect
+
```js
/*eslint no-inner-declarations: ["error", "both"]*/
@@ -161,8 +169,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `"both"` option:
+::: correct
+
```js
/*eslint no-inner-declarations: ["error", "both"]*/
@@ -183,6 +195,8 @@ class C {
}
```
+:::
+
## When Not To Use It
The function declaration portion rule will be rendered obsolete when [block-scoped functions](https://bugzilla.mozilla.org/show_bug.cgi?id=585536) land in ES6, but until then, it should be left on to enforce valid constructions. Disable checking variable declarations when using [block-scoped-var](block-scoped-var) or if declaring variables in nested blocks is acceptable despite hoisting.
diff --git a/docs/src/rules/no-invalid-regexp.md b/docs/src/rules/no-invalid-regexp.md
index 5c70b81aae1..42c8d7bf348 100644
--- a/docs/src/rules/no-invalid-regexp.md
+++ b/docs/src/rules/no-invalid-regexp.md
@@ -7,9 +7,7 @@ further_reading:
- https://es5.github.io/#x7.8.5
---
-
-Disallows invalid regular expression strings in `RegExp` constructors.
An invalid pattern in a regular expression literal is a `SyntaxError` when the code is parsed, but an invalid string in `RegExp` constructors throws a `SyntaxError` only when the code is executed.
@@ -19,6 +17,8 @@ This rule disallows invalid regular expression strings in `RegExp` constructors.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-invalid-regexp: "error"*/
@@ -29,8 +29,12 @@ RegExp('.', 'z')
new RegExp('\\')
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-invalid-regexp: "error"*/
@@ -41,6 +45,8 @@ new RegExp
this.RegExp('[')
```
+:::
+
Please note that this rule validates regular expressions per the latest ECMAScript specification, regardless of your parser settings.
If you want to allow additional constructor flags for any reason, you can specify them using the `allowConstructorFlags` option. These flags will then be ignored by the rule.
@@ -55,6 +61,8 @@ This rule has an object option for exceptions:
Examples of **correct** code for this rule with the `{ "allowConstructorFlags": ["a", "z"] }` option:
+::: correct
+
```js
/*eslint no-invalid-regexp: ["error", { "allowConstructorFlags": ["a", "z"] }]*/
@@ -62,3 +70,5 @@ new RegExp('.', 'a')
new RegExp('.', 'az')
```
+
+:::
diff --git a/docs/src/rules/no-invalid-this.md b/docs/src/rules/no-invalid-this.md
index 4358deedeee..2fb5ec8b63c 100644
--- a/docs/src/rules/no-invalid-this.md
+++ b/docs/src/rules/no-invalid-this.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-invalid-
rule_type: suggestion
---
-Disallows use of `this` in contexts where the value of `this` is `undefined`.
Under the strict mode, `this` keywords outside of classes or class-like objects might be `undefined` and raise a `TypeError`.
@@ -50,6 +49,8 @@ With `"parserOptions": { "sourceType": "module" }` in the ESLint configuration,
Examples of **incorrect** code for this rule in strict mode:
+::: incorrect
+
```js
/*eslint no-invalid-this: "error"*/
/*eslint-env es6*/
@@ -92,8 +93,12 @@ foo.forEach(function() {
});
```
+:::
+
Examples of **correct** code for this rule in strict mode:
+::: correct
+
```js
/*eslint no-invalid-this: "error"*/
/*eslint-env es6*/
@@ -222,6 +227,8 @@ function foo() {
}
```
+:::
+
## Options
This rule has an object option, with one option:
@@ -236,6 +243,8 @@ Set `"capIsConstructor"` to `false` if you want those functions to be treated as
Examples of **incorrect** code for this rule with `"capIsConstructor"` option set to `false`:
+::: incorrect
+
```js
/*eslint no-invalid-this: ["error", { "capIsConstructor": false }]*/
@@ -258,8 +267,12 @@ Baz = function() {
};
```
+:::
+
Examples of **correct** code for this rule with `"capIsConstructor"` option set to `false`:
+::: correct
+
```js
/*eslint no-invalid-this: ["error", { "capIsConstructor": false }]*/
@@ -271,6 +284,8 @@ obj.Foo = function Foo() {
};
```
+:::
+
## When Not To Use It
If you don't want to be notified about usage of `this` keyword outside of classes or class-like objects, you can safely disable this rule.
diff --git a/docs/src/rules/no-irregular-whitespace.md b/docs/src/rules/no-irregular-whitespace.md
index f470a893875..5996fb53021 100644
--- a/docs/src/rules/no-irregular-whitespace.md
+++ b/docs/src/rules/no-irregular-whitespace.md
@@ -8,9 +8,7 @@ further_reading:
- https://web.archive.org/web/20200414142829/http://timelessrepo.com/json-isnt-a-javascript-subset
---
-
-Disallows irregular whitespace characters.
Invalid or irregular whitespace causes issues with ECMAScript 5 parsers and also makes code harder to debug in a similar nature to mixed tabs and spaces.
@@ -32,30 +30,32 @@ This rule is aimed at catching invalid whitespace that is not a normal tab and s
This rule disallows the following characters except where the options allow:
- \u000B - Line Tabulation (\v) -
- \u000C - Form Feed (\f) -
- \u00A0 - No-Break Space -
- \u0085 - Next Line
- \u1680 - Ogham Space Mark
- \u180E - Mongolian Vowel Separator -
- \ufeff - Zero Width No-Break Space -
- \u2000 - En Quad
- \u2001 - Em Quad
- \u2002 - En Space -
- \u2003 - Em Space -
- \u2004 - Three-Per-Em
- \u2005 - Four-Per-Em
- \u2006 - Six-Per-Em
- \u2007 - Figure Space
- \u2008 - Punctuation Space -
- \u2009 - Thin Space
- \u200A - Hair Space
- \u200B - Zero Width Space -
- \u2028 - Line Separator
- \u2029 - Paragraph Separator
- \u202F - Narrow No-Break Space
- \u205f - Medium Mathematical Space
- \u3000 - Ideographic Space
+```text
+\u000B - Line Tabulation (\v) -
+\u000C - Form Feed (\f) -
+\u00A0 - No-Break Space -
+\u0085 - Next Line
+\u1680 - Ogham Space Mark
+\u180E - Mongolian Vowel Separator -
+\ufeff - Zero Width No-Break Space -
+\u2000 - En Quad
+\u2001 - Em Quad
+\u2002 - En Space -
+\u2003 - Em Space -
+\u2004 - Three-Per-Em
+\u2005 - Four-Per-Em
+\u2006 - Six-Per-Em
+\u2007 - Figure Space
+\u2008 - Punctuation Space -
+\u2009 - Thin Space
+\u200A - Hair Space
+\u200B - Zero Width Space -
+\u2028 - Line Separator
+\u2029 - Paragraph Separator
+\u202F - Narrow No-Break Space
+\u205f - Medium Mathematical Space
+\u3000 - Ideographic Space
+```
## Options
@@ -70,6 +70,8 @@ This rule has an object option for exceptions:
Examples of **incorrect** code for this rule with the default `{ "skipStrings": true }` option:
+::: incorrect
+
```js
/*eslint no-irregular-whitespace: "error"*/
@@ -115,8 +117,12 @@ function thing() {
}
```
+:::
+
Examples of **correct** code for this rule with the default `{ "skipStrings": true }` option:
+::: correct
+
```js
/*eslint no-irregular-whitespace: "error"*/
@@ -133,10 +139,14 @@ function thing() {
}
```
+:::
+
### skipComments
Examples of additional **correct** code for this rule with the `{ "skipComments": true }` option:
+::: correct
+
```js
/*eslint no-irregular-whitespace: ["error", { "skipComments": true }]*/
@@ -149,10 +159,14 @@ Description : some descriptive text
*/
```
+:::
+
### skipRegExps
Examples of additional **correct** code for this rule with the `{ "skipRegExps": true }` option:
+::: correct
+
```js
/*eslint no-irregular-whitespace: ["error", { "skipRegExps": true }]*/
@@ -161,10 +175,14 @@ function thing() {
}
```
+:::
+
### skipTemplates
Examples of additional **correct** code for this rule with the `{ "skipTemplates": true }` option:
+::: correct
+
```js
/*eslint no-irregular-whitespace: ["error", { "skipTemplates": true }]*/
/*eslint-env es6*/
@@ -174,6 +192,8 @@ function thing() {
}
```
+:::
+
## When Not To Use It
If you decide that you wish to use whitespace other than tabs and spaces outside of strings in your application.
diff --git a/docs/src/rules/no-iterator.md b/docs/src/rules/no-iterator.md
index 87aab8ce4e1..fba039adcbd 100644
--- a/docs/src/rules/no-iterator.md
+++ b/docs/src/rules/no-iterator.md
@@ -9,7 +9,6 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#Object_methods
---
-Disallows the use of the `__iterator__` property.
The `__iterator__` property was a SpiderMonkey extension to JavaScript that could be used to create custom iterators that are compatible with JavaScript's `for in` and `for each` constructs. However, this property is now obsolete, so it should not be used. Here's an example of how this used to work:
@@ -27,6 +26,8 @@ This rule is aimed at preventing errors that may arise from using the `__iterato
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-iterator: "error"*/
@@ -40,10 +41,16 @@ foo["__iterator__"] = function () {};
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-iterator: "error"*/
var __iterator__ = foo; // Not using the `__iterator__` property.
```
+
+:::
diff --git a/docs/src/rules/no-label-var.md b/docs/src/rules/no-label-var.md
index 3f98e2de32c..c0a1ec13c4c 100644
--- a/docs/src/rules/no-label-var.md
+++ b/docs/src/rules/no-label-var.md
@@ -9,7 +9,6 @@ related_rules:
- no-unused-labels
---
-Disallows labels that are variable names.
## Rule Details
@@ -17,6 +16,8 @@ This rule aims to create clearer code by disallowing the bad practice of creatin
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-label-var: "error"*/
@@ -29,8 +30,12 @@ x:
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-label-var: "error"*/
@@ -48,6 +53,8 @@ q:
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about usage of labels, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-labels.md b/docs/src/rules/no-labels.md
index 1165439538c..6df5f52fab6 100644
--- a/docs/src/rules/no-labels.md
+++ b/docs/src/rules/no-labels.md
@@ -9,7 +9,6 @@ related_rules:
- no-unused-labels
---
-Disallows labeled statements.
Labeled statements in JavaScript are used in conjunction with `break` and `continue` to control flow around multiple loops. For example:
@@ -33,6 +32,8 @@ This rule aims to eliminate the use of labeled statements in JavaScript. It will
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-labels: "error"*/
@@ -68,8 +69,12 @@ label:
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-labels: "error"*/
@@ -86,6 +91,8 @@ while (true) {
}
```
+:::
+
## Options
The options allow labels with loop or switch statements:
@@ -100,6 +107,8 @@ However, this way is ultra rare, not well-known, so this would be confusing deve
Examples of **correct** code for the `{ "allowLoop": true }` option:
+::: correct
+
```js
/*eslint no-labels: ["error", { "allowLoop": true }]*/
@@ -109,10 +118,14 @@ label:
}
```
+:::
+
### allowSwitch
Examples of **correct** code for the `{ "allowSwitch": true }` option:
+::: correct
+
```js
/*eslint no-labels: ["error", { "allowSwitch": true }]*/
@@ -123,6 +136,8 @@ label:
}
```
+:::
+
## When Not To Use It
If you need to use labeled statements everywhere, then you can safely disable this rule.
diff --git a/docs/src/rules/no-lone-blocks.md b/docs/src/rules/no-lone-blocks.md
index c3ee3c3d69f..8255b3dafba 100644
--- a/docs/src/rules/no-lone-blocks.md
+++ b/docs/src/rules/no-lone-blocks.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-lone-blo
rule_type: suggestion
---
-Disallows unnecessary nested blocks.
In JavaScript, prior to ES6, standalone code blocks delimited by curly braces do not create a new scope and have no use. For example, these curly braces do nothing to `foo`:
@@ -23,6 +22,8 @@ This rule aims to eliminate unnecessary and potentially confusing blocks at the
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-lone-blocks: "error"*/
@@ -59,8 +60,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with ES6 environment:
+::: correct
+
```js
/*eslint no-lone-blocks: "error"*/
/*eslint-env es6*/
@@ -107,8 +112,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with ES6 environment and strict mode via `"parserOptions": { "sourceType": "module" }` in the ESLint configuration or `"use strict"` directive in the code:
+::: correct
+
```js
/*eslint no-lone-blocks: "error"*/
/*eslint-env es6*/
@@ -119,3 +128,5 @@ Examples of **correct** code for this rule with ES6 environment and strict mode
function foo() {}
}
```
+
+:::
diff --git a/docs/src/rules/no-lonely-if.md b/docs/src/rules/no-lonely-if.md
index 8f62be51694..1ef30c57244 100644
--- a/docs/src/rules/no-lonely-if.md
+++ b/docs/src/rules/no-lonely-if.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-lonely-i
rule_type: suggestion
---
-
-Disallows `if` statements as the only statement in `else` blocks.
If an `if` statement is the only statement in the `else` block, it is often clearer to use an `else if` form.
@@ -37,6 +35,8 @@ This rule disallows `if` statements as the only statement in `else` blocks.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-lonely-if: "error"*/
@@ -59,8 +59,12 @@ if (condition) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-lonely-if: "error"*/
@@ -88,6 +92,8 @@ if (condition) {
}
```
+:::
+
## When Not To Use It
Disable this rule if the code is clearer without requiring the `else if` form.
diff --git a/docs/src/rules/no-loop-func.md b/docs/src/rules/no-loop-func.md
index 9ab8e60e480..e37fe82a1e0 100644
--- a/docs/src/rules/no-loop-func.md
+++ b/docs/src/rules/no-loop-func.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-loop-fun
rule_type: suggestion
---
-Disallows functions in loops.
Writing functions within loops tends to result in errors due to the way the function creates a closure around the loop. For example:
@@ -41,6 +40,8 @@ This rule disallows any function within a loop that contains unsafe references (
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-loop-func: "error"*/
/*eslint-env es6*/
@@ -73,8 +74,12 @@ for (let i = 0; i < 10; ++i) {
foo = 100;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-loop-func: "error"*/
/*eslint-env es6*/
@@ -102,3 +107,5 @@ for (let i=10; i; i--) {
}
//... no modifications of foo after this loop ...
```
+
+:::
diff --git a/docs/src/rules/no-loss-of-precision.md b/docs/src/rules/no-loss-of-precision.md
index b8a4050c529..3932866036e 100644
--- a/docs/src/rules/no-loss-of-precision.md
+++ b/docs/src/rules/no-loss-of-precision.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-loss-of-
rule_type: problem
---
-
-Disallows number literals that lose precision.
This rule would disallow the use of number literals that immediately lose precision at runtime when converted to a JS `Number` due to 64-bit floating-point rounding.
@@ -17,6 +15,8 @@ In JS, `Number`s are stored as double-precision floating-point numbers according
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-loss-of-precision: "error"*/
@@ -28,8 +28,12 @@ const x = 0X20000000000001
const x = 0X2_000000000_0001;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-loss-of-precision: "error"*/
@@ -41,3 +45,5 @@ const x = 0x1FFFFFFFFFFFFF
const x = 9007199254740991
const x = 9007_1992547409_91
```
+
+:::
diff --git a/docs/src/rules/no-magic-numbers.md b/docs/src/rules/no-magic-numbers.md
index f53d2e433b0..2f862575646 100644
--- a/docs/src/rules/no-magic-numbers.md
+++ b/docs/src/rules/no-magic-numbers.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-magic-nu
rule_type: suggestion
---
-Disallows magic numbers.
'Magic numbers' are numbers that occur multiple times in code without an explicit meaning.
They should preferably be replaced by named constants.
@@ -22,6 +21,8 @@ are declared as constants to make their meaning explicit.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-magic-numbers: "error"*/
@@ -29,6 +30,10 @@ var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * 0.25);
```
+:::
+
+::: incorrect
+
```js
/*eslint no-magic-numbers: "error"*/
@@ -37,6 +42,10 @@ var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
```
+:::
+
+::: incorrect
+
```js
/*eslint no-magic-numbers: "error"*/
@@ -45,8 +54,12 @@ var SECONDS;
SECONDS = 60;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-magic-numbers: "error"*/
@@ -56,6 +69,8 @@ var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
```
+:::
+
## Options
### ignore
@@ -68,6 +83,8 @@ If it's a string, the text must be parsed as `bigint` literal (e.g., `"100n"`).
Examples of **correct** code for the sample `{ "ignore": [1] }` option:
+::: correct
+
```js
/*eslint no-magic-numbers: ["error", { "ignore": [1] }]*/
@@ -75,14 +92,20 @@ var data = ['foo', 'bar', 'baz'];
var dataLast = data.length && data[data.length - 1];
```
+:::
+
Examples of **correct** code for the sample `{ "ignore": ["1n"] }` option:
+::: correct
+
```js
/*eslint no-magic-numbers: ["error", { "ignore": ["1n"] }]*/
foo(1n);
```
+:::
+
### ignoreArrayIndexes
A boolean to specify if numbers used in the context of array indexes (e.g., `data[2]`) are considered okay. `false` by default.
@@ -95,6 +118,8 @@ Additionally, since the maximum [array length](https://developer.mozilla.org/en-
Examples of **correct** code for the `{ "ignoreArrayIndexes": true }` option:
+::: correct
+
```js
/*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/
@@ -115,8 +140,12 @@ a = data[10n]; // same as data[10], 10n will be coerced to "10"
a = data[4294967294]; // max array index
```
+:::
+
Examples of **incorrect** code for the `{ "ignoreArrayIndexes": true }` option:
+::: incorrect
+
```js
/*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/
@@ -135,12 +164,16 @@ a = data[4294967295]; // above the max array index
a = data[1e500]; // same as data["Infinity"]
```
+:::
+
### ignoreDefaultValues
A boolean to specify if numbers used in default value assignments are considered okay. `false` by default.
Examples of **correct** code for the `{ "ignoreDefaultValues": true }` option:
+::: correct
+
```js
/*eslint no-magic-numbers: ["error", { "ignoreDefaultValues": true }]*/
@@ -149,6 +182,10 @@ const { tax = 0.25 } = accountancy;
function mapParallel(concurrency = 3) { /***/ }
```
+:::
+
+::: correct
+
```js
/*eslint no-magic-numbers: ["error", { "ignoreDefaultValues": true }]*/
@@ -156,12 +193,16 @@ let head;
[head = 100] = []
```
+:::
+
### enforceConst
A boolean to specify if we should check for the const keyword in variable declaration of numbers. `false` by default.
Examples of **incorrect** code for the `{ "enforceConst": true }` option:
+::: incorrect
+
```js
/*eslint no-magic-numbers: ["error", { "enforceConst": true }]*/
@@ -171,12 +212,16 @@ var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
```
+:::
+
### detectObjects
A boolean to specify if we should detect numbers when setting object properties for example. `false` by default.
Examples of **incorrect** code for the `{ "detectObjects": true }` option:
+::: incorrect
+
```js
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
@@ -188,8 +233,12 @@ var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
```
+:::
+
Examples of **correct** code for the `{ "detectObjects": true }` option:
+::: correct
+
```js
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
@@ -202,3 +251,5 @@ var magic = {
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
```
+
+:::
diff --git a/docs/src/rules/no-misleading-character-class.md b/docs/src/rules/no-misleading-character-class.md
index 005127abf48..a3d156a4a4c 100644
--- a/docs/src/rules/no-misleading-character-class.md
+++ b/docs/src/rules/no-misleading-character-class.md
@@ -5,9 +5,9 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-misleadi
rule_type: problem
---
-
-Disallows characters which are made with multiple code points in character class syntax.
+
+
Unicode includes the characters which are made with multiple code points.
RegExp character class syntax (`/[abc]/`) cannot handle characters which are made by multiple code points as a character; those characters will be dissolved to each code point. For example, `❇️` is made by `❇` (`U+2747`) and VARIATION SELECTOR-16 (`U+FE0F`). If this character is in RegExp character class, it will match to either `❇` (`U+2747`) or VARIATION SELECTOR-16 (`U+FE0F`) rather than `❇️`.
@@ -57,6 +57,8 @@ This rule reports the regular expressions which include multiple code point char
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-misleading-character-class: error */
@@ -68,8 +70,12 @@ Examples of **incorrect** code for this rule:
/^[👍]$/
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-misleading-character-class: error */
@@ -77,6 +83,8 @@ Examples of **correct** code for this rule:
/^[👍]$/u
```
+:::
+
## When Not To Use It
You can turn this rule off if you don't want to check RegExp character class syntax for multiple code point characters.
diff --git a/docs/src/rules/no-mixed-operators.md b/docs/src/rules/no-mixed-operators.md
index d47e47781dd..9db3066925e 100644
--- a/docs/src/rules/no-mixed-operators.md
+++ b/docs/src/rules/no-mixed-operators.md
@@ -7,7 +7,6 @@ related_rules:
- no-extra-parens
---
-Disallows mixes of different operators.
Enclosing complex expressions by parentheses clarifies the developer's intention, which makes the code more readable.
This rule warns when different operators are used consecutively without parentheses in an expression.
@@ -41,6 +40,8 @@ If you use both this and [no-extra-parens](no-extra-parens) rule together, you n
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-mixed-operators: "error"*/
@@ -48,8 +49,12 @@ var foo = a && b < 0 || c > 0 || d + 1 === 0;
var foo = a + b * c;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-mixed-operators: "error"*/
@@ -61,6 +66,8 @@ var foo = a + (b * c);
var foo = (a + b) * c;
```
+:::
+
## Options
```json
@@ -106,6 +113,8 @@ In this case, this rule checks if bitwise operators and logical operators are mi
Examples of **incorrect** code for this rule with `{"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}` option:
+::: incorrect
+
```js
/*eslint no-mixed-operators: ["error", {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}]*/
@@ -113,6 +122,10 @@ var foo = a && b < 0 || c > 0 || d + 1 === 0;
var foo = a & b | c;
```
+:::
+
+::: incorrect
+
```js
/*eslint no-mixed-operators: ["error", {"groups": [["&&", "||", "?:"]]}]*/
@@ -123,8 +136,12 @@ var bar = a ? b || c : d;
var baz = a ? b : c || d;
```
+:::
+
Examples of **correct** code for this rule with `{"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}` option:
+::: correct
+
```js
/*eslint no-mixed-operators: ["error", {"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}]*/
@@ -139,6 +156,10 @@ var foo = a + (b * c);
var foo = (a + b) * c;
```
+:::
+
+::: correct
+
```js
/*eslint no-mixed-operators: ["error", {"groups": [["&&", "||", "?:"]]}]*/
@@ -151,10 +172,14 @@ var baz = a ? b : (c || d);
var baz = (a ? b : c) || d;
```
+:::
+
### allowSamePrecedence
Examples of **correct** code for this rule with `{"allowSamePrecedence": true}` option:
+::: correct
+
```js
/*eslint no-mixed-operators: ["error", {"allowSamePrecedence": true}]*/
@@ -162,8 +187,12 @@ Examples of **correct** code for this rule with `{"allowSamePrecedence": true}`
var foo = a + b - c;
```
+:::
+
Examples of **incorrect** code for this rule with `{"allowSamePrecedence": false}` option:
+::: incorrect
+
```js
/*eslint no-mixed-operators: ["error", {"allowSamePrecedence": false}]*/
@@ -171,8 +200,12 @@ Examples of **incorrect** code for this rule with `{"allowSamePrecedence": false
var foo = a + b - c;
```
+:::
+
Examples of **correct** code for this rule with `{"allowSamePrecedence": false}` option:
+::: correct
+
```js
/*eslint no-mixed-operators: ["error", {"allowSamePrecedence": false}]*/
@@ -180,6 +213,8 @@ Examples of **correct** code for this rule with `{"allowSamePrecedence": false}`
var foo = (a + b) - c;
```
+:::
+
## When Not To Use It
If you don't want to be notified about mixed operators, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-mixed-requires.md b/docs/src/rules/no-mixed-requires.md
index 4137e9a66fb..6584e8fb7f1 100644
--- a/docs/src/rules/no-mixed-requires.md
+++ b/docs/src/rules/no-mixed-requires.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-mixed-re
rule_type: suggestion
---
-Disallows `require` calls to be mixed with regular variable declarations.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -46,6 +45,8 @@ Configuring this rule with one boolean option `true` is deprecated.
Examples of **incorrect** code for this rule with the default `{ "grouping": false, "allowCall": false }` options:
+::: incorrect
+
```js
/*eslint no-mixed-requires: "error"*/
@@ -57,8 +58,12 @@ var async = require('async'),
eslint = require('eslint');
```
+:::
+
Examples of **correct** code for this rule with the default `{ "grouping": false, "allowCall": false }` options:
+::: correct
+
```js
/*eslint no-mixed-requires: "error"*/
@@ -78,10 +83,14 @@ var foo = require('foo' + VERSION),
baz = require();
```
+:::
+
### grouping
Examples of **incorrect** code for this rule with the `{ "grouping": true }` option:
+::: incorrect
+
```js
/*eslint no-mixed-requires: ["error", { "grouping": true }]*/
@@ -94,10 +103,14 @@ var foo = require('foo'),
bar = require(getBarModuleName());
```
+:::
+
### allowCall
Examples of **incorrect** code for this rule with the `{ "allowCall": true }` option:
+::: incorrect
+
```js
/*eslint no-mixed-requires: ["error", { "allowCall": true }]*/
@@ -106,8 +119,12 @@ var async = require('async'),
eslint = require('eslint');
```
+:::
+
Examples of **correct** code for this rule with the `{ "allowCall": true }` option:
+::: correct
+
```js
/*eslint no-mixed-requires: ["error", { "allowCall": true }]*/
@@ -116,6 +133,8 @@ var async = require('async'),
eslint = require('eslint');
```
+:::
+
## Known Limitations
* The implementation is not aware of any local functions with the name `require` that may shadow Node.js' global `require`.
diff --git a/docs/src/rules/no-mixed-spaces-and-tabs.md b/docs/src/rules/no-mixed-spaces-and-tabs.md
index 2e7dc0cfccc..0dc791a9a35 100644
--- a/docs/src/rules/no-mixed-spaces-and-tabs.md
+++ b/docs/src/rules/no-mixed-spaces-and-tabs.md
@@ -7,9 +7,7 @@ further_reading:
- https://www.emacswiki.org/emacs/SmartTabs
---
-
-Disallows mixed spaces and tabs for indentation.
Most code conventions require either tabs or spaces be used for indentation. As such, it's usually an error if a single line of code is indented with both tabs and spaces.
@@ -19,6 +17,8 @@ This rule disallows mixed spaces and tabs for indentation.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-mixed-spaces-and-tabs: "error"*/
@@ -37,8 +37,12 @@ function main() {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-mixed-spaces-and-tabs: "error"*/
@@ -48,6 +52,8 @@ function add(x, y) {
}
```
+:::
+
## Options
This rule has a string option.
@@ -58,6 +64,8 @@ This rule has a string option.
Examples of **correct** code for this rule with the `"smart-tabs"` option:
+::: correct
+
```js
/*eslint no-mixed-spaces-and-tabs: ["error", "smart-tabs"]*/
@@ -69,3 +77,5 @@ function main() {
y = 7;
}
```
+
+:::
diff --git a/docs/src/rules/no-multi-assign.md b/docs/src/rules/no-multi-assign.md
index 34909f92c2b..a6b08849cb4 100644
--- a/docs/src/rules/no-multi-assign.md
+++ b/docs/src/rules/no-multi-assign.md
@@ -7,7 +7,6 @@ related_rules:
- max-statements-per-line
---
-Disallows use of chained assignment expressions.
Chaining the assignment of variables can lead to unexpected results and be difficult to read.
@@ -25,6 +24,8 @@ This rule disallows using multiple assignments within a single statement.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-multi-assign: "error"*/
@@ -43,8 +44,12 @@ class Foo {
a = b = "quux";
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-multi-assign: "error"*/
@@ -67,6 +72,8 @@ a = "quux";
b = "quux";
```
+:::
+
## Options
This rule has an object option:
@@ -77,6 +84,8 @@ This rule has an object option:
Examples of **correct** code for the `{ "ignoreNonDeclaration": true }` option:
+::: correct
+
```js
/*eslint no-multi-assign: ["error", { "ignoreNonDeclaration": true }]*/
@@ -89,8 +98,12 @@ const y = {};
x.one = y.one = 1;
```
+:::
+
Examples of **incorrect** code for the `{ "ignoreNonDeclaration": true }` option:
+::: incorrect
+
```js
/*eslint no-multi-assign: ["error", { "ignoreNonDeclaration": true }]*/
@@ -102,3 +115,5 @@ class Foo {
a = b = 10;
}
```
+
+:::
diff --git a/docs/src/rules/no-multi-spaces.md b/docs/src/rules/no-multi-spaces.md
index 373ef1ea4ec..e8a38dd96b9 100644
--- a/docs/src/rules/no-multi-spaces.md
+++ b/docs/src/rules/no-multi-spaces.md
@@ -13,9 +13,7 @@ related_rules:
- space-return-throw-case
---
-
-Disallows multiple consecutive spaces.
Multiple spaces in a row that are not used for indentation are typically mistakes. For example:
@@ -39,6 +37,8 @@ This rule aims to disallow multiple whitespace around logical expressions, condi
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-multi-spaces: "error"*/
@@ -53,8 +53,12 @@ var arr = [1, 2];
a ? b: c
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-multi-spaces: "error"*/
@@ -69,6 +73,8 @@ var arr = [1, 2];
a ? b: c
```
+:::
+
## Options
This rule's configuration consists of an object with the following properties:
@@ -80,6 +86,8 @@ This rule's configuration consists of an object with the following properties:
Examples of **incorrect** code for this rule with the `{ "ignoreEOLComments": false }` (default) option:
+::: incorrect
+
```js
/*eslint no-multi-spaces: ["error", { ignoreEOLComments: false }]*/
@@ -89,8 +97,12 @@ var x = 5; /* multiline
*/
```
+:::
+
Examples of **correct** code for this rule with the `{ "ignoreEOLComments": false }` (default) option:
+::: correct
+
```js
/*eslint no-multi-spaces: ["error", { ignoreEOLComments: false }]*/
@@ -100,8 +112,12 @@ var x = 5; /* multiline
*/
```
+:::
+
Examples of **correct** code for this rule with the `{ "ignoreEOLComments": true }` option:
+::: correct
+
```js
/*eslint no-multi-spaces: ["error", { ignoreEOLComments: true }]*/
@@ -115,6 +131,8 @@ var x = 5; /* multiline
*/
```
+:::
+
### exceptions
To avoid contradictions with other rules that require multiple spaces, this rule has an `exceptions` option to ignore certain nodes.
@@ -125,6 +143,8 @@ Only the `Property` node type is ignored by default, because for the [key-spacin
Examples of **correct** code for the default `"exceptions": { "Property": true }` option:
+::: correct
+
```js
/*eslint no-multi-spaces: "error"*/
/*eslint key-spacing: ["error", { align: "value" }]*/
@@ -135,8 +155,12 @@ var obj = {
};
```
+:::
+
Examples of **incorrect** code for the `"exceptions": { "Property": false }` option:
+::: incorrect
+
```js
/*eslint no-multi-spaces: ["error", { exceptions: { "Property": false } }]*/
/*eslint key-spacing: ["error", { align: "value" }]*/
@@ -147,16 +171,24 @@ var obj = {
};
```
+:::
+
Examples of **correct** code for the `"exceptions": { "BinaryExpression": true }` option:
+::: correct
+
```js
/*eslint no-multi-spaces: ["error", { exceptions: { "BinaryExpression": true } }]*/
var a = 1 * 2;
```
+:::
+
Examples of **correct** code for the `"exceptions": { "VariableDeclarator": true }` option:
+::: correct
+
```js
/*eslint no-multi-spaces: ["error", { exceptions: { "VariableDeclarator": true } }]*/
@@ -164,8 +196,12 @@ var someVar = 'foo';
var someOtherVar = 'barBaz';
```
+:::
+
Examples of **correct** code for the `"exceptions": { "ImportDeclaration": true }` option:
+::: correct
+
```js
/*eslint no-multi-spaces: ["error", { exceptions: { "ImportDeclaration": true } }]*/
@@ -173,6 +209,8 @@ import mod from 'mod';
import someOtherMod from 'some-other-mod';
```
+:::
+
## When Not To Use It
If you don't want to check and disallow multiple spaces, then you should turn this rule off.
diff --git a/docs/src/rules/no-multi-str.md b/docs/src/rules/no-multi-str.md
index caeb62defce..3548be839d8 100644
--- a/docs/src/rules/no-multi-str.md
+++ b/docs/src/rules/no-multi-str.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-multi-st
rule_type: suggestion
---
-Disallows multiline strings.
It's possible to create multiline strings in JavaScript by using a slash before a newline, such as:
@@ -22,6 +21,8 @@ This rule is aimed at preventing the use of multiline strings.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-multi-str: "error"*/
@@ -29,8 +30,12 @@ var x = "some very \
long text";
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-multi-str: "error"*/
@@ -39,3 +44,5 @@ var x = "some very long text";
var x = "some very " +
"long text";
```
+
+:::
diff --git a/docs/src/rules/no-multiple-empty-lines.md b/docs/src/rules/no-multiple-empty-lines.md
index 8da7a54dbce..5606beacf6c 100644
--- a/docs/src/rules/no-multiple-empty-lines.md
+++ b/docs/src/rules/no-multiple-empty-lines.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-multiple
rule_type: layout
---
-
-Disallows multiple empty lines.
Some developers prefer to have multiple blank lines removed, while others feel that it helps improve readability. Whitespace is useful for separating logical sections of code, but excess whitespace takes up more of the screen.
@@ -27,6 +25,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule with the default `{ "max": 2 }` option:
+::: incorrect
+
```js
/*eslint no-multiple-empty-lines: "error"*/
@@ -36,8 +36,12 @@ var foo = 5;
var bar = 3;
```
+:::
+
Examples of **correct** code for this rule with the default `{ "max": 2 }` option:
+::: correct
+
```js
/*eslint no-multiple-empty-lines: "error"*/
@@ -46,10 +50,14 @@ var foo = 5;
var bar = 3;
```
+:::
+
### maxEOF
Examples of **incorrect** code for this rule with the `{ max: 2, maxEOF: 0 }` options:
+::: incorrect
+
```js
/*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxEOF": 0 }]*/
@@ -59,8 +67,12 @@ var bar = 3;
```
+:::
+
Examples of **correct** code for this rule with the `{ max: 2, maxEOF: 0 }` options:
+::: correct
+
```js
/*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxEOF": 0 }]*/
@@ -69,6 +81,8 @@ var foo = 5;
var bar = 3;
```
+:::
+
**Note**: Although this ensures zero empty lines at the EOF, most editors will still show one empty line at the end if the file ends with a line break, as illustrated below. There is no empty line at the end of a file after the last `\n`, although editors may show an additional line. A true additional line would be represented by `\n\n`.
**Incorrect**:
@@ -100,6 +114,8 @@ var bar = 3;
Examples of **incorrect** code for this rule with the `{ max: 2, maxBOF: 1 }` options:
+::: incorrect
+
```js
/*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxBOF": 1 }]*/
@@ -108,8 +124,12 @@ var foo = 5;
var bar = 3;
```
+:::
+
Examples of **correct** code for this rule with the `{ max: 2, maxBOF: 1 }` options:
+::: correct
+
```js
/*eslint no-multiple-empty-lines: ["error", { "max": 2, "maxBOF": 1}]*/
@@ -118,6 +138,8 @@ var foo = 5;
var bar = 3;
```
+:::
+
## When Not To Use It
If you do not care about extra blank lines, turn this off.
diff --git a/docs/src/rules/no-native-reassign.md b/docs/src/rules/no-native-reassign.md
index ce6b557b18d..43772e027fc 100644
--- a/docs/src/rules/no-native-reassign.md
+++ b/docs/src/rules/no-native-reassign.md
@@ -9,7 +9,6 @@ related_rules:
- no-shadow
---
-Disallows reassignment of native objects.
This rule was **deprecated** in ESLint v3.3.0 and replaced by the [no-global-assign](no-global-assign) rule.
@@ -32,6 +31,8 @@ ESLint has the capability to configure global variables as read-only.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-native-reassign: "error"*/
@@ -39,6 +40,10 @@ Object = null
undefined = 1
```
+:::
+
+::: incorrect
+
```js
/*eslint no-native-reassign: "error"*/
/*eslint-env browser*/
@@ -48,6 +53,10 @@ length = 1
top = 1
```
+:::
+
+::: incorrect
+
```js
/*eslint no-native-reassign: "error"*/
/*global a:readonly*/
@@ -55,8 +64,12 @@ top = 1
a = 1
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-native-reassign: "error"*/
@@ -65,6 +78,10 @@ var b = 1
b = 2
```
+:::
+
+::: correct
+
```js
/*eslint no-native-reassign: "error"*/
/*eslint-env browser*/
@@ -72,6 +89,10 @@ b = 2
onload = function() {}
```
+:::
+
+::: correct
+
```js
/*eslint no-native-reassign: "error"*/
/*global a:writable*/
@@ -79,6 +100,8 @@ onload = function() {}
a = 1
```
+:::
+
## Options
This rule accepts an `exceptions` option, which can be used to specify a list of builtins for which reassignments will be allowed:
diff --git a/docs/src/rules/no-negated-condition.md b/docs/src/rules/no-negated-condition.md
index c6f62f0f08c..3c8ff950388 100644
--- a/docs/src/rules/no-negated-condition.md
+++ b/docs/src/rules/no-negated-condition.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-negated-
rule_type: suggestion
---
-Disallows negated conditions.
Negated conditions are more difficult to understand. Code can be made more readable by inverting the condition instead.
@@ -18,6 +17,8 @@ This rule disallows negated conditions in either of the following:
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-negated-condition: "error"*/
@@ -42,8 +43,12 @@ if (a !== b) {
!a ? c : b
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-negated-condition: "error"*/
@@ -63,3 +68,5 @@ if (a != b) {
a ? b : c
```
+
+:::
diff --git a/docs/src/rules/no-negated-in-lhs.md b/docs/src/rules/no-negated-in-lhs.md
index 052b863202d..02329fd2dfc 100644
--- a/docs/src/rules/no-negated-in-lhs.md
+++ b/docs/src/rules/no-negated-in-lhs.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-negated-
rule_type: problem
---
-Disallows negating the left operand in `in` expressions.
This rule was **deprecated** in ESLint v3.3.0 and replaced by the [no-unsafe-negation](no-unsafe-negation) rule.
@@ -17,6 +16,8 @@ This rule disallows negating the left operand in `in` expressions.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-negated-in-lhs: "error"*/
@@ -26,8 +27,12 @@ if(!key in object) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-negated-in-lhs: "error"*/
@@ -41,6 +46,8 @@ if(('' + !key) in object) {
}
```
+:::
+
## When Not To Use It
Never.
diff --git a/docs/src/rules/no-nested-ternary.md b/docs/src/rules/no-nested-ternary.md
index c1906cb1677..92e6a4124c0 100644
--- a/docs/src/rules/no-nested-ternary.md
+++ b/docs/src/rules/no-nested-ternary.md
@@ -8,7 +8,6 @@ related_rules:
- no-unneeded-ternary
---
-Disallows nested ternary expressions.
Nesting ternary expressions can make code more difficult to understand.
@@ -22,6 +21,8 @@ The `no-nested-ternary` rule disallows nested ternary expressions.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-nested-ternary: "error"*/
@@ -30,8 +31,12 @@ var thing = foo ? bar : baz === qux ? quxx : foobar;
foo ? baz === qux ? quxx() : foobar() : bar();
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-nested-ternary: "error"*/
@@ -47,3 +52,5 @@ if (foo) {
thing = foobar;
}
```
+
+:::
diff --git a/docs/src/rules/no-new-func.md b/docs/src/rules/no-new-func.md
index 28e663b4455..a82454440f1 100644
--- a/docs/src/rules/no-new-func.md
+++ b/docs/src/rules/no-new-func.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-new-func
rule_type: suggestion
---
-Disallows `new` operators with the `Function` object.
It's possible to create functions in JavaScript from strings at runtime using the `Function` constructor, such as:
@@ -25,6 +24,8 @@ This error is raised to highlight the use of a bad practice. By passing a string
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-new-func: "error"*/
@@ -36,8 +37,12 @@ var x = Function.bind(null, "a", "b", "return a + b")();
var f = Function.bind(null, "a", "b", "return a + b"); // assuming that the result of Function.bind(...) will be eventually called.
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-new-func: "error"*/
@@ -46,6 +51,8 @@ var x = function (a, b) {
};
```
+:::
+
## When Not To Use It
In more advanced cases where you really need to use the `Function` constructor.
diff --git a/docs/src/rules/no-new-object.md b/docs/src/rules/no-new-object.md
index 9655b13bbdb..fb007c89e41 100644
--- a/docs/src/rules/no-new-object.md
+++ b/docs/src/rules/no-new-object.md
@@ -8,7 +8,6 @@ related_rules:
- no-new-wrappers
---
-Disallows `new` operators with the `Object` object.
The `Object` constructor is used to create new generic objects in JavaScript, such as:
@@ -32,6 +31,8 @@ This rule disallows `Object` constructors.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-new-object: "error"*/
@@ -40,8 +41,12 @@ var myObject = new Object();
new Object();
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-new-object: "error"*/
@@ -53,6 +58,8 @@ var Object = function Object() {};
new Object();
```
+:::
+
## When Not To Use It
If you wish to allow the use of the `Object` constructor, you can safely turn this rule off.
diff --git a/docs/src/rules/no-new-require.md b/docs/src/rules/no-new-require.md
index 13500baec20..7b684ecf29b 100644
--- a/docs/src/rules/no-new-require.md
+++ b/docs/src/rules/no-new-require.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-new-requ
rule_type: suggestion
---
-Disallows `new` operators with calls to `require`.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -35,14 +34,20 @@ This rule aims to eliminate use of the `new require` expression.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-new-require: "error"*/
var appHeader = new require('app-header');
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-new-require: "error"*/
@@ -50,6 +55,8 @@ var AppHeader = require('app-header');
var appHeader = new AppHeader();
```
+:::
+
## When Not To Use It
If you are using a custom implementation of `require` and your code will never be used in projects where a standard `require` (CommonJS, Node.js, AMD) is expected, you can safely turn this rule off.
diff --git a/docs/src/rules/no-new-symbol.md b/docs/src/rules/no-new-symbol.md
index 461cdc8f054..d28383f1e2c 100644
--- a/docs/src/rules/no-new-symbol.md
+++ b/docs/src/rules/no-new-symbol.md
@@ -7,9 +7,7 @@ further_reading:
- https://www.ecma-international.org/ecma-262/6.0/#sec-symbol-objects
---
-
-Disallows `new` operators with the `Symbol` object.
`Symbol` is not intended to be used with the `new` operator, but to be called as a function.
@@ -27,6 +25,8 @@ This rule is aimed at preventing the accidental calling of `Symbol` with the `ne
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-new-symbol: "error"*/
/*eslint-env es6*/
@@ -34,8 +34,12 @@ Examples of **incorrect** code for this rule:
var foo = new Symbol('foo');
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-new-symbol: "error"*/
/*eslint-env es6*/
@@ -49,6 +53,8 @@ function bar(Symbol) {
```
+:::
+
## When Not To Use It
This rule should not be used in ES3/5 environments.
diff --git a/docs/src/rules/no-new-wrappers.md b/docs/src/rules/no-new-wrappers.md
index 174d27d9c02..ee5c8546d7f 100644
--- a/docs/src/rules/no-new-wrappers.md
+++ b/docs/src/rules/no-new-wrappers.md
@@ -10,7 +10,6 @@ further_reading:
- https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-3/wrapper-objects
---
-Disallows `new` operators with the `String`, `Number`, and `Boolean` objects.
There are three primitive types in JavaScript that have wrapper objects: string, number, and boolean. These are represented by the constructors `String`, `Number`, and `Boolean`, respectively. The primitive wrapper types are used whenever one of these primitive values is read, providing them with object-like capabilities such as methods. Behind the scenes, an object of the associated wrapper type is created and then destroyed, which is why you can call methods on primitive values, such as:
@@ -53,6 +52,8 @@ This rule aims to eliminate the use of `String`, `Number`, and `Boolean` with th
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-new-wrappers: "error"*/
@@ -65,8 +66,12 @@ var numberObject = new Number;
var booleanObject = new Boolean;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-new-wrappers: "error"*/
@@ -76,6 +81,8 @@ var num = Number(someValue);
var object = new MyString();
```
+:::
+
## When Not To Use It
If you want to allow the use of primitive wrapper objects, then you can safely disable this rule.
diff --git a/docs/src/rules/no-new.md b/docs/src/rules/no-new.md
index 41d46310df0..b62a2975943 100644
--- a/docs/src/rules/no-new.md
+++ b/docs/src/rules/no-new.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-new.md
rule_type: suggestion
---
-Disallows `new` operators outside of assignments or comparisons.
The goal of using `new` with a constructor is typically to create an object of a particular type and store that object in a variable, such as:
@@ -27,14 +26,20 @@ This rule is aimed at maintaining consistency and convention by disallowing cons
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-new: "error"*/
new Thing();
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-new: "error"*/
@@ -42,3 +47,5 @@ var thing = new Thing();
Thing();
```
+
+:::
diff --git a/docs/src/rules/no-nonoctal-decimal-escape.md b/docs/src/rules/no-nonoctal-decimal-escape.md
index 9fb530a7f0d..ba58cbf6386 100644
--- a/docs/src/rules/no-nonoctal-decimal-escape.md
+++ b/docs/src/rules/no-nonoctal-decimal-escape.md
@@ -9,11 +9,9 @@ further_reading:
- https://tc39.es/ecma262/#prod-annexB-NonOctalDecimalEscapeSequence
---
-
-
-Disallows `\8` and `\9` escape sequences in string literals.
+
Although not being specified in the language until ECMAScript 2021, `\8` and `\9` escape sequences in string literals were allowed in most JavaScript engines, and treated as "useless" escapes:
@@ -34,6 +32,8 @@ This rule disallows `\8` and `\9` escape sequences in string literals.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-nonoctal-decimal-escape: "error"*/
@@ -50,8 +50,12 @@ var baz = "Don't use \8 and \9 escapes.";
var quux = "\0\8";
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-nonoctal-decimal-escape: "error"*/
@@ -67,3 +71,5 @@ var baz = "Don't use \\8 and \\9 escapes.";
var quux = "\0\u0038";
```
+
+:::
diff --git a/docs/src/rules/no-obj-calls.md b/docs/src/rules/no-obj-calls.md
index cd5bb376afc..04cfe61b695 100644
--- a/docs/src/rules/no-obj-calls.md
+++ b/docs/src/rules/no-obj-calls.md
@@ -7,9 +7,7 @@ further_reading:
- https://es5.github.io/#x15.8
---
-
-Disallows calling global object properties as functions.
ECMAScript provides several global objects that are intended to be used as-is. Some of these objects look as if they could be constructors due their capitalization (such as `Math` and `JSON`) but will throw an error if you try to execute them as functions.
@@ -33,6 +31,8 @@ This rule also disallows using these objects as constructors with the `new` oper
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-obj-calls: "error"*/
/*eslint-env es2017*/
@@ -54,8 +54,12 @@ var atomics = Atomics();
var newAtomics = new Atomics();
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-obj-calls: "error"*/
/*eslint-env es2017*/
@@ -70,3 +74,5 @@ var value = Reflect.get({ x: 1, y: 2 }, "x");
var first = Atomics.load(foo, 0);
```
+
+:::
diff --git a/docs/src/rules/no-octal-escape.md b/docs/src/rules/no-octal-escape.md
index b6a06a4d7eb..366b3940b67 100644
--- a/docs/src/rules/no-octal-escape.md
+++ b/docs/src/rules/no-octal-escape.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-octal-es
rule_type: suggestion
---
-Disallows octal escape sequences in string literals.
As of the ECMAScript 5 specification, octal escape sequences in string literals are deprecated and should not be used. Unicode escape sequences should be used instead.
@@ -21,14 +20,20 @@ If ESLint parses code in strict mode, the parser (instead of this rule) reports
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-octal-escape: "error"*/
var foo = "Copyright \251";
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-octal-escape: "error"*/
@@ -36,3 +41,5 @@ var foo = "Copyright \u00A9"; // unicode
var foo = "Copyright \xA9"; // hexadecimal
```
+
+:::
diff --git a/docs/src/rules/no-octal.md b/docs/src/rules/no-octal.md
index 513ac64781a..cb86480d630 100644
--- a/docs/src/rules/no-octal.md
+++ b/docs/src/rules/no-octal.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-octal.md
rule_type: suggestion
---
-
-Disallows octal literals.
Octal literals are numerals that begin with a leading zero, such as:
@@ -25,6 +23,8 @@ If ESLint parses code in strict mode, the parser (instead of this rule) reports
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-octal: "error"*/
@@ -32,14 +32,20 @@ var num = 071;
var result = 5 + 07;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-octal: "error"*/
var num = "071";
```
+:::
+
## Compatibility
* **JSHint**: W115
diff --git a/docs/src/rules/no-param-reassign.md b/docs/src/rules/no-param-reassign.md
index 8ee3eb57337..694c861c109 100644
--- a/docs/src/rules/no-param-reassign.md
+++ b/docs/src/rules/no-param-reassign.md
@@ -7,7 +7,6 @@ further_reading:
- https://spin.atomicobject.com/2011/04/10/javascript-don-t-reassign-your-function-arguments/
---
-Disallows reassignment of function parameters.
Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the `arguments` object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.
@@ -19,6 +18,8 @@ This rule aims to prevent unintended behavior caused by modification or reassign
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-param-reassign: "error"*/
@@ -39,8 +40,12 @@ function foo(bar) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-param-reassign: "error"*/
@@ -49,6 +54,8 @@ function foo(bar) {
}
```
+:::
+
## Options
This rule takes one option, an object, with a boolean property `"props"`, and arrays `"ignorePropertyModificationsFor"` and `"ignorePropertyModificationsForRegex"`. `"props"` is `false` by default. If `"props"` is set to `true`, this rule warns against the modification of parameter properties unless they're included in `"ignorePropertyModificationsFor"` or `"ignorePropertyModificationsForRegex"`, which is an empty array by default.
@@ -57,6 +64,8 @@ This rule takes one option, an object, with a boolean property `"props"`, and a
Examples of **correct** code for the default `{ "props": false }` option:
+::: correct
+
```js
/*eslint no-param-reassign: ["error", { "props": false }]*/
@@ -81,8 +90,12 @@ function foo(bar) {
}
```
+:::
+
Examples of **incorrect** code for the `{ "props": true }` option:
+::: incorrect
+
```js
/*eslint no-param-reassign: ["error", { "props": true }]*/
@@ -107,8 +120,12 @@ function foo(bar) {
}
```
+:::
+
Examples of **correct** code for the `{ "props": true }` option with `"ignorePropertyModificationsFor"` set:
+::: correct
+
```js
/*eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsFor": ["bar"] }]*/
@@ -133,8 +150,12 @@ function foo(bar) {
}
```
+:::
+
Examples of **correct** code for the `{ "props": true }` option with `"ignorePropertyModificationsForRegex"` set:
+::: correct
+
```js
/*eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsForRegex": ["^bar"] }]*/
@@ -159,6 +180,8 @@ function foo(barBaz) {
}
```
+:::
+
## When Not To Use It
If you want to allow assignment to function parameters, then you can safely disable this rule.
diff --git a/docs/src/rules/no-path-concat.md b/docs/src/rules/no-path-concat.md
index e419526769c..c1887926d37 100644
--- a/docs/src/rules/no-path-concat.md
+++ b/docs/src/rules/no-path-concat.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-path-con
rule_type: suggestion
---
-Disallows string concatenation when using `__dirname` and `__filename`.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -37,6 +36,8 @@ This rule aims to prevent string concatenation of directory paths in Node.js
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-path-concat: "error"*/
@@ -46,14 +47,20 @@ var fullPath = __filename + "/foo.js";
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-path-concat: "error"*/
var fullPath = dirname + "/foo.js";
```
+:::
+
## When Not To Use It
If you want to allow string concatenation of path names.
diff --git a/docs/src/rules/no-plusplus.md b/docs/src/rules/no-plusplus.md
index 5f93853717f..4c1df56a7de 100644
--- a/docs/src/rules/no-plusplus.md
+++ b/docs/src/rules/no-plusplus.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-plusplus
rule_type: suggestion
---
-Disallows the unary operators `++` and `--`.
Because the unary `++` and `--` operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code.
@@ -34,6 +33,8 @@ This rule disallows the unary operators `++` and `--`.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-plusplus: "error"*/
@@ -48,8 +49,12 @@ for (i = 0; i < l; i++) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-plusplus: "error"*/
@@ -64,6 +69,8 @@ for (i = 0; i < l; i += 1) {
}
```
+:::
+
## Options
This rule has an object option.
@@ -74,6 +81,8 @@ This rule has an object option.
Examples of **correct** code for this rule with the `{ "allowForLoopAfterthoughts": true }` option:
+::: correct
+
```js
/*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/
@@ -90,8 +99,12 @@ for (i = 0, j = l; i < l; i++, j--) {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "allowForLoopAfterthoughts": true }` option:
+::: incorrect
+
```js
/*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/
@@ -105,3 +118,5 @@ for (i = l; i--;) {
for (i = 0; i < l;) i++;
```
+
+:::
diff --git a/docs/src/rules/no-process-env.md b/docs/src/rules/no-process-env.md
index f9223d46dc0..dd95ec90492 100644
--- a/docs/src/rules/no-process-env.md
+++ b/docs/src/rules/no-process-env.md
@@ -8,7 +8,6 @@ further_reading:
- https://blog.benhall.me.uk/2012/02/storing-application-config-data-in/
---
-Disallows the use of `process.env`.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -20,6 +19,8 @@ This rule is aimed at discouraging use of `process.env` to avoid global dependen
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-process-env: "error"*/
@@ -28,8 +29,12 @@ if(process.env.NODE_ENV === "development") {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-process-env: "error"*/
@@ -40,6 +45,8 @@ if(config.env === "development") {
}
```
+:::
+
## When Not To Use It
If you prefer to use `process.env` throughout your project to retrieve values from environment variables, then you can safely disable this rule.
diff --git a/docs/src/rules/no-process-exit.md b/docs/src/rules/no-process-exit.md
index 59913153395..8af40c50f90 100644
--- a/docs/src/rules/no-process-exit.md
+++ b/docs/src/rules/no-process-exit.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-process-
rule_type: suggestion
---
-Disallows the use of `process.exit()`.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -36,6 +35,8 @@ This rule aims to prevent the use of `process.exit()` in Node.js JavaScript. As
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-process-exit: "error"*/
@@ -43,8 +44,12 @@ process.exit(1);
process.exit(0);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-process-exit: "error"*/
@@ -52,6 +57,8 @@ Process.exit();
var exit = process.exit;
```
+:::
+
## When Not To Use It
There may be a part of a Node.js application that is responsible for determining the correct exit code to return upon exiting. In that case, you should turn this rule off to allow proper handling of the exit code.
diff --git a/docs/src/rules/no-promise-executor-return.md b/docs/src/rules/no-promise-executor-return.md
index 1a694603d69..ffbc12124e4 100644
--- a/docs/src/rules/no-promise-executor-return.md
+++ b/docs/src/rules/no-promise-executor-return.md
@@ -9,7 +9,6 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
---
-Disallows returning values from Promise executor functions.
The `new Promise` constructor accepts a single argument, called an *executor*.
@@ -37,6 +36,8 @@ Only `return` without a value is allowed, as it's a control flow statement.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-promise-executor-return: "error"*/
@@ -66,8 +67,12 @@ new Promise(() => {
});
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-promise-executor-return: "error"*/
@@ -97,3 +102,5 @@ new Promise((resolve, reject) => {
Promise.resolve(1);
```
+
+:::
diff --git a/docs/src/rules/no-proto.md b/docs/src/rules/no-proto.md
index 07ee394123f..c8c15e4f403 100644
--- a/docs/src/rules/no-proto.md
+++ b/docs/src/rules/no-proto.md
@@ -7,7 +7,6 @@ further_reading:
- https://johnresig.com/blog/objectgetprototypeof/
---
-Disallows the use of the `__proto__` property.
`__proto__` property has been deprecated as of ECMAScript 3.1 and shouldn't be used in the code. Use `Object.getPrototypeOf` and `Object.setPrototypeOf` instead.
@@ -17,6 +16,8 @@ When an object is created with the `new` operator, `__proto__` is set to the ori
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-proto: "error"*/
@@ -29,8 +30,12 @@ obj.__proto__ = b;
obj["__proto__"] = b;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-proto: "error"*/
@@ -41,6 +46,8 @@ Object.setPrototypeOf(obj, b);
var c = { __proto__: a };
```
+:::
+
## When Not To Use It
You might want to turn this rule off if you need to support legacy browsers which implement the
diff --git a/docs/src/rules/no-prototype-builtins.md b/docs/src/rules/no-prototype-builtins.md
index c2e9f1d8ecf..ece2bb9f1c1 100644
--- a/docs/src/rules/no-prototype-builtins.md
+++ b/docs/src/rules/no-prototype-builtins.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-prototyp
rule_type: problem
---
-
-Disallows calling some `Object.prototype` methods directly on objects.
In ECMAScript 5.1, `Object.create` was added, which enables the creation of objects with a specified `[[Prototype]]`. `Object.create(null)` is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from `Object.prototype`. This rule prevents calling some `Object.prototype` methods directly from an object.
@@ -21,6 +19,8 @@ This rule disallows calling some `Object.prototype` methods directly on object i
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-prototype-builtins: "error"*/
@@ -31,8 +31,12 @@ var isPrototypeOfBar = foo.isPrototypeOf(bar);
var barIsEnumerable = foo.propertyIsEnumerable("bar");
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-prototype-builtins: "error"*/
@@ -43,6 +47,8 @@ var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);
var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");
```
+:::
+
## When Not To Use It
You may want to turn this rule off if your code only touches objects with hardcoded keys, and you will never use an object that shadows an `Object.prototype` method or which does not inherit from `Object.prototype`.
diff --git a/docs/src/rules/no-redeclare.md b/docs/src/rules/no-redeclare.md
index 6a5de912090..141339a63c6 100644
--- a/docs/src/rules/no-redeclare.md
+++ b/docs/src/rules/no-redeclare.md
@@ -7,9 +7,7 @@ related_rules:
- no-shadow
---
-
-Disallows variable redeclarations.
In JavaScript, it's possible to redeclare the same variable name using `var`. This can lead to confusion as to where the variable is actually declared and initialized.
@@ -19,6 +17,8 @@ This rule is aimed at eliminating variables that have multiple declarations in t
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-redeclare: "error"*/
@@ -38,8 +38,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-redeclare: "error"*/
@@ -60,6 +64,8 @@ class C {
```
+:::
+
## Options
This rule takes one optional argument, an object with a boolean property `"builtinGlobals"`. It defaults to `true`.
@@ -71,14 +77,20 @@ The `"builtinGlobals"` option will check for redeclaration of built-in globals i
Examples of **incorrect** code for the `{ "builtinGlobals": true }` option:
+::: incorrect
+
```js
/*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/
var Object = 0;
```
+:::
+
Examples of **incorrect** code for the `{ "builtinGlobals": true }` option and the `browser` environment:
+::: incorrect
+
```js
/*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/
/*eslint-env browser*/
@@ -86,6 +98,8 @@ Examples of **incorrect** code for the `{ "builtinGlobals": true }` option and t
var top = 0;
```
+:::
+
The `browser` environment has many built-in global variables (for example, `top`). Some of built-in global variables cannot be redeclared.
Note that when using the `node` or `commonjs` environments (or `ecmaFeatures.globalReturn`, if using the default parser), the top scope of a program is not actually the global scope, but rather a "module" scope. When this is the case, declaring a variable named after a builtin global is not a redeclaration, but rather a shadowing of the global variable. In that case, the [`no-shadow`](no-shadow) rule with the `"builtinGlobals"` option should be used.
diff --git a/docs/src/rules/no-regex-spaces.md b/docs/src/rules/no-regex-spaces.md
index 8bb2133031b..f1c7b748b5a 100644
--- a/docs/src/rules/no-regex-spaces.md
+++ b/docs/src/rules/no-regex-spaces.md
@@ -8,11 +8,9 @@ related_rules:
- no-control-regex
---
-
-
-Disallows multiple spaces in regular expression literals.
+
Regular expressions can be very complex and difficult to understand, which is why it's important to keep them as simple as possible in order to avoid mistakes. One of the more error-prone things you can do with a regular expression is to use more than one space, such as:
@@ -34,6 +32,8 @@ This rule disallows multiple spaces in regular expression literals.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-regex-spaces: "error"*/
@@ -41,8 +41,12 @@ var re = /foo bar/;
var re = new RegExp("foo bar");
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-regex-spaces: "error"*/
@@ -50,6 +54,8 @@ var re = /foo {3}bar/;
var re = new RegExp("foo {3}bar");
```
+:::
+
## When Not To Use It
If you want to allow multiple spaces in a regular expression, then you can safely turn this rule off.
diff --git a/docs/src/rules/no-reserved-keys.md b/docs/src/rules/no-reserved-keys.md
index 8608eeb6060..66cc08e4317 100644
--- a/docs/src/rules/no-reserved-keys.md
+++ b/docs/src/rules/no-reserved-keys.md
@@ -29,6 +29,8 @@ This rule is aimed at eliminating the use of ECMAScript 3 keywords and reserved
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
var superman = {
class: "Superhero",
@@ -40,8 +42,12 @@ var values = {
};
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
var superman = {
"class": "Superhero",
@@ -53,6 +59,8 @@ var values = {
};
```
+:::
+
## When Not To Use It
If your code is only going to be executed in an ECMAScript 5 or higher environment, then you can safely leave this rule off.
diff --git a/docs/src/rules/no-restricted-exports.md b/docs/src/rules/no-restricted-exports.md
index e168c1cdca4..0136a1f6d19 100644
--- a/docs/src/rules/no-restricted-exports.md
+++ b/docs/src/rules/no-restricted-exports.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-restrict
rule_type: suggestion
---
-Disallows specified names in exports.
In a project, certain names may be disallowed from being used as exported names for various reasons.
@@ -23,6 +22,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-restricted-exports: ["error", {
"restrictedNamedExports": ["foo", "bar", "Baz", "a", "b", "c", "d", "e", "👍"]
@@ -49,8 +50,12 @@ export { something as e } from "some_module";
export { "👍" } from "some_module";
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-restricted-exports: ["error", {
"restrictedNamedExports": ["foo", "bar", "Baz", "a", "b", "c", "d", "e", "👍"]
@@ -77,12 +82,16 @@ export { something } from "some_module";
export { "👍" as thumbsUp } from "some_module";
```
+:::
+
### Default exports
By design, this rule doesn't disallow `export default` declarations. If you configure `"default"` as a restricted name, that restriction will apply only to named export declarations.
Examples of additional **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["default"] }]*/
@@ -91,20 +100,30 @@ function foo() {}
export { foo as default };
```
+:::
+
+::: incorrect
+
```js
/*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["default"] }]*/
export { default } from "some_module";
```
+:::
+
Examples of additional **correct** code for this rule:
+::: correct
+
```js
/*eslint no-restricted-exports: ["error", { "restrictedNamedExports": ["default", "foo"] }]*/
export default function foo() {}
```
+:::
+
## Known Limitations
This rule doesn't inspect the content of source modules in re-export declarations. In particular, if you are re-exporting everything from another module's export, that export may include a restricted name. This rule cannot detect such cases.
diff --git a/docs/src/rules/no-restricted-globals.md b/docs/src/rules/no-restricted-globals.md
index 4e9de8a0efd..a3f602beee6 100644
--- a/docs/src/rules/no-restricted-globals.md
+++ b/docs/src/rules/no-restricted-globals.md
@@ -8,7 +8,6 @@ related_rules:
- no-restricted-syntax
---
-Disallows specific global variables.
Disallowing usage of specific global variables can be useful if you want to allow a set of global
variables by enabling an environment, but still want to disallow some of those.
@@ -55,6 +54,8 @@ Alternatively, the rule also accepts objects, where the global name and an optio
Examples of **incorrect** code for sample `"event", "fdescribe"` global variable names:
+::: incorrect
+
```js
/*global event, fdescribe*/
/*eslint no-restricted-globals: ["error", "event", "fdescribe"]*/
@@ -67,8 +68,12 @@ fdescribe("foo", function() {
});
```
+:::
+
Examples of **correct** code for a sample `"event"` global variable name:
+::: correct
+
```js
/*global event*/
/*eslint no-restricted-globals: ["error", "event"]*/
@@ -76,6 +81,10 @@ Examples of **correct** code for a sample `"event"` global variable name:
import event from "event-module";
```
+:::
+
+::: correct
+
```js
/*global event*/
/*eslint no-restricted-globals: ["error", "event"]*/
@@ -83,8 +92,12 @@ import event from "event-module";
var event = 1;
```
+:::
+
Examples of **incorrect** code for a sample `"event"` global variable name, along with a custom error message:
+::: incorrect
+
```js
/*global event*/
/* eslint no-restricted-globals: ["error", { name: "event", message: "Use local parameter instead." }] */
@@ -93,3 +106,5 @@ function onClick() {
console.log(event); // Unexpected global variable 'event'. Use local parameter instead.
}
```
+
+:::
diff --git a/docs/src/rules/no-restricted-imports.md b/docs/src/rules/no-restricted-imports.md
index d4543c20e30..72768cd0d42 100644
--- a/docs/src/rules/no-restricted-imports.md
+++ b/docs/src/rules/no-restricted-imports.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-restrict
rule_type: suggestion
---
-Disallows specific imports.
Imports are an ES6/ES2015 standard for making the functionality of other modules available in your current module. In CommonJS this is implemented through the `require()` call which makes this ESLint rule roughly equivalent to its CommonJS counterpart `no-restricted-modules`.
@@ -109,6 +108,18 @@ Pattern matches can also be configured to be case-sensitive:
}]
```
+Pattern matches can restrict specific import names only, similar to the `paths` option:
+
+```json
+"no-restricted-imports": ["error", {
+ "patterns": [{
+ "group": ["utils/*"],
+ "importNames": ["isEmpty"],
+ "message": "Use 'isEmpty' from lodash instead."
+ }]
+}]
+```
+
To restrict the use of all Node.js core imports (via ):
```json
@@ -121,36 +132,58 @@ To restrict the use of all Node.js core imports (via
-Disallows assignments where both sides are exactly the same.
Self assignments have no effect, so probably those are an error due to incomplete refactoring.
Those indicate that what you should do is still remaining.
@@ -23,6 +21,8 @@ This rule is aimed at eliminating self assignments.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-self-assign: "error"*/
@@ -39,8 +39,12 @@ foo ||= foo;
foo ??= foo;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-self-assign: "error"*/
@@ -72,6 +76,8 @@ obj[a + b] = obj[a + b];
obj["a" + "b"] = obj["a" + "b"];
```
+:::
+
## Options
This rule has the option to check properties as well.
@@ -88,6 +94,8 @@ This rule has the option to check properties as well.
Examples of **correct** code with the `{ "props": false }` option:
+::: correct
+
```js
/*eslint no-self-assign: ["error", {"props": false}]*/
@@ -98,6 +106,8 @@ obj["a"] = obj["a"];
obj[a] = obj[a];
```
+:::
+
## When Not To Use It
If you don't want to notify about self assignments, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-self-compare.md b/docs/src/rules/no-self-compare.md
index 744fbd8818c..a0ba9bdd0cb 100644
--- a/docs/src/rules/no-self-compare.md
+++ b/docs/src/rules/no-self-compare.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-self-com
rule_type: problem
---
-Disallows comparisons where both sides are exactly the same.
Comparing a variable against itself is usually an error, either a typo or refactoring error. It is confusing to the reader and may potentially introduce a runtime error.
@@ -17,6 +16,8 @@ This error is raised to highlight a potentially confusing and potentially pointl
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-self-compare: "error"*/
@@ -25,3 +26,5 @@ if (x === x) {
x = 20;
}
```
+
+:::
diff --git a/docs/src/rules/no-sequences.md b/docs/src/rules/no-sequences.md
index cb17caa7ccf..6e9ab59d2e5 100644
--- a/docs/src/rules/no-sequences.md
+++ b/docs/src/rules/no-sequences.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-sequence
rule_type: suggestion
---
-Disallows use of the comma operator.
The comma operator includes multiple expressions where only one is expected. It evaluates each operand from left to right and returns the value of the last operand. However, this frequently obscures side effects, and its use is often an accident. Here are some examples of sequences:
@@ -28,6 +27,8 @@ This rule forbids the use of the comma operator, with the following exceptions:
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-sequences: "error"*/
@@ -48,8 +49,12 @@ while (val = foo(), val < 42);
with (doSomething(), val) {}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-sequences: "error"*/
@@ -70,12 +75,16 @@ while ((val = foo(), val < 42));
with ((doSomething(), val)) {}
```
+:::
+
### Note about arrow function bodies
If an arrow function body is a statement rather than a block, and that statement contains a sequence, you need to use double parentheses around the statement to indicate that the sequence is intentional.
Examples of **incorrect** code for arrow functions:
+::: incorrect
+
```js
/*eslint no-sequences: "error"*/
const foo = (val) => (console.log('bar'), val);
@@ -85,8 +94,12 @@ const foo = () => ((bar = 123), 10);
const foo = () => { return (bar = 123), 10 }
```
+:::
+
Examples of **correct** code for arrow functions:
+::: correct
+
```js
/*eslint no-sequences: "error"*/
const foo = (val) => ((console.log('bar'), val));
@@ -96,6 +109,8 @@ const foo = () => (((bar = 123), 10));
const foo = () => { return ((bar = 123), 10) }
```
+:::
+
## Options
This rule takes one option, an object, with the following properties:
@@ -106,6 +121,8 @@ This rule takes one option, an object, with the following properties:
Examples of **incorrect** code for this rule with the `{ "allowInParentheses": false }` option:
+::: incorrect
+
```js
/*eslint no-sequences: ["error", { "allowInParentheses": false }]*/
@@ -128,14 +145,20 @@ with ((doSomething(), val)) {}
const foo = (val) => ((console.log('bar'), val));
```
+:::
+
Examples of **correct** code for this rule with the `{ "allowInParentheses": false }` option:
+::: correct
+
```js
/*eslint no-sequences: ["error", { "allowInParentheses": false }]*/
for (i = 0, j = 10; i < j; i++, j--);
```
+:::
+
## When Not To Use It
Disable this rule if sequence expressions with the comma operator are acceptable.
diff --git a/docs/src/rules/no-setter-return.md b/docs/src/rules/no-setter-return.md
index b2dd68ed4ca..2538cd8f797 100644
--- a/docs/src/rules/no-setter-return.md
+++ b/docs/src/rules/no-setter-return.md
@@ -9,9 +9,7 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
---
-
-Disallows returning values from setters.
Setters cannot return values.
@@ -31,6 +29,8 @@ This rule checks setters in:
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-setter-return: "error"*/
@@ -68,8 +68,12 @@ Object.defineProperty(foo, "bar", {
});
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-setter-return: "error"*/
@@ -104,3 +108,5 @@ Object.defineProperty(foo, "bar", {
}
});
```
+
+:::
diff --git a/docs/src/rules/no-shadow-restricted-names.md b/docs/src/rules/no-shadow-restricted-names.md
index 95a8553ad34..64a00184d41 100644
--- a/docs/src/rules/no-shadow-restricted-names.md
+++ b/docs/src/rules/no-shadow-restricted-names.md
@@ -10,9 +10,7 @@ further_reading:
- https://es5.github.io/#C
---
-
-Disallows identifiers from shadowing restricted names.
ES5 §15.1.1 Value Properties of the Global Object (`NaN`, `Infinity`, `undefined`) as well as strict mode restricted identifiers `eval` and `arguments` are considered to be restricted names in JavaScript. Defining them to mean something else can have unintended consequences and confuse others reading the code. For example, there's nothing preventing you from writing:
@@ -26,6 +24,8 @@ Then any code used within the same scope would not get the global `undefined`, b
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-shadow-restricted-names: "error"*/
@@ -38,8 +38,12 @@ var undefined = 5;
try {} catch(eval){}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-shadow-restricted-names: "error"*/
@@ -50,3 +54,5 @@ function f(a, b){}
// Exception: `undefined` may be shadowed if the variable is never assigned a value.
var undefined;
```
+
+:::
diff --git a/docs/src/rules/no-shadow.md b/docs/src/rules/no-shadow.md
index fee157c5435..5d8ccf732e1 100644
--- a/docs/src/rules/no-shadow.md
+++ b/docs/src/rules/no-shadow.md
@@ -9,7 +9,6 @@ further_reading:
- https://en.wikipedia.org/wiki/Variable_shadowing
---
-Disallows variable declarations from shadowing variables declared in the outer scope.
Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. For example:
@@ -28,6 +27,8 @@ This rule aims to eliminate shadowed variable declarations.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-shadow: "error"*/
/*eslint-env es6*/
@@ -51,6 +52,8 @@ if (true) {
}
```
+:::
+
## Options
This rule takes one option, an object, with properties `"builtinGlobals"`, `"hoist"`, `"allow"` and `"ignoreOnInitialization"`.
@@ -68,6 +71,8 @@ If it is `true`, the rule prevents shadowing of built-in global variables: `Obje
Examples of **incorrect** code for the `{ "builtinGlobals": true }` option:
+::: incorrect
+
```js
/*eslint no-shadow: ["error", { "builtinGlobals": true }]*/
@@ -76,6 +81,8 @@ function foo() {
}
```
+:::
+
### hoist
The `hoist` option has three settings:
@@ -88,6 +95,8 @@ The `hoist` option has three settings:
Examples of **incorrect** code for the default `{ "hoist": "functions" }` option:
+::: incorrect
+
```js
/*eslint no-shadow: ["error", { "hoist": "functions" }]*/
/*eslint-env es6*/
@@ -99,10 +108,14 @@ if (true) {
function b() {}
```
+:::
+
Although `let b` in the `if` statement is before the *function* declaration in the outer scope, it is incorrect.
Examples of **correct** code for the default `{ "hoist": "functions" }` option:
+::: correct
+
```js
/*eslint no-shadow: ["error", { "hoist": "functions" }]*/
/*eslint-env es6*/
@@ -114,12 +127,16 @@ if (true) {
let a = 5;
```
+:::
+
Because `let a` in the `if` statement is before the *variable* declaration in the outer scope, it is correct.
#### hoist: all
Examples of **incorrect** code for the `{ "hoist": "all" }` option:
+::: incorrect
+
```js
/*eslint no-shadow: ["error", { "hoist": "all" }]*/
/*eslint-env es6*/
@@ -133,10 +150,14 @@ let a = 5;
function b() {}
```
+:::
+
#### hoist: never
Examples of **correct** code for the `{ "hoist": "never" }` option:
+::: correct
+
```js
/*eslint no-shadow: ["error", { "hoist": "never" }]*/
/*eslint-env es6*/
@@ -150,6 +171,8 @@ let a = 5;
function b() {}
```
+:::
+
Because `let a` and `let b` in the `if` statement are before the declarations in the outer scope, they are correct.
### allow
@@ -158,6 +181,8 @@ The `allow` option is an array of identifier names for which shadowing is allowe
Examples of **correct** code for the `{ "allow": ["done"] }` option:
+::: correct
+
```js
/*eslint no-shadow: ["error", { "allow": ["done"] }]*/
/*eslint-env es6*/
@@ -175,6 +200,8 @@ foo(function (err, result) {
});
```
+:::
+
### ignoreOnInitialization
The `ignoreOnInitialization` option is `false` by default. If it is `true`, it prevents reporting shadowing of variables in their initializers when the shadowed variable is presumably still uninitialized.
@@ -183,16 +210,22 @@ The shadowed variable must be on the left side. The shadowing variable must be o
Examples of **incorrect** code for the `{ "ignoreOnInitialization": "true" }` option:
+::: incorrect
+
```js
/*eslint no-shadow: ["error", { "ignoreOnInitialization": true }]*/
var x = x => x;
```
+:::
+
Because the shadowing variable `x` will shadow the already initialized shadowed variable `x`.
Examples of **correct** code for the `{ "ignoreOnInitialization": true }` option:
+::: correct
+
```js
/*eslint no-shadow: ["error", { "ignoreOnInitialization": true }]*/
@@ -201,4 +234,6 @@ var x = foo(x => x)
var y = (y => y)()
```
+:::
+
The rationale for callback functions is the assumption that they will be called during the initialization, so that at the time when the shadowing variable will be used, the shadowed variable has not yet been initialized.
diff --git a/docs/src/rules/no-space-before-semi.md b/docs/src/rules/no-space-before-semi.md
index 627003d3cda..03a39fe47a8 100644
--- a/docs/src/rules/no-space-before-semi.md
+++ b/docs/src/rules/no-space-before-semi.md
@@ -28,6 +28,8 @@ This rule prevents the use of spaces before a semicolon in expressions.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
var foo = "bar" ;
@@ -39,10 +41,16 @@ var foo = function() {
var foo = 1 + 2 ;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
;(function(){}());
var foo = "bar";
```
+
+:::
diff --git a/docs/src/rules/no-spaced-func.md b/docs/src/rules/no-spaced-func.md
index b06d81ae426..5858cea9b44 100644
--- a/docs/src/rules/no-spaced-func.md
+++ b/docs/src/rules/no-spaced-func.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-spaced-f
rule_type: layout
---
-
-Disallows spacing between function identifiers and their applications.
This rule was **deprecated** in ESLint v3.3.0 and replaced by the [func-call-spacing](func-call-spacing) rule.
@@ -19,6 +17,8 @@ This rule disallows spacing between function identifiers and their applications.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-spaced-func: "error"*/
@@ -28,10 +28,16 @@ fn
()
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-spaced-func: "error"*/
fn()
```
+
+:::
diff --git a/docs/src/rules/no-sparse-arrays.md b/docs/src/rules/no-sparse-arrays.md
index df061c50af5..d948d943b48 100644
--- a/docs/src/rules/no-sparse-arrays.md
+++ b/docs/src/rules/no-sparse-arrays.md
@@ -7,9 +7,7 @@ further_reading:
- https://www.nczonline.net/blog/2007/09/09/inconsistent-array-literals/
---
-
-Disallows sparse arrays.
Sparse arrays contain empty slots, most frequently due to multiple commas being used in an array literal, such as:
@@ -33,6 +31,8 @@ This rule disallows sparse array literals which have "holes" where commas are no
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-sparse-arrays: "error"*/
@@ -40,8 +40,12 @@ var items = [,];
var colors = [ "red",, "blue" ];
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-sparse-arrays: "error"*/
@@ -52,6 +56,8 @@ var items = new Array(23);
var colors = [ "red", "blue", ];
```
+:::
+
## When Not To Use It
If you want to use sparse arrays, then it is safe to disable this rule.
diff --git a/docs/src/rules/no-sync.md b/docs/src/rules/no-sync.md
index 2c839f42e64..1e48dd3bb8d 100644
--- a/docs/src/rules/no-sync.md
+++ b/docs/src/rules/no-sync.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-sync.md
rule_type: suggestion
---
-Disallows synchronous methods.
This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node).
@@ -21,6 +20,8 @@ This rule has an optional object option `{ allowAtRootLevel: }`, which
Examples of **incorrect** code for this rule with the default `{ allowAtRootLevel: false }` option:
+::: incorrect
+
```js
/*eslint no-sync: "error"*/
@@ -31,8 +32,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the default `{ allowAtRootLevel: false }` option:
+::: correct
+
```js
/*eslint no-sync: "error"*/
@@ -43,8 +48,12 @@ async(function() {
});
```
+:::
+
Examples of **incorrect** code for this rule with the `{ allowAtRootLevel: true }` option
+::: incorrect
+
```js
/*eslint no-sync: ["error", { allowAtRootLevel: true }]*/
@@ -55,14 +64,20 @@ function foo() {
var bar = baz => fs.readFileSync(qux);
```
+:::
+
Examples of **correct** code for this rule with the `{ allowAtRootLevel: true }` option
+::: correct
+
```js
/*eslint no-sync: ["error", { allowAtRootLevel: true }]*/
fs.readFileSync(somePath).toString();
```
+:::
+
## When Not To Use It
If you want to allow synchronous operations in your script, do not enable this rule.
diff --git a/docs/src/rules/no-tabs.md b/docs/src/rules/no-tabs.md
index fa26235ffce..756070950ef 100644
--- a/docs/src/rules/no-tabs.md
+++ b/docs/src/rules/no-tabs.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-tabs.md
rule_type: layout
---
-Disallows all tabs.
Some style guides don't allow the use of tab characters at all, including within comments.
@@ -15,6 +14,8 @@ This rule looks for tabs anywhere inside a file: code, comments or anything else
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
var a \t= 2;
@@ -26,8 +27,12 @@ function test(){}
var x = 1; // \t test
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
var a = 2;
@@ -39,6 +44,8 @@ function test(){}
var x = 1; // test
```
+:::
+
### Options
This rule has an optional object option with the following properties:
@@ -49,6 +56,8 @@ This rule has an optional object option with the following properties:
Examples of **correct** code for this rule with the `allowIndentationTabs: true` option:
+::: correct
+
```js
/* eslint no-tabs: ["error", { allowIndentationTabs: true }] */
@@ -59,6 +68,8 @@ function test() {
\t// comment with leading indentation tab
```
+:::
+
## When Not To Use It
If you have established a standard where having tabs is fine, then you can disable this rule.
diff --git a/docs/src/rules/no-template-curly-in-string.md b/docs/src/rules/no-template-curly-in-string.md
index 64b08187d94..ff968df3c97 100644
--- a/docs/src/rules/no-template-curly-in-string.md
+++ b/docs/src/rules/no-template-curly-in-string.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-template
rule_type: problem
---
-Disallows template literal placeholder syntax in regular strings.
ECMAScript 6 allows programmers to create strings containing variable or expressions using template literals, instead of string concatenation, by writing expressions like `${variable}` between two backtick quotes (\`). It can be easy to use the wrong quotes when wanting to use template literals, by writing `"${variable}"`, and end up with the literal value `"${variable}"` instead of a string containing the value of the injected expressions.
@@ -17,6 +16,8 @@ This rule aims to warn when a regular string contains what looks like a template
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-template-curly-in-string: "error"*/
"Hello ${name}!";
@@ -24,8 +25,12 @@ Examples of **incorrect** code for this rule:
"Time: ${12 * 60 * 60 * 1000}";
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-template-curly-in-string: "error"*/
`Hello ${name}!`;
@@ -34,6 +39,8 @@ Examples of **correct** code for this rule:
templateFunction`Hello ${name}`;
```
+:::
+
## When Not To Use It
This rule should not be used in ES3/5 environments.
diff --git a/docs/src/rules/no-ternary.md b/docs/src/rules/no-ternary.md
index 2f9eb38b32a..28c935c8b1b 100644
--- a/docs/src/rules/no-ternary.md
+++ b/docs/src/rules/no-ternary.md
@@ -8,7 +8,6 @@ related_rules:
- no-unneeded-ternary
---
-Disallows ternary operators.
The ternary operator is used to conditionally assign a value to a variable. Some believe that the use of ternary operators leads to unclear code.
@@ -22,6 +21,8 @@ This rule disallows ternary operators.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-ternary: "error"*/
@@ -32,8 +33,12 @@ function quux() {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-ternary: "error"*/
@@ -53,3 +58,5 @@ function quux() {
}
}
```
+
+:::
diff --git a/docs/src/rules/no-this-before-super.md b/docs/src/rules/no-this-before-super.md
index 7b679d85059..0493064867c 100644
--- a/docs/src/rules/no-this-before-super.md
+++ b/docs/src/rules/no-this-before-super.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-this-bef
rule_type: problem
---
-
-Disallows use of `this`/`super` before calling `super()` in constructors.
In the constructor of derived classes, if `this`/`super` are used before `super()` calls, it raises a reference error.
@@ -21,6 +19,8 @@ This rule is aimed to flag `this`/`super` keywords before `super()` callings.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-this-before-super: "error"*/
/*eslint-env es6*/
@@ -53,8 +53,12 @@ class A extends B {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-this-before-super: "error"*/
/*eslint-env es6*/
@@ -79,6 +83,8 @@ class A extends B {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about using `this`/`super` before `super()` in constructors, you can safely disable this rule.
diff --git a/docs/src/rules/no-throw-literal.md b/docs/src/rules/no-throw-literal.md
index 52d5ad44236..798d5c80eea 100644
--- a/docs/src/rules/no-throw-literal.md
+++ b/docs/src/rules/no-throw-literal.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-throw-li
rule_type: suggestion
---
-Restricts what can be thrown as an exception.
It is considered good practice to only `throw` the `Error` object itself or an object using the `Error` object as base objects for user-defined exceptions.
The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated.
@@ -18,6 +17,8 @@ This rule is aimed at maintaining consistency when throwing exception by disallo
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-throw-literal: "error"*/
/*eslint-env es6*/
@@ -39,8 +40,12 @@ throw `${err}`
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-throw-literal: "error"*/
@@ -58,12 +63,16 @@ try {
}
```
+:::
+
## Known Limitations
Due to the limits of static analysis, this rule cannot guarantee that you will only throw `Error` objects.
Examples of **correct** code for this rule, but which do not throw an `Error` object:
+::: correct
+
```js
/*eslint no-throw-literal: "error"*/
@@ -82,3 +91,5 @@ var foo = {
};
throw foo.bar;
```
+
+:::
diff --git a/docs/src/rules/no-trailing-spaces.md b/docs/src/rules/no-trailing-spaces.md
index 515e8ad6f8c..40e70c52ca1 100644
--- a/docs/src/rules/no-trailing-spaces.md
+++ b/docs/src/rules/no-trailing-spaces.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-trailing
rule_type: layout
---
-
-Disallows trailing whitespace at the end of lines.
Sometimes in the course of editing files, you can end up with extra whitespace at the end of lines. These whitespace differences can be picked up by source control systems and flagged as diffs, causing frustration for developers. While this extra whitespace causes no functional issues, many code conventions require that trailing spaces be removed before check-in.
@@ -17,6 +15,8 @@ This rule disallows trailing whitespace (spaces, tabs, and other Unicode whitesp
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-trailing-spaces: "error"*/
@@ -25,8 +25,12 @@ var baz = 5;//••
//•••••
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-trailing-spaces: "error"*/
@@ -34,6 +38,8 @@ var foo = 0;
var baz = 5;
```
+:::
+
## Options
This rule has an object option:
@@ -47,6 +53,8 @@ This rule has an object option:
Examples of **correct** code for this rule with the `{ "skipBlankLines": true }` option:
+::: correct
+
```js
/*eslint no-trailing-spaces: ["error", { "skipBlankLines": true }]*/
@@ -55,10 +63,14 @@ var baz = 5;
//•••••
```
+:::
+
### ignoreComments
Examples of **correct** code for this rule with the `{ "ignoreComments": true }` option:
+::: correct
+
```js
/*eslint no-trailing-spaces: ["error", { "ignoreComments": true }]*/
@@ -70,3 +82,5 @@ Examples of **correct** code for this rule with the `{ "ignoreComments": true }`
*•bar
*/
```
+
+:::
diff --git a/docs/src/rules/no-undef-init.md b/docs/src/rules/no-undef-init.md
index 84908ace717..6bfa7386c8f 100644
--- a/docs/src/rules/no-undef-init.md
+++ b/docs/src/rules/no-undef-init.md
@@ -8,9 +8,7 @@ related_rules:
- no-void
---
-
-Disallows initializing variables to `undefined`.
In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of `undefined`. For example:
@@ -34,6 +32,8 @@ This rule aims to eliminate `var` and `let` variable declarations that initializ
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-undef-init: "error"*/
@@ -41,8 +41,12 @@ var foo = undefined;
let bar = undefined;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-undef-init: "error"*/
@@ -50,10 +54,14 @@ var foo;
let bar;
```
+:::
+
Please note that this rule does not check `const` declarations, destructuring patterns, function parameters, and class fields.
Examples of additional **correct** code for this rule:
+::: correct
+
```js
/*eslint no-undef-init: "error"*/
@@ -70,12 +78,16 @@ class Foo {
}
```
+:::
+
## When Not To Use It
There is one situation where initializing to `undefined` behaves differently than omitting the initialization, and that's when a `var` declaration occurs inside of a loop. For example:
Example of **incorrect** code for this rule:
+::: incorrect
+
```js
for (i = 0; i < 10; i++) {
var x = undefined;
@@ -84,6 +96,8 @@ for (i = 0; i < 10; i++) {
}
```
+:::
+
In this case, the `var x` is hoisted out of the loop, effectively creating:
```js
@@ -123,6 +137,8 @@ If you're using such an initialization inside of a loop, then you should disable
Example of **correct** code for this rule, because it is disabled on a specific line:
+::: correct
+
```js
/*eslint no-undef-init: "error"*/
@@ -132,3 +148,5 @@ for (i = 0; i < 10; i++) {
x = i;
}
```
+
+:::
diff --git a/docs/src/rules/no-undef.md b/docs/src/rules/no-undef.md
index 6f153b94de8..e1e4c6780a2 100644
--- a/docs/src/rules/no-undef.md
+++ b/docs/src/rules/no-undef.md
@@ -8,18 +8,18 @@ related_rules:
- no-redeclare
---
-
-Disallows the use of undeclared variables unless mentioned in `/*global */` comments.
This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the `var` keyword in a `for` loop initializer).
## Rule Details
-Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a `/*global ...*/` comment, or specified in the [`globals` key in the configuration file](https://eslint.org/docs/user-guide/configuring#specifying-globals). A common use case for these is if you intentionally use globals that are defined elsewhere (e.g. in a script sourced from HTML).
+Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a `/*global ...*/` comment, or specified in the [`globals` key in the configuration file](../user-guide/configuring/language-options#using-configuration-files-1). A common use case for these is if you intentionally use globals that are defined elsewhere (e.g. in a script sourced from HTML).
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-undef: "error"*/
@@ -27,8 +27,12 @@ var foo = someFunction();
var bar = a + 1;
```
+:::
+
Examples of **correct** code for this rule with `global` declaration:
+::: correct
+
```js
/*global someFunction, a*/
/*eslint no-undef: "error"*/
@@ -37,6 +41,8 @@ var foo = someFunction();
var bar = a + 1;
```
+:::
+
Note that this rule does not disallow assignments to read-only global variables.
See [no-global-assign](no-global-assign) if you also want to disallow those assignments.
@@ -51,6 +57,8 @@ See [no-redeclare](no-redeclare) if you also want to disallow those redeclaratio
Examples of **correct** code for the default `{ "typeof": false }` option:
+::: correct
+
```js
/*eslint no-undef: "error"*/
@@ -59,18 +67,26 @@ if (typeof UndefinedIdentifier === "undefined") {
}
```
+:::
+
You can use this option if you want to prevent `typeof` check on a variable which has not been declared.
Examples of **incorrect** code for the `{ "typeof": true }` option:
+::: incorrect
+
```js
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
```
+:::
+
Examples of **correct** code for the `{ "typeof": true }` option with `global` declaration:
+::: correct
+
```js
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */
@@ -78,6 +94,8 @@ Examples of **correct** code for the `{ "typeof": true }` option with `global` d
if(typeof a === "string"){}
```
+:::
+
## Environments
For convenience, ESLint provides shortcuts that pre-define global variables exposed by popular libraries and runtime environments. This rule supports these environments, as listed in [Specifying Environments](../user-guide/configuring/language-options#specifying-environments). A few examples are given below.
@@ -86,6 +104,8 @@ For convenience, ESLint provides shortcuts that pre-define global variables expo
Examples of **correct** code for this rule with `browser` environment:
+::: correct
+
```js
/*eslint no-undef: "error"*/
/*eslint-env browser*/
@@ -95,10 +115,14 @@ setTimeout(function() {
});
```
+:::
+
### Node.js
Examples of **correct** code for this rule with `node` environment:
+::: correct
+
```js
/*eslint no-undef: "error"*/
/*eslint-env node*/
@@ -109,6 +133,8 @@ module.exports = function() {
};
```
+:::
+
## When Not To Use It
If explicit declaration of global variables is not to your taste.
diff --git a/docs/src/rules/no-undefined.md b/docs/src/rules/no-undefined.md
index 9398312a05a..e4c561b346e 100644
--- a/docs/src/rules/no-undefined.md
+++ b/docs/src/rules/no-undefined.md
@@ -14,7 +14,6 @@ further_reading:
- https://es5.github.io/#x15.1.1.3
---
-Disallows the use of `undefined` as an identifier.
The `undefined` variable in JavaScript is actually a property of the global object. As such, in ECMAScript 3 it was possible to overwrite the value of `undefined`. While ECMAScript 5 disallows overwriting `undefined`, it's still possible to shadow `undefined`, such as:
@@ -44,6 +43,8 @@ This rule aims to eliminate the use of `undefined`, and as such, generates a war
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-undefined: "error"*/
@@ -60,8 +61,12 @@ function foo(undefined) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-undefined: "error"*/
@@ -76,6 +81,8 @@ if (typeof foo === "undefined") {
global.undefined = "foo";
```
+:::
+
## When Not To Use It
If you want to allow the use of `undefined` in your code, then you can safely turn this rule off.
diff --git a/docs/src/rules/no-underscore-dangle.md b/docs/src/rules/no-underscore-dangle.md
index 15f082629e5..82c7af71720 100644
--- a/docs/src/rules/no-underscore-dangle.md
+++ b/docs/src/rules/no-underscore-dangle.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-undersco
rule_type: suggestion
---
-Disallows dangling underscores in identifiers.
As far as naming conventions for identifiers go, dangling underscores may be the most polarizing in JavaScript. Dangling underscores are underscores at either the beginning or end of an identifier, such as:
@@ -23,6 +22,8 @@ This rule disallows dangling underscores in identifiers.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-underscore-dangle: "error"*/
@@ -31,8 +32,12 @@ var __proto__ = {};
foo._bar();
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-underscore-dangle: "error"*/
@@ -45,6 +50,8 @@ const foo = { onClick(_bar) {} };
const foo = (_bar) => {};
```
+:::
+
## Options
This rule has an object option:
@@ -61,6 +68,8 @@ This rule has an object option:
Examples of additional **correct** code for this rule with the `{ "allow": ["foo_", "_bar"] }` option:
+::: correct
+
```js
/*eslint no-underscore-dangle: ["error", { "allow": ["foo_", "_bar"] }]*/
@@ -68,10 +77,14 @@ var foo_;
foo._bar();
```
+:::
+
### allowAfterThis
Examples of **correct** code for this rule with the `{ "allowAfterThis": true }` option:
+::: correct
+
```js
/*eslint no-underscore-dangle: ["error", { "allowAfterThis": true }]*/
@@ -79,10 +92,14 @@ var a = this.foo_;
this._bar();
```
+:::
+
### allowAfterSuper
Examples of **correct** code for this rule with the `{ "allowAfterSuper": true }` option:
+::: correct
+
```js
/*eslint no-underscore-dangle: ["error", { "allowAfterSuper": true }]*/
@@ -90,10 +107,14 @@ var a = super.foo_;
super._bar();
```
+:::
+
### allowAfterThisConstructor
Examples of **correct** code for this rule with the `{ "allowAfterThisConstructor": true }` option:
+::: correct
+
```js
/*eslint no-underscore-dangle: ["error", { "allowAfterThisConstructor": true }]*/
@@ -101,10 +122,14 @@ var a = this.constructor.foo_;
this.constructor._bar();
```
+:::
+
### enforceInMethodNames
Examples of **incorrect** code for this rule with the `{ "enforceInMethodNames": true }` option:
+::: incorrect
+
```js
/*eslint no-underscore-dangle: ["error", { "enforceInMethodNames": true }]*/
@@ -125,10 +150,14 @@ const o = {
};
```
+:::
+
### enforceInClassFields
Examples of **incorrect** code for this rule with the `{ "enforceInClassFields": true }` option:
+::: incorrect
+
```js
/*eslint no-underscore-dangle: ["error", { "enforceInClassFields": true }]*/
@@ -153,10 +182,14 @@ class Foo {
}
```
+:::
+
### allowFunctionParams
Examples of **incorrect** code for this rule with the `{ "allowFunctionParams": false }` option:
+::: incorrect
+
```js
/*eslint no-underscore-dangle: ["error", { "allowFunctionParams": false }]*/
@@ -173,6 +206,8 @@ const foo = (_bar = 0) => {};
const foo = (..._bar) => {};
```
+:::
+
## When Not To Use It
If you want to allow dangling underscores in identifiers, then you can safely turn this rule off.
diff --git a/docs/src/rules/no-unexpected-multiline.md b/docs/src/rules/no-unexpected-multiline.md
index cae4d74500d..5e27842c8e1 100644
--- a/docs/src/rules/no-unexpected-multiline.md
+++ b/docs/src/rules/no-unexpected-multiline.md
@@ -9,9 +9,7 @@ related_rules:
- space-unary-ops
---
-
-Disallows confusing multiline expressions.
Semicolons are usually optional in JavaScript, because of automatic semicolon insertion (ASI). You can require or disallow semicolons with the [semi](./semi) rule.
@@ -30,6 +28,8 @@ This rule disallows confusing multiline expressions where a newline looks like i
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unexpected-multiline: "error"*/
@@ -50,8 +50,12 @@ let x = foo
/regex/g.test(bar)
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unexpected-multiline: "error"*/
@@ -74,6 +78,8 @@ let tag = function() {}
tag `hello`
```
+:::
+
## When Not To Use It
You can turn this rule off if you are confident that you will not accidentally introduce code like this.
diff --git a/docs/src/rules/no-unmodified-loop-condition.md b/docs/src/rules/no-unmodified-loop-condition.md
index 154d7c05d0f..3deaa86122d 100644
--- a/docs/src/rules/no-unmodified-loop-condition.md
+++ b/docs/src/rules/no-unmodified-loop-condition.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-unmodifi
rule_type: problem
---
-Disallows unmodified conditions of loops.
Variables in a loop condition often are modified in the loop.
If not, it's possibly a mistake.
@@ -35,6 +34,8 @@ If a reference is inside of a dynamic expression (e.g. `CallExpression`,
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unmodified-loop-condition: "error"*/
@@ -54,8 +55,12 @@ while (node !== root) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unmodified-loop-condition: "error"*/
@@ -92,6 +97,8 @@ while (check(obj)) {
}
```
+:::
+
## When Not To Use It
If you don't want to notified about references inside of loop conditions, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-unneeded-ternary.md b/docs/src/rules/no-unneeded-ternary.md
index a9a8b540f62..6bd9d96ae8b 100644
--- a/docs/src/rules/no-unneeded-ternary.md
+++ b/docs/src/rules/no-unneeded-ternary.md
@@ -8,9 +8,7 @@ related_rules:
- no-nested-ternary
---
-
-Disallows ternary operators when simpler alternatives exist.
It's a common mistake in JavaScript to use a conditional expression to select between two Boolean values instead of using ! to convert the test to a Boolean.
Here are some examples:
@@ -46,6 +44,8 @@ This rule disallow ternary operators when simpler alternatives exist.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unneeded-ternary: "error"*/
@@ -54,8 +54,12 @@ var a = x === 2 ? true : false;
var a = x ? true : false;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unneeded-ternary: "error"*/
@@ -70,6 +74,8 @@ var a = x ? y : x;
f(x ? x : 1); // default assignment - would be disallowed if defaultAssignment option set to false. See option details below.
```
+:::
+
## Options
This rule has an object option:
@@ -83,6 +89,8 @@ When set to `true`, which it is by default, The defaultAssignment option allows
Examples of additional **incorrect** code for this rule with the `{ "defaultAssignment": false }` option:
+::: incorrect
+
```js
/*eslint no-unneeded-ternary: ["error", { "defaultAssignment": false }]*/
@@ -91,6 +99,8 @@ var a = x ? x : 1;
f(x ? x : 1);
```
+:::
+
Note that `defaultAssignment: false` still allows expressions of the form `x ? expr : x` (where the identifier is on the right hand side of the ternary).
## When Not To Use It
diff --git a/docs/src/rules/no-unreachable-loop.md b/docs/src/rules/no-unreachable-loop.md
index 8cdd64ee353..b5e79ef1d2a 100644
--- a/docs/src/rules/no-unreachable-loop.md
+++ b/docs/src/rules/no-unreachable-loop.md
@@ -10,7 +10,6 @@ related_rules:
- for-direction
---
-Disallows loops with a body that allows only one iteration.
A loop that can never reach the second iteration is a possible error in the code.
@@ -36,6 +35,8 @@ This rule checks `while`, `do-while`, `for`, `for-in` and `for-of` loops. You ca
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unreachable-loop: "error"*/
@@ -83,8 +84,12 @@ for (foo of bar) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unreachable-loop: "error"*/
@@ -132,10 +137,14 @@ for (foo of bar) {
}
```
+:::
+
Please note that this rule is not designed to check loop conditions, and will not warn in cases such as the following examples.
Examples of additional **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unreachable-loop: "error"*/
@@ -152,6 +161,8 @@ for (const a of [1]) {
}
```
+:::
+
## Options
This rule has an object option, with one option:
@@ -170,6 +181,8 @@ You can specify up to 5 different elements in the `"ignore"` array:
Examples of **correct** code for this rule with the `"ignore"` option:
+::: correct
+
```js
/*eslint no-unreachable-loop: ["error", { "ignore": ["ForInStatement", "ForOfStatement"] }]*/
@@ -181,6 +194,8 @@ for (var key in obj) {
for (const a of b) break;
```
+:::
+
## Known Limitations
Static code path analysis, in general, does not evaluate conditions. Due to this fact, this rule might miss reporting cases such as the following:
diff --git a/docs/src/rules/no-unreachable.md b/docs/src/rules/no-unreachable.md
index 2af7ae0407c..789815b1c03 100644
--- a/docs/src/rules/no-unreachable.md
+++ b/docs/src/rules/no-unreachable.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-unreacha
rule_type: problem
---
-
-Disallows unreachable code after `return`, `throw`, `continue`, and `break` statements.
Because the `return`, `throw`, `break`, and `continue` statements unconditionally exit a block of code, any statements after them cannot be executed. Unreachable statements are usually a mistake.
@@ -37,6 +35,8 @@ This rule disallows unreachable code after `return`, `throw`, `continue`, and `b
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unreachable: "error"*/
@@ -71,8 +71,12 @@ for (;;) {}
console.log("done");
```
+:::
+
Examples of **correct** code for this rule, because of JavaScript function and variable hoisting:
+::: correct
+
```js
/*eslint no-unreachable: "error"*/
@@ -95,8 +99,12 @@ switch (foo) {
}
```
+:::
+
Examples of additional **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unreachable: "error"*/
@@ -112,8 +120,12 @@ class C extends B {
}
```
+:::
+
Examples of additional **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unreachable: "error"*/
@@ -148,3 +160,5 @@ class F extends B {
}
}
```
+
+:::
diff --git a/docs/src/rules/no-unsafe-finally.md b/docs/src/rules/no-unsafe-finally.md
index 51b4afe2786..6451bc93706 100644
--- a/docs/src/rules/no-unsafe-finally.md
+++ b/docs/src/rules/no-unsafe-finally.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-unsafe-f
rule_type: problem
---
-
-Disallows control flow statements in `finally` blocks.
JavaScript suspends the control flow statements of `try` and `catch` blocks until the execution of `finally` block finishes. So, when `return`, `throw`, `break`, or `continue` is used in `finally`, control flow statements inside `try` and `catch` are overwritten, which is considered as unexpected behavior. Such as:
@@ -74,6 +72,8 @@ This rule disallows `return`, `throw`, `break`, and `continue` statements inside
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
@@ -87,6 +87,10 @@ let foo = function() {
};
```
+:::
+
+::: incorrect
+
```js
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
@@ -100,8 +104,12 @@ let foo = function() {
};
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
@@ -115,6 +123,10 @@ let foo = function() {
};
```
+:::
+
+::: correct
+
```js
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
@@ -130,6 +142,10 @@ let foo = function() {
};
```
+:::
+
+::: correct
+
```js
/*eslint no-unsafe-finally: "error"*/
let foo = function(a) {
@@ -148,6 +164,8 @@ let foo = function(a) {
};
```
+:::
+
## When Not To Use It
If you want to allow control flow operations in `finally` blocks, you can turn this rule off.
diff --git a/docs/src/rules/no-unsafe-negation.md b/docs/src/rules/no-unsafe-negation.md
index a9379d58bfd..3bbd5b8f5f3 100644
--- a/docs/src/rules/no-unsafe-negation.md
+++ b/docs/src/rules/no-unsafe-negation.md
@@ -5,11 +5,9 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-unsafe-n
rule_type: problem
---
-
-
-Disallows negating the left operand of relational operators.
+
Just as developers might type `-a + b` when they mean `-(a + b)` for the negative of a sum, they might type `!key in object` by mistake when they almost certainly mean `!(key in object)` to test that a key is not in an object. `!obj instanceof Ctor` is similar.
@@ -22,6 +20,8 @@ This rule disallows negating the left operand of the following relational operat
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unsafe-negation: "error"*/
@@ -36,8 +36,12 @@ if (!obj instanceof Ctor) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unsafe-negation: "error"*/
@@ -50,6 +54,8 @@ if (!(obj instanceof Ctor)) {
}
```
+:::
+
### Exception
For rare situations when negating the left operand is intended, this rule allows an exception.
@@ -57,6 +63,8 @@ If the whole negation is explicitly wrapped in parentheses, the rule will not re
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unsafe-negation: "error"*/
@@ -71,8 +79,12 @@ if(("" + !foo) in object) {
}
```
+:::
+
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unsafe-negation: "error"*/
@@ -81,6 +93,8 @@ if (!(foo) in object) {
}
```
+:::
+
## Options
This rule has an object option:
@@ -101,6 +115,8 @@ The purpose is to avoid expressions such as `! a < b` (which is equivalent to `(
Examples of additional **incorrect** code for this rule with the `{ "enforceForOrderingRelations": true }` option:
+::: incorrect
+
```js
/*eslint no-unsafe-negation: ["error", { "enforceForOrderingRelations": true }]*/
@@ -113,6 +129,8 @@ foo = ! a <= b;
foo = ! a >= b;
```
+:::
+
## When Not To Use It
If you don't want to notify unsafe logical negations, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-unsafe-optional-chaining.md b/docs/src/rules/no-unsafe-optional-chaining.md
index 879662df4ea..a04520df000 100644
--- a/docs/src/rules/no-unsafe-optional-chaining.md
+++ b/docs/src/rules/no-unsafe-optional-chaining.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-unsafe-o
rule_type: problem
---
-
-Disallows use of optional chaining in contexts where the `undefined` value is not allowed.
The optional chaining (`?.`) expression can short-circuit with a return value of `undefined`. Therefore, treating an evaluated optional chaining expression as a function, object, number, etc., can cause TypeError or unexpected results. For example:
@@ -36,6 +34,8 @@ This rule aims to detect some cases where the use of optional chaining doesn't p
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unsafe-optional-chaining: "error"*/
@@ -88,8 +88,12 @@ async function foo () {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unsafe-optional-chaining: "error"*/
@@ -120,6 +124,8 @@ async function foo () {
}
```
+:::
+
## Options
This rule has an object option:
@@ -136,6 +142,8 @@ With this option set to `true` the rule is enforced for:
Examples of additional **incorrect** code for this rule with the `{ "disallowArithmeticOperators": true }` option:
+::: incorrect
+
```js
/*eslint no-unsafe-optional-chaining: ["error", { "disallowArithmeticOperators": true }]*/
@@ -162,3 +170,5 @@ async function foo () {
baz += await obj?.foo;
}
```
+
+:::
diff --git a/docs/src/rules/no-unused-expressions.md b/docs/src/rules/no-unused-expressions.md
index fb69dbd4909..769f483527c 100644
--- a/docs/src/rules/no-unused-expressions.md
+++ b/docs/src/rules/no-unused-expressions.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-unused-e
rule_type: suggestion
---
-Disallows unused expressions.
An unused expression which has no effect on the state of the program indicates a logic error.
@@ -44,6 +43,8 @@ These options allow unused expressions *only if all* of the code paths either di
Examples of **incorrect** code for the default `{ "allowShortCircuit": false, "allowTernary": false }` options:
+::: incorrect
+
```js
/*eslint no-unused-expressions: "error"*/
@@ -69,8 +70,12 @@ injectGlobal`body{ color: red; }`
```
+:::
+
Examples of **correct** code for the default `{ "allowShortCircuit": false, "allowTernary": false }` options:
+::: correct
+
```js
/*eslint no-unused-expressions: "error"*/
@@ -93,10 +98,14 @@ delete a.b
void a
```
+:::
+
Note that one or more string expression statements (with or without semi-colons) will only be considered as unused if they are not in the beginning of a script, module, or function (alone and uninterrupted by other statements). Otherwise, they will be treated as part of a "directive prologue", a section potentially usable by JavaScript engines. This includes "strict mode" directives.
Examples of **correct** code for this rule in regard to directives:
+::: correct
+
```js
/*eslint no-unused-expressions: "error"*/
@@ -118,8 +127,12 @@ class Foo {
}
```
+:::
+
Examples of **incorrect** code for this rule in regard to directives:
+::: incorrect
+
```js
/*eslint no-unused-expressions: "error"*/
@@ -137,18 +150,26 @@ class Foo {
}
```
+:::
+
### allowShortCircuit
Examples of **incorrect** code for the `{ "allowShortCircuit": true }` option:
+::: incorrect
+
```js
/*eslint no-unused-expressions: ["error", { "allowShortCircuit": true }]*/
a || b
```
+:::
+
Examples of **correct** code for the `{ "allowShortCircuit": true }` option:
+::: correct
+
```js
/*eslint no-unused-expressions: ["error", { "allowShortCircuit": true }]*/
@@ -156,10 +177,14 @@ a && b()
a() || (b = c)
```
+:::
+
### allowTernary
Examples of **incorrect** code for the `{ "allowTernary": true }` option:
+::: incorrect
+
```js
/*eslint no-unused-expressions: ["error", { "allowTernary": true }]*/
@@ -167,8 +192,12 @@ a ? b : 0
a ? b : c()
```
+:::
+
Examples of **correct** code for the `{ "allowTernary": true }` option:
+::: correct
+
```js
/*eslint no-unused-expressions: ["error", { "allowTernary": true }]*/
@@ -176,40 +205,56 @@ a ? b() : c()
a ? (b = c) : d()
```
+:::
+
### allowShortCircuit and allowTernary
Examples of **correct** code for the `{ "allowShortCircuit": true, "allowTernary": true }` options:
+::: correct
+
```js
/*eslint no-unused-expressions: ["error", { "allowShortCircuit": true, "allowTernary": true }]*/
a ? b() || (c = d) : e()
```
+:::
+
### allowTaggedTemplates
Examples of **incorrect** code for the `{ "allowTaggedTemplates": true }` option:
+::: incorrect
+
```js
/*eslint no-unused-expressions: ["error", { "allowTaggedTemplates": true }]*/
`some untagged template string`;
```
+:::
+
Examples of **correct** code for the `{ "allowTaggedTemplates": true }` option:
+::: correct
+
```js
/*eslint no-unused-expressions: ["error", { "allowTaggedTemplates": true }]*/
tag`some tagged template string`;
```
+:::
+
### enforceForJSX
JSX is most-commonly used in the React ecosystem, where it is compiled to `React.createElement` expressions. Though free from side-effects, these calls are not automatically flagged by the `no-unused-expression` rule. If you're using React, or any other side-effect-free JSX pragma, this option can be enabled to flag these expressions.
Examples of **incorrect** code for the `{ "enforceForJSX": true }` option:
+::: incorrect
+
```jsx
/*eslint no-unused-expressions: ["error", { "enforceForJSX": true }]*/
@@ -218,8 +263,12 @@ Examples of **incorrect** code for the `{ "enforceForJSX": true }` option:
<>>;
```
+:::
+
Examples of **correct** code for the `{ "enforceForJSX": true }` option:
+::: correct
+
```jsx
/*eslint no-unused-expressions: ["error", { "enforceForJSX": true }]*/
@@ -227,3 +276,5 @@ var myComponentPartial = ;
var myFragment = <>>;
```
+
+:::
diff --git a/docs/src/rules/no-unused-labels.md b/docs/src/rules/no-unused-labels.md
index 6bdc389b4f0..5ebd95ca233 100644
--- a/docs/src/rules/no-unused-labels.md
+++ b/docs/src/rules/no-unused-labels.md
@@ -9,11 +9,9 @@ related_rules:
- no-label-var
---
-
-
-Disallows unused labels.
+
Labels that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring.
@@ -36,6 +34,8 @@ This rule is aimed at eliminating unused labels.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unused-labels: "error"*/
@@ -51,8 +51,12 @@ for (let i = 0; i < 10; ++i) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unused-labels: "error"*/
@@ -72,6 +76,8 @@ for (let i = 0; i < 10; ++i) {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about unused labels, then it's safe to disable this rule.
diff --git a/docs/src/rules/no-unused-private-class-members.md b/docs/src/rules/no-unused-private-class-members.md
index c3852c5aab3..f277c677eb8 100644
--- a/docs/src/rules/no-unused-private-class-members.md
+++ b/docs/src/rules/no-unused-private-class-members.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-unused-p
rule_type: problem
---
-Disallows unused private class members.
Private class members that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such class members take up space in the code and can lead to confusion by readers.
@@ -18,6 +17,8 @@ This rule reports unused private class members.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unused-private-class-members: "error"*/
@@ -49,8 +50,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unused-private-class-members: "error"*/
@@ -80,6 +85,8 @@ class Foo {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about unused private class members, you can safely turn this rule off.
diff --git a/docs/src/rules/no-unused-vars.md b/docs/src/rules/no-unused-vars.md
index cea0d7f1ccd..06a83cab24c 100644
--- a/docs/src/rules/no-unused-vars.md
+++ b/docs/src/rules/no-unused-vars.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-unused-v
rule_type: problem
---
-
-Disallows unused variables.
Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
@@ -26,6 +24,8 @@ A variable is *not* considered to be used if it is only ever declared (`var foo
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-unused-vars: "error"*/
/*global some_unused_var*/
@@ -60,8 +60,12 @@ function getY([x, y]) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-unused-vars: "error"*/
@@ -89,6 +93,8 @@ function getY([, y]) {
}
```
+:::
+
### exported
In environments outside of CommonJS or ECMAScript modules, you may use `var` to create a global variable that may be used by other scripts. You can use the `/* exported variableName */` comment block to indicate that this variable is being exported and therefore should not be considered unused.
@@ -103,12 +109,16 @@ The line comment `// exported variableName` will not work as `exported` is not l
Examples of **correct** code for `/* exported variableName */` operation:
+::: correct
+
```js
/* exported global_var */
var global_var = 42;
```
+:::
+
## Options
This rule takes one argument which can be a string or an object. The string settings are the same as those of the `vars` property (explained below).
@@ -134,6 +144,8 @@ The `vars` option has two settings:
Examples of **correct** code for the `{ "vars": "local" }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", { "vars": "local" }]*/
/*global some_unused_var */
@@ -141,12 +153,16 @@ Examples of **correct** code for the `{ "vars": "local" }` option:
some_unused_var = 42;
```
+:::
+
### varsIgnorePattern
The `varsIgnorePattern` option specifies exceptions not to check for usage: variables whose names match a regexp pattern. For example, variables whose names contain `ignored` or `Ignored`.
Examples of **correct** code for the `{ "varsIgnorePattern": "[iI]gnored" }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", { "varsIgnorePattern": "[iI]gnored" }]*/
@@ -155,6 +171,8 @@ var secondVar = 2;
console.log(secondVar);
```
+:::
+
### args
The `args` option has three settings:
@@ -167,6 +185,8 @@ The `args` option has three settings:
Examples of **incorrect** code for the default `{ "args": "after-used" }` option:
+::: incorrect
+
```js
/*eslint no-unused-vars: ["error", { "args": "after-used" }]*/
@@ -178,8 +198,12 @@ Examples of **incorrect** code for the default `{ "args": "after-used" }` option
})();
```
+:::
+
Examples of **correct** code for the default `{ "args": "after-used" }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", {"args": "after-used"}]*/
@@ -188,10 +212,14 @@ Examples of **correct** code for the default `{ "args": "after-used" }` option:
})();
```
+:::
+
#### args: all
Examples of **incorrect** code for the `{ "args": "all" }` option:
+::: incorrect
+
```js
/*eslint no-unused-vars: ["error", { "args": "all" }]*/
@@ -203,10 +231,14 @@ Examples of **incorrect** code for the `{ "args": "all" }` option:
})();
```
+:::
+
#### args: none
Examples of **correct** code for the `{ "args": "none" }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", { "args": "none" }]*/
@@ -215,12 +247,16 @@ Examples of **correct** code for the `{ "args": "none" }` option:
})();
```
+:::
+
### ignoreRestSiblings
The `ignoreRestSiblings` option is a boolean (default: `false`). Using a [Rest Property](https://github.com/tc39/proposal-object-rest-spread) it is possible to "omit" properties from an object, but by default the sibling properties are marked as "unused". With this option enabled the rest property's siblings are ignored.
Examples of **correct** code for the `{ "ignoreRestSiblings": true }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/
// 'foo' and 'bar' were ignored because they have a rest property sibling.
@@ -230,12 +266,16 @@ var bar;
({ bar, ...coords } = data);
```
+:::
+
### argsIgnorePattern
The `argsIgnorePattern` option specifies exceptions not to check for usage: arguments whose names match a regexp pattern. For example, variables whose names begin with an underscore.
Examples of **correct** code for the `{ "argsIgnorePattern": "^_" }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_" }]*/
@@ -245,12 +285,16 @@ function foo(x, _y) {
foo();
```
+:::
+
### destructuredArrayIgnorePattern
The `destructuredArrayIgnorePattern` option specifies exceptions not to check for usage: elements of array destructuring patterns whose names match a regexp pattern. For example, variables whose names begin with an underscore.
Examples of **correct** code for the `{ "destructuredArrayIgnorePattern": "^_" }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", { "destructuredArrayIgnorePattern": "^_" }]*/
@@ -282,6 +326,8 @@ _o = 1;
p;
```
+:::
+
### caughtErrors
The `caughtErrors` option is used for `catch` block arguments validation.
@@ -297,6 +343,8 @@ Not specifying this rule is equivalent of assigning it to `none`.
Examples of **correct** code for the `{ "caughtErrors": "none" }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", { "caughtErrors": "none" }]*/
@@ -307,10 +355,14 @@ try {
}
```
+:::
+
#### caughtErrors: all
Examples of **incorrect** code for the `{ "caughtErrors": "all" }` option:
+::: incorrect
+
```js
/*eslint no-unused-vars: ["error", { "caughtErrors": "all" }]*/
@@ -323,12 +375,16 @@ try {
}
```
+:::
+
### caughtErrorsIgnorePattern
The `caughtErrorsIgnorePattern` option specifies exceptions not to check for usage: catch arguments whose names match a regexp pattern. For example, variables whose names begin with a string 'ignore'.
Examples of **correct** code for the `{ "caughtErrorsIgnorePattern": "^ignore" }` option:
+::: correct
+
```js
/*eslint no-unused-vars: ["error", { "caughtErrorsIgnorePattern": "^ignore" }]*/
@@ -339,6 +395,8 @@ try {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about unused variables or function arguments, you can safely turn this rule off.
diff --git a/docs/src/rules/no-use-before-define.md b/docs/src/rules/no-use-before-define.md
index f388a469540..01b2c387d6e 100644
--- a/docs/src/rules/no-use-before-define.md
+++ b/docs/src/rules/no-use-before-define.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-use-befo
rule_type: problem
---
-Disallows the use of variables before they are defined.
In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code. This can be confusing and some believe it is best to always declare variables and functions before using them.
@@ -17,6 +16,8 @@ This rule will warn when it encounters a reference to an identifier that has not
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-use-before-define: "error"*/
@@ -60,10 +61,17 @@ var b = 1;
}
}
}
+
+export { foo };
+const foo = 1;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-use-before-define: "error"*/
@@ -109,13 +117,23 @@ function g() {
}
}
}
+
+const foo = 1;
+export { foo };
```
+:::
+
## Options
```json
{
- "no-use-before-define": ["error", { "functions": true, "classes": true, "variables": true }]
+ "no-use-before-define": ["error", {
+ "functions": true,
+ "classes": true,
+ "variables": true,
+ "allowNamedExports": false
+ }]
}
```
@@ -136,14 +154,20 @@ function g() {
If this is `true`, the rule warns every reference to a variable before the variable declaration.
Otherwise, the rule ignores a reference if the declaration is in an upper scope, while still reporting the reference if it's in the same scope as the declaration.
Default is `true`.
+* `allowNamedExports` (`boolean`) -
+ If this flag is set to `true`, the rule always allows references in `export {};` declarations.
+ These references are safe even if the variables are declared later in the code.
+ Default is `false`.
This rule accepts `"nofunc"` string as an option.
-`"nofunc"` is the same as `{ "functions": false, "classes": true, "variables": true }`.
+`"nofunc"` is the same as `{ "functions": false, "classes": true, "variables": true, "allowNamedExports": false }`.
### functions
Examples of **correct** code for the `{ "functions": false }` option:
+::: correct
+
```js
/*eslint no-use-before-define: ["error", { "functions": false }]*/
@@ -151,12 +175,16 @@ f();
function f() {}
```
+:::
+
This option allows references to function declarations. For function expressions and arrow functions, please see the [`variables`](#variables) option.
### classes
Examples of **incorrect** code for the `{ "classes": false }` option:
+::: incorrect
+
```js
/*eslint no-use-before-define: ["error", { "classes": false }]*/
@@ -190,8 +218,12 @@ class A {
}
```
+:::
+
Examples of **correct** code for the `{ "classes": false }` option:
+::: correct
+
```js
/*eslint no-use-before-define: ["error", { "classes": false }]*/
@@ -203,10 +235,14 @@ class A {
}
```
+:::
+
### variables
Examples of **incorrect** code for the `{ "variables": false }` option:
+::: incorrect
+
```js
/*eslint no-use-before-define: ["error", { "variables": false }]*/
@@ -242,8 +278,12 @@ const g = function() {};
}
```
+:::
+
Examples of **correct** code for the `{ "variables": false }` option:
+::: correct
+
```js
/*eslint no-use-before-define: ["error", { "variables": false }]*/
@@ -267,3 +307,48 @@ const g = function() {}
const foo = 1;
}
```
+
+:::
+
+### allowNamedExports
+
+Examples of **correct** code for the `{ "allowNamedExports": true }` option:
+
+::: correct
+
+```js
+/*eslint no-use-before-define: ["error", { "allowNamedExports": true }]*/
+
+export { a, b, f, C };
+
+const a = 1;
+
+let b;
+
+function f () {}
+
+class C {}
+```
+
+:::
+
+Examples of **incorrect** code for the `{ "allowNamedExports": true }` option:
+
+::: incorrect
+
+```js
+/*eslint no-use-before-define: ["error", { "allowNamedExports": true }]*/
+
+export default a;
+const a = 1;
+
+const b = c;
+export const c = 1;
+
+export function foo() {
+ return d;
+}
+const d = 1;
+```
+
+:::
diff --git a/docs/src/rules/no-useless-backreference.md b/docs/src/rules/no-useless-backreference.md
index 615287b12bd..5178a2ec937 100644
--- a/docs/src/rules/no-useless-backreference.md
+++ b/docs/src/rules/no-useless-backreference.md
@@ -11,9 +11,7 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
---
-
-Disallows useless backreferences in regular expressions.
In JavaScript regular expressions, it's syntactically valid to define a backreference to a group that belongs to another alternative part of the pattern, a backreference to a group that appears after the backreference, a backreference to a group that contains that backreference, or a backreference to a group that is inside a negative lookaround. However, by the specification, in any of these cases the backreference always ends up matching only zero-length (the empty string), regardless of the context in which the backreference and the group appear.
@@ -56,6 +54,8 @@ This might be surprising to developers coming from other languages where some of
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-useless-backreference: "error"*/
@@ -88,8 +88,12 @@ new RegExp('(\\1)'); // nested reference to (\1)
/(?
-Disallows unnecessary catch clauses.
A `catch` clause that only rethrows the original error is redundant, and has no effect on the runtime behavior of the program. These redundant clauses can be a source of confusion and code bloat, so it's better to disallow these unnecessary `catch` clauses.
@@ -17,6 +15,8 @@ This rule reports `catch` clauses that only `throw` the caught error.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-useless-catch: "error"*/
@@ -35,8 +35,12 @@ try {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-useless-catch: "error"*/
@@ -60,6 +64,8 @@ try {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about unnecessary catch clauses, you can safely disable this rule.
diff --git a/docs/src/rules/no-useless-computed-key.md b/docs/src/rules/no-useless-computed-key.md
index 0049d773570..be4aa353d9f 100644
--- a/docs/src/rules/no-useless-computed-key.md
+++ b/docs/src/rules/no-useless-computed-key.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-useless-
rule_type: suggestion
---
-
-Disallows unnecessary computed property keys in objects and classes.
It's unnecessary to use computed properties with literals such as:
@@ -27,6 +25,8 @@ This rule disallows unnecessary usage of computed property keys.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-useless-computed-key: "error"*/
@@ -37,8 +37,12 @@ var a = { ['x']: 0 };
var a = { ['x']() {} };
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-useless-computed-key: "error"*/
@@ -49,8 +53,12 @@ var c = { a: 0 };
var c = { '0+1,234': 0 };
```
+:::
+
Examples of additional **correct** code for this rule:
+::: correct
+
```js
/*eslint no-useless-computed-key: "error"*/
@@ -61,6 +69,8 @@ var c = {
};
```
+:::
+
## Options
This rule has an object option:
@@ -76,6 +86,8 @@ When `enforceForClassMembers` is set to `true`, the rule will also disallow unne
Examples of **incorrect** code for this rule with the `{ "enforceForClassMembers": true }` option:
+::: incorrect
+
```js
/*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": true }]*/
@@ -93,8 +105,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "enforceForClassMembers": true }` option:
+::: correct
+
```js
/*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": true }]*/
@@ -112,8 +128,12 @@ class Foo {
}
```
+:::
+
Examples of additional **correct** code for this rule with the `{ "enforceForClassMembers": true }` option:
+::: correct
+
```js
/*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": true }]*/
@@ -130,6 +150,8 @@ class Foo {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about unnecessary computed property keys, you can safely disable this rule.
diff --git a/docs/src/rules/no-useless-concat.md b/docs/src/rules/no-useless-concat.md
index 5e21f9de32f..57cf297c250 100644
--- a/docs/src/rules/no-useless-concat.md
+++ b/docs/src/rules/no-useless-concat.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-useless-
rule_type: suggestion
---
-Disallows unnecessary concatenation of strings.
It's unnecessary to concatenate two strings together, such as:
@@ -25,6 +24,8 @@ This rule aims to flag the concatenation of 2 literals when they could be combin
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-useless-concat: "error"*/
/*eslint-env es6*/
@@ -38,8 +39,12 @@ var a = `1` + '0';
var a = `1` + `0`;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-useless-concat: "error"*/
@@ -53,6 +58,8 @@ var c = "foo" +
"bar";
```
+:::
+
## When Not To Use It
If you don't want to be notified about unnecessary string concatenation, you can safely disable this rule.
diff --git a/docs/src/rules/no-useless-constructor.md b/docs/src/rules/no-useless-constructor.md
index 58557862bac..1830b2e085f 100644
--- a/docs/src/rules/no-useless-constructor.md
+++ b/docs/src/rules/no-useless-constructor.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-useless-
rule_type: suggestion
---
-Disallows unnecessary constructors.
ES2015 provides a default class constructor if one is not specified. As such, it is unnecessary to provide an empty constructor or one that simply delegates into its parent class, as in the following examples:
@@ -30,6 +29,8 @@ This rule flags class constructors that can be safely removed without changing h
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-useless-constructor: "error"*/
/*eslint-env es6*/
@@ -46,8 +47,12 @@ class B extends A {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-useless-constructor: "error"*/
@@ -73,6 +78,8 @@ class B extends A {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about unnecessary constructors, you can safely disable this rule.
diff --git a/docs/src/rules/no-useless-escape.md b/docs/src/rules/no-useless-escape.md
index 4d1af9988bc..b52f569d923 100644
--- a/docs/src/rules/no-useless-escape.md
+++ b/docs/src/rules/no-useless-escape.md
@@ -5,11 +5,9 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-useless-
rule_type: suggestion
---
-
-
-Disallows unnecessary escape characters.
+
Escaping non-special characters in strings, template literals, and regular expressions doesn't have any effect, as demonstrated in the following example:
@@ -25,6 +23,8 @@ This rule flags escapes that can be safely removed without changing behavior.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-useless-escape: "error"*/
@@ -41,8 +41,12 @@ Examples of **incorrect** code for this rule:
/[a-z\-]/;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-useless-escape: "error"*/
@@ -63,6 +67,8 @@ Examples of **correct** code for this rule:
/[a-z-]/;
```
+:::
+
## When Not To Use It
If you don't want to be notified about unnecessary escapes, you can safely disable this rule.
diff --git a/docs/src/rules/no-useless-rename.md b/docs/src/rules/no-useless-rename.md
index ddaafdd0cb6..97ee34c7b30 100644
--- a/docs/src/rules/no-useless-rename.md
+++ b/docs/src/rules/no-useless-rename.md
@@ -7,9 +7,7 @@ related_rules:
- object-shorthand
---
-
-Disallows renaming import, export, and destructured assignments to the same name.
ES2015 allows for the renaming of references in import and export statements as well as destructuring assignments. This gives programmers a concise syntax for performing these operations while renaming these references:
@@ -59,6 +57,8 @@ By default, all options are set to `false`:
Examples of **incorrect** code for this rule by default:
+::: incorrect
+
```js
/*eslint no-useless-rename: "error"*/
@@ -74,8 +74,12 @@ function foo({ bar: bar }) {}
({ foo: foo }) => {}
```
+:::
+
Examples of **correct** code for this rule by default:
+::: correct
+
```js
/*eslint no-useless-rename: "error"*/
@@ -101,16 +105,24 @@ function foo({ bar: baz }) {}
({ foo: bar }) => {}
```
+:::
+
Examples of **correct** code for this rule with `{ ignoreImport: true }`:
+::: correct
+
```js
/*eslint no-useless-rename: ["error", { ignoreImport: true }]*/
import { foo as foo } from "bar";
```
+:::
+
Examples of **correct** code for this rule with `{ ignoreExport: true }`:
+::: correct
+
```js
/*eslint no-useless-rename: ["error", { ignoreExport: true }]*/
@@ -118,8 +130,12 @@ export { foo as foo };
export { foo as foo } from "bar";
```
+:::
+
Examples of **correct** code for this rule with `{ ignoreDestructuring: true }`:
+::: correct
+
```js
/*eslint no-useless-rename: ["error", { ignoreDestructuring: true }]*/
@@ -128,6 +144,8 @@ function foo({ bar: bar }) {}
({ foo: foo }) => {}
```
+:::
+
## When Not To Use It
You can safely disable this rule if you do not care about redundantly renaming import, export, and destructuring assignments.
diff --git a/docs/src/rules/no-useless-return.md b/docs/src/rules/no-useless-return.md
index b207177d35b..e52673601f1 100644
--- a/docs/src/rules/no-useless-return.md
+++ b/docs/src/rules/no-useless-return.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-useless-
rule_type: suggestion
---
-
-Disallows redundant return statements.
A `return;` statement with nothing after it is redundant, and has no effect on the runtime behavior of a function. This can be confusing, so it's better to disallow these redundant statements.
@@ -17,6 +15,8 @@ This rule aims to report redundant `return` statements.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/* eslint no-useless-return: "error" */
@@ -48,8 +48,12 @@ function foo() {
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/* eslint no-useless-return: "error" */
@@ -87,6 +91,8 @@ function foo() {
```
+:::
+
## When Not To Use It
If you don't care about disallowing redundant return statements, you can turn off this rule.
diff --git a/docs/src/rules/no-var.md b/docs/src/rules/no-var.md
index 8d8b754797c..dbd266b4523 100644
--- a/docs/src/rules/no-var.md
+++ b/docs/src/rules/no-var.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-var.md
rule_type: suggestion
---
-
-Requires `let` or `const` instead of `var`.
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the `let`
and `const` keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
@@ -34,6 +32,8 @@ This rule is aimed at discouraging the use of `var` and encouraging the use of `
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-var: "error"*/
@@ -41,8 +41,12 @@ var x = "y";
var CONFIG = {};
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-var: "error"*/
/*eslint-env es6*/
@@ -51,6 +55,8 @@ let x = "y";
const CONFIG = {};
```
+:::
+
## When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
diff --git a/docs/src/rules/no-void.md b/docs/src/rules/no-void.md
index d37beda429b..6ca4a15599c 100644
--- a/docs/src/rules/no-void.md
+++ b/docs/src/rules/no-void.md
@@ -11,7 +11,6 @@ further_reading:
- https://oreilly.com/javascript/excerpts/javascript-good-parts/bad-parts.html
---
-Disallows use of the void operator.
The `void` operator takes an operand and returns `undefined`: `void expression` will evaluate `expression` and return `undefined`. It can be used to ignore any side effects `expression` may produce:
@@ -63,6 +62,8 @@ This rule aims to eliminate use of void operator.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-void: "error"*/
@@ -75,6 +76,8 @@ function baz() {
}
```
+:::
+
## Options
This rule has an object option:
@@ -87,6 +90,8 @@ When `allowAsStatement` is set to true, the rule will not error on cases that th
Examples of **incorrect** code for `{ "allowAsStatement": true }`:
+::: incorrect
+
```js
/*eslint no-void: ["error", { "allowAsStatement": true }]*/
@@ -96,8 +101,12 @@ function baz() {
}
```
+:::
+
Examples of **correct** code for `{ "allowAsStatement": true }`:
+::: correct
+
```js
/*eslint no-void: ["error", { "allowAsStatement": true }]*/
@@ -105,6 +114,8 @@ void foo;
void someFunction();
```
+:::
+
## When Not To Use It
If you intentionally use the `void` operator then you can disable this rule.
diff --git a/docs/src/rules/no-warning-comments.md b/docs/src/rules/no-warning-comments.md
index 6775c41e408..6ddef3c5de4 100644
--- a/docs/src/rules/no-warning-comments.md
+++ b/docs/src/rules/no-warning-comments.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-warning-
rule_type: suggestion
---
-Disallows specified warning terms in comments.
Developers often add comments to code which is not complete or needs review. Most likely you want to fix or review the code, and then remove the comment, before you consider the code to be production ready.
@@ -27,6 +26,8 @@ This rule has an options object literal:
Example of **incorrect** code for the default `{ "terms": ["todo", "fixme", "xxx"], "location": "start" }` options:
+::: incorrect
+
```js
/*eslint no-warning-comments: "error"*/
@@ -39,8 +40,12 @@ function callback(err, results) {
}
```
+:::
+
Example of **correct** code for the default `{ "terms": ["todo", "fixme", "xxx"], "location": "start" }` options:
+::: correct
+
```js
/*eslint no-warning-comments: "error"*/
@@ -54,10 +59,14 @@ function callback(err, results) {
}
```
+:::
+
### terms and location
Examples of **incorrect** code for the `{ "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }` options:
+::: incorrect
+
```js
/*eslint no-warning-comments: ["error", { "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }]*/
@@ -71,8 +80,12 @@ Examples of **incorrect** code for the `{ "terms": ["todo", "fixme", "any other
*/
```
+:::
+
Examples of **correct** code for the `{ "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }` options:
+::: correct
+
```js
/*eslint no-warning-comments: ["error", { "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }]*/
@@ -86,6 +99,8 @@ Examples of **correct** code for the `{ "terms": ["todo", "fixme", "any other te
*/
```
+:::
+
## When Not To Use It
* If you have a large code base that was not developed with a policy to not use such warning terms, you might get hundreds of warnings / errors which might be counter-productive if you can't fix all of them (e.g. if you don't get the time to do it) as you might overlook other warnings / errors or get used to many of them and don't pay attention on it anymore.
diff --git a/docs/src/rules/no-whitespace-before-property.md b/docs/src/rules/no-whitespace-before-property.md
index c90bbe8a575..1a46c56b698 100644
--- a/docs/src/rules/no-whitespace-before-property.md
+++ b/docs/src/rules/no-whitespace-before-property.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/no-whitespa
rule_type: layout
---
-
-Disallows whitespace before properties.
JavaScript allows whitespace between objects and their properties. However, inconsistent spacing can make code harder to read and can lead to errors.
@@ -28,6 +26,8 @@ foo
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-whitespace-before-property: "error"*/
@@ -46,8 +46,12 @@ foo
.bar(). baz()
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-whitespace-before-property: "error"*/
@@ -71,6 +75,8 @@ foo.
baz()
```
+:::
+
## When Not To Use It
Turn this rule off if you do not care about allowing whitespace around the dot or before the opening bracket before properties of objects if they are on the same line.
diff --git a/docs/src/rules/no-with.md b/docs/src/rules/no-with.md
index 4e479dee010..6e1740acdf3 100644
--- a/docs/src/rules/no-with.md
+++ b/docs/src/rules/no-with.md
@@ -7,9 +7,7 @@ further_reading:
- https://web.archive.org/web/20200717110117/https://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/
---
-
-Disallows `with` statements.
The `with` statement is potentially problematic because it adds members of an object to the current scope, making it impossible to tell what a variable inside the block actually refers to.
@@ -21,6 +19,8 @@ If ESLint parses code in strict mode, the parser (instead of this rule) reports
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint no-with: "error"*/
@@ -29,8 +29,12 @@ with (point) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint no-with: "error"*/
/*eslint-env es6*/
@@ -38,6 +42,8 @@ Examples of **correct** code for this rule:
const r = ({x, y}) => Math.sqrt(x * x + y * y);
```
+:::
+
## When Not To Use It
If you intentionally use `with` statements then you can disable this rule.
diff --git a/docs/src/rules/no-wrap-func.md b/docs/src/rules/no-wrap-func.md
index 0285338ed4b..22c57a390fd 100644
--- a/docs/src/rules/no-wrap-func.md
+++ b/docs/src/rules/no-wrap-func.md
@@ -27,14 +27,22 @@ This rule will raise a warning when it encounters a function expression wrapped
Example of **incorrect** code for this rule:
+::: incorrect
+
```js
var a = (function() {/*...*/});
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
var a = function() {/*...*/};
(function() {/*...*/})();
```
+
+:::
diff --git a/docs/src/rules/nonblock-statement-body-position.md b/docs/src/rules/nonblock-statement-body-position.md
index 05b2a40ce9a..6c6c2cfdccb 100644
--- a/docs/src/rules/nonblock-statement-body-position.md
+++ b/docs/src/rules/nonblock-statement-body-position.md
@@ -7,9 +7,7 @@ further_reading:
- https://jscs-dev.github.io/rule/requireNewlineBeforeSingleStatementsInIf
---
-
-Enforces the location of single-line statements.
When writing `if`, `else`, `while`, `do-while`, and `for` statements, the body can be a single statement instead of a block. It can be useful to enforce a consistent location for these single statements.
@@ -55,6 +53,8 @@ Additionally, the rule accepts an optional object option with an `"overrides"` k
Examples of **incorrect** code for this rule with the default `"beside"` option:
+::: incorrect
+
```js
/* eslint nonblock-statement-body-position: ["error", "beside"] */
@@ -75,8 +75,12 @@ while (foo)
```
+:::
+
Examples of **correct** code for this rule with the default `"beside"` option:
+::: correct
+
```js
/* eslint nonblock-statement-body-position: ["error", "beside"] */
@@ -96,8 +100,12 @@ if (foo) { // block statements are always allowed with this rule
}
```
+:::
+
Examples of **incorrect** code for this rule with the `"below"` option:
+::: incorrect
+
```js
/* eslint nonblock-statement-body-position: ["error", "below"] */
@@ -111,8 +119,12 @@ for (let i = 1; i < foo; i++) bar();
do bar(); while (foo)
```
+:::
+
Examples of **correct** code for this rule with the `"below"` option:
+::: correct
+
```js
/* eslint nonblock-statement-body-position: ["error", "below"] */
@@ -138,8 +150,12 @@ if (foo) {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `"beside", { "overrides": { "while": "below" } }` rule:
+::: incorrect
+
```js
/* eslint nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] */
@@ -149,8 +165,12 @@ if (foo)
while (foo) bar();
```
+:::
+
Examples of **correct** code for this rule with the `"beside", { "overrides": { "while": "below" } }` rule:
+::: correct
+
```js
/* eslint nonblock-statement-body-position: ["error", "beside", { "overrides": { "while": "below" } }] */
@@ -160,6 +180,8 @@ while (foo)
bar();
```
+:::
+
## When Not To Use It
If you're not concerned about consistent locations of single-line statements, you should not turn on this rule. You can also disable this rule if you're using the `"all"` option for the [`curly`](/docs/rules/curly) rule, because this will disallow single-line statements entirely.
diff --git a/docs/src/rules/object-curly-newline.md b/docs/src/rules/object-curly-newline.md
index eadbc77680f..6c992c7aa27 100644
--- a/docs/src/rules/object-curly-newline.md
+++ b/docs/src/rules/object-curly-newline.md
@@ -10,9 +10,7 @@ related_rules:
- object-property-newline
---
-
-Enforces consistent line breaks after opening and before closing braces.
A number of style guides require or disallow line breaks inside of object braces and other tokens.
@@ -55,6 +53,8 @@ You can specify different options for object literals, destructuring assignments
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint object-curly-newline: ["error", "always"]*/
/*eslint-env es6*/
@@ -78,8 +78,12 @@ let {k = function() {
}} = obj;
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint object-curly-newline: ["error", "always"]*/
/*eslint-env es6*/
@@ -121,10 +125,14 @@ let {
} = obj;
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint object-curly-newline: ["error", "never"]*/
/*eslint-env es6*/
@@ -166,8 +174,12 @@ let {
} = obj;
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint object-curly-newline: ["error", "never"]*/
/*eslint-env es6*/
@@ -191,10 +203,14 @@ let {k = function() {
}} = obj;
```
+:::
+
### multiline
Examples of **incorrect** code for this rule with the `{ "multiline": true }` option:
+::: incorrect
+
```js
/*eslint object-curly-newline: ["error", { "multiline": true }]*/
/*eslint-env es6*/
@@ -228,8 +244,12 @@ let {k = function() {
}} = obj;
```
+:::
+
Examples of **correct** code for this rule with the `{ "multiline": true }` option:
+::: correct
+
```js
/*eslint object-curly-newline: ["error", { "multiline": true }]*/
/*eslint-env es6*/
@@ -261,10 +281,14 @@ let {
} = obj;
```
+:::
+
### minProperties
Examples of **incorrect** code for this rule with the `{ "minProperties": 2 }` option:
+::: incorrect
+
```js
/*eslint object-curly-newline: ["error", { "minProperties": 2 }]*/
/*eslint-env es6*/
@@ -298,8 +322,12 @@ let {
} = obj;
```
+:::
+
Examples of **correct** code for this rule with the `{ "minProperties": 2 }` option:
+::: correct
+
```js
/*eslint object-curly-newline: ["error", { "minProperties": 2 }]*/
/*eslint-env es6*/
@@ -331,10 +359,14 @@ let {k = function() {
}} = obj;
```
+:::
+
### consistent
Examples of **incorrect** code for this rule with the default `{ "consistent": true }` option:
+::: incorrect
+
```js
/*eslint object-curly-newline: ["error", { "consistent": true }]*/
/*eslint-env es6*/
@@ -377,8 +409,12 @@ let {
}} = obj;
```
+:::
+
Examples of **correct** code for this rule with the default `{ "consistent": true }` option:
+::: correct
+
```js
/*eslint object-curly-newline: ["error", { "consistent": true }]*/
/*eslint-env es6*/
@@ -429,10 +465,14 @@ let {
} = obj;
```
+:::
+
### ObjectExpression and ObjectPattern
Examples of **incorrect** code for this rule with the `{ "ObjectExpression": "always", "ObjectPattern": "never" }` options:
+::: incorrect
+
```js
/*eslint object-curly-newline: ["error", { "ObjectExpression": "always", "ObjectPattern": "never" }]*/
/*eslint-env es6*/
@@ -465,8 +505,12 @@ let {
} = obj;
```
+:::
+
Examples of **correct** code for this rule with the `{ "ObjectExpression": "always", "ObjectPattern": "never" }` options:
+::: correct
+
```js
/*eslint object-curly-newline: ["error", { "ObjectExpression": "always", "ObjectPattern": "never" }]*/
/*eslint-env es6*/
@@ -499,10 +543,14 @@ let {k = function() {
}} = obj;
```
+:::
+
### ImportDeclaration and ExportDeclaration
Examples of **incorrect** code for this rule with the `{ "ImportDeclaration": "always", "ExportDeclaration": "never" }` options:
+::: incorrect
+
```js
/*eslint object-curly-newline: ["error", { "ImportDeclaration": "always", "ExportDeclaration": "never" }]*/
/*eslint-env es6*/
@@ -522,8 +570,12 @@ export {
} from 'foo-bar';
```
+:::
+
Examples of **correct** code for this rule with the `{ "ImportDeclaration": "always", "ExportDeclaration": "never" }` options:
+::: correct
+
```js
/*eslint object-curly-newline: ["error", { "ImportDeclaration": "always", "ExportDeclaration": "never" }]*/
/*eslint-env es6*/
@@ -544,6 +596,8 @@ export { foo, bar } from 'foo-bar';
export { foo as f, bar } from 'foo-bar';
```
+:::
+
## When Not To Use It
If you don't want to enforce consistent line breaks after opening and before closing braces, then it's safe to disable this rule.
diff --git a/docs/src/rules/object-curly-spacing.md b/docs/src/rules/object-curly-spacing.md
index 42f296c2f2c..0b36ade9ea9 100644
--- a/docs/src/rules/object-curly-spacing.md
+++ b/docs/src/rules/object-curly-spacing.md
@@ -10,9 +10,7 @@ related_rules:
- space-in-parens
---
-
-Enforces consistent spacing inside braces.
While formatting preferences are very personal, a number of style guides require
or disallow spaces between curly braces in the following situations:
@@ -56,6 +54,8 @@ Object option:
Examples of **incorrect** code for this rule with the default `"never"` option:
+::: incorrect
+
```js
/*eslint object-curly-spacing: ["error", "never"]*/
@@ -67,8 +67,12 @@ var {x } = y;
import { foo } from 'bar';
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+::: correct
+
```js
/*eslint object-curly-spacing: ["error", "never"]*/
@@ -86,10 +90,14 @@ var {x} = y;
import {foo} from 'bar';
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint object-curly-spacing: ["error", "always"]*/
@@ -105,8 +113,12 @@ var {x} = y;
import {foo } from 'bar';
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint object-curly-spacing: ["error", "always"]*/
@@ -120,10 +132,14 @@ var { x } = y;
import { foo } from 'bar';
```
+:::
+
#### arraysInObjects
Examples of additional **correct** code for this rule with the `"never", { "arraysInObjects": true }` options:
+::: correct
+
```js
/*eslint object-curly-spacing: ["error", "never", { "arraysInObjects": true }]*/
@@ -131,8 +147,12 @@ var obj = {"foo": [ 1, 2 ] };
var obj = {"foo": [ "baz", "bar" ] };
```
+:::
+
Examples of additional **correct** code for this rule with the `"always", { "arraysInObjects": false }` options:
+::: correct
+
```js
/*eslint object-curly-spacing: ["error", "always", { "arraysInObjects": false }]*/
@@ -140,24 +160,34 @@ var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
```
+:::
+
#### objectsInObjects
Examples of additional **correct** code for this rule with the `"never", { "objectsInObjects": true }` options:
+::: correct
+
```js
/*eslint object-curly-spacing: ["error", "never", { "objectsInObjects": true }]*/
var obj = {"foo": {"baz": 1, "bar": 2} };
```
+:::
+
Examples of additional **correct** code for this rule with the `"always", { "objectsInObjects": false }` options:
+::: correct
+
```js
/*eslint object-curly-spacing: ["error", "always", { "objectsInObjects": false }]*/
var obj = { "foo": { "baz": 1, "bar": 2 }};
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between curly braces.
diff --git a/docs/src/rules/object-property-newline.md b/docs/src/rules/object-property-newline.md
index 5e0985907ee..0b8a657b0b9 100644
--- a/docs/src/rules/object-property-newline.md
+++ b/docs/src/rules/object-property-newline.md
@@ -10,9 +10,7 @@ related_rules:
- object-curly-spacing
---
-
-Enforces placing object properties on separate lines.
This rule permits you to restrict the locations of property specifications in object literals. You may prohibit any part of any property specification from appearing on the same line as any part of any other property specification. You may make this prohibition absolute, or, by invoking an object option, you may allow an exception, permitting an object literal to have all parts of all of its property specifications on a single line.
@@ -108,7 +106,7 @@ This rule applies equally to all property specifications, regardless of notation
* `a` (ES2015 shorthand property)
* ``[`prop${a}`]`` (ES2015 computed property name)
-Thus, the rule (without the object option) prohibits both of these:
+Thus, the rule (without the optional exception) prohibits both of these:
```js
const newObject = {
@@ -188,6 +186,8 @@ As illustrated above, the `--fix` option, applied to this rule, does not comply
Examples of **incorrect** code for this rule, with no object option or with `allowAllPropertiesOnSameLine` set to `false`:
+::: incorrect
+
```js
/*eslint object-property-newline: "error"*/
@@ -222,8 +222,12 @@ const obj5 = {
]: true};
```
+:::
+
Examples of **correct** code for this rule, with no object option or with `allowAllPropertiesOnSameLine` set to `false`:
+::: correct
+
```js
/*eslint object-property-newline: "error"*/
@@ -252,8 +256,12 @@ const obj3 = {
};
```
+:::
+
Examples of additional **correct** code for this rule with the `{ "allowAllPropertiesOnSameLine": true }` option:
+::: correct
+
```js
/*eslint object-property-newline: ["error", { "allowAllPropertiesOnSameLine": true }]*/
@@ -268,6 +276,8 @@ const obj3 = {
};
```
+:::
+
## When Not To Use It
You can turn this rule off if you want to decide, case-by-case, whether to place property specifications on separate lines.
diff --git a/docs/src/rules/object-shorthand.md b/docs/src/rules/object-shorthand.md
index 7ff7c2df6f7..d4e5f016b6d 100644
--- a/docs/src/rules/object-shorthand.md
+++ b/docs/src/rules/object-shorthand.md
@@ -9,9 +9,7 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
---
-
-Requires or disallows method and property shorthand syntax for object literals.
ECMAScript 6 provides a concise form for defining object literal methods and properties. This
syntax can make defining complex object literals much cleaner.
@@ -129,6 +127,8 @@ Additionally, the rule takes an optional object configuration:
Example of **incorrect** code for this rule with the `"always", { "avoidQuotes": true }` option:
+::: incorrect
+
```js
/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/
@@ -138,8 +138,12 @@ var foo = {
};
```
+:::
+
Example of **correct** code for this rule with the `"always", { "avoidQuotes": true }` option:
+::: correct
+
```js
/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/
@@ -150,6 +154,8 @@ var foo = {
};
```
+:::
+
### `ignoreConstructors`
```json
@@ -160,6 +166,8 @@ var foo = {
Example of **correct** code for this rule with the `"always", { "ignoreConstructors": true }` option:
+::: correct
+
```js
/*eslint object-shorthand: ["error", "always", { "ignoreConstructors": true }]*/
/*eslint-env es6*/
@@ -169,6 +177,8 @@ var foo = {
};
```
+:::
+
### `avoidExplicitReturnArrows`
```json
@@ -179,6 +189,8 @@ var foo = {
Example of **incorrect** code for this rule with the `"always", { "avoidExplicitReturnArrows": true }` option:
+::: incorrect
+
```js
/*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]*/
/*eslint-env es6*/
@@ -194,8 +206,12 @@ var foo = {
};
```
+:::
+
Example of **correct** code for this rule with the `"always", { "avoidExplicitReturnArrows": true }` option:
+::: correct
+
```js
/*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]*/
/*eslint-env es6*/
@@ -209,8 +225,12 @@ var foo = {
};
```
+:::
+
Example of **incorrect** code for this rule with the `"consistent"` option:
+::: incorrect
+
```js
/*eslint object-shorthand: [2, "consistent"]*/
/*eslint-env es6*/
@@ -221,8 +241,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule with the `"consistent"` option:
+::: correct
+
```js
/*eslint object-shorthand: [2, "consistent"]*/
/*eslint-env es6*/
@@ -238,8 +262,12 @@ var bar = {
};
```
+:::
+
Example of **incorrect** code with the `"consistent-as-needed"` option, which is very similar to `"consistent"`:
+::: incorrect
+
```js
/*eslint object-shorthand: [2, "consistent-as-needed"]*/
/*eslint-env es6*/
@@ -250,6 +278,8 @@ var foo = {
};
```
+:::
+
## When Not To Use It
Anyone not yet in an ES6 environment would not want to apply this rule. Others may find the terseness of the shorthand
diff --git a/docs/src/rules/one-var-declaration-per-line.md b/docs/src/rules/one-var-declaration-per-line.md
index 0a04ec25fcc..b2b21d447d8 100644
--- a/docs/src/rules/one-var-declaration-per-line.md
+++ b/docs/src/rules/one-var-declaration-per-line.md
@@ -7,9 +7,7 @@ related_rules:
- one-var
---
-
-Requires or disallows newlines around variable declarations.
Some developers declare multiple var statements on the same line:
@@ -42,6 +40,8 @@ This rule has a single string option:
Examples of **incorrect** code for this rule with the default `"initializations"` option:
+::: incorrect
+
```js
/*eslint one-var-declaration-per-line: ["error", "initializations"]*/
/*eslint-env es6*/
@@ -52,8 +52,12 @@ let a,
b = 0, c;
```
+:::
+
Examples of **correct** code for this rule with the default `"initializations"` option:
+::: correct
+
```js
/*eslint one-var-declaration-per-line: ["error", "initializations"]*/
/*eslint-env es6*/
@@ -67,10 +71,14 @@ let a,
b = 0;
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint one-var-declaration-per-line: ["error", "always"]*/
/*eslint-env es6*/
@@ -82,8 +90,12 @@ let a, b = 0;
const a = 0, b = 0;
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint one-var-declaration-per-line: ["error", "always"]*/
/*eslint-env es6*/
@@ -94,3 +106,5 @@ var a,
let a,
b = 0;
```
+
+:::
diff --git a/docs/src/rules/one-var.md b/docs/src/rules/one-var.md
index c7631e2493e..1835b6b2be8 100644
--- a/docs/src/rules/one-var.md
+++ b/docs/src/rules/one-var.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/one-var.md
rule_type: suggestion
---
-
-Enforces variables to be declared either together or separately in functions.
Variables can be declared at any point in JavaScript code using `var`, `let`, or `const`. There are many styles and preferences related to the declaration of variables, and one of those is deciding on how many variable declarations should be allowed in a single function.
@@ -73,6 +71,8 @@ Alternate object option:
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", "always"]*/
@@ -118,8 +118,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint one-var: ["error", "always"]*/
@@ -179,10 +183,14 @@ class C {
}
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", "never"]*/
@@ -215,8 +223,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint one-var: ["error", "never"]*/
@@ -256,10 +268,14 @@ for (var i = 0, len = arr.length; i < len; i++) {
}
```
+:::
+
### consecutive
Examples of **incorrect** code for this rule with the `"consecutive"` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", "consecutive"]*/
@@ -288,8 +304,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `"consecutive"` option:
+::: correct
+
```js
/*eslint one-var: ["error", "consecutive"]*/
@@ -319,10 +339,14 @@ class C {
}
```
+:::
+
### var, let, and const
Examples of **incorrect** code for this rule with the `{ var: "always", let: "never", const: "never" }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { var: "always", let: "never", const: "never" }]*/
/*eslint-env es6*/
@@ -342,8 +366,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ var: "always", let: "never", const: "never" }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { var: "always", let: "never", const: "never" }]*/
/*eslint-env es6*/
@@ -363,8 +391,12 @@ function foo() {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ var: "never" }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { var: "never" }]*/
/*eslint-env es6*/
@@ -375,8 +407,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ var: "never" }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { var: "never" }]*/
/*eslint-env es6*/
@@ -391,8 +427,12 @@ function foo() {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ separateRequires: true }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { separateRequires: true, var: "always" }]*/
/*eslint-env node*/
@@ -401,8 +441,12 @@ var foo = require("foo"),
bar = "bar";
```
+:::
+
Examples of **correct** code for this rule with the `{ separateRequires: true }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { separateRequires: true, var: "always" }]*/
/*eslint-env node*/
@@ -411,13 +455,21 @@ var foo = require("foo");
var bar = "bar";
```
+:::
+
+::: correct
+
```js
var foo = require("foo"),
bar = require("bar");
```
+:::
+
Examples of **incorrect** code for this rule with the `{ var: "never", let: "consecutive", const: "consecutive" }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { var: "never", let: "consecutive", const: "consecutive" }]*/
/*eslint-env es6*/
@@ -441,8 +493,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ var: "never", let: "consecutive", const: "consecutive" }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { var: "never", let: "consecutive", const: "consecutive" }]*/
/*eslint-env es6*/
@@ -468,8 +524,12 @@ function foo() {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ var: "consecutive" }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { var: "consecutive" }]*/
/*eslint-env es6*/
@@ -480,8 +540,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ var: "consecutive" }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { var: "consecutive" }]*/
/*eslint-env es6*/
@@ -496,10 +560,14 @@ function foo() {
}
```
+:::
+
### initialized and uninitialized
Examples of **incorrect** code for this rule with the `{ "initialized": "always", "uninitialized": "never" }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { "initialized": "always", "uninitialized": "never" }]*/
/*eslint-env es6*/
@@ -511,8 +579,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "initialized": "always", "uninitialized": "never" }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { "initialized": "always", "uninitialized": "never" }]*/
@@ -534,8 +606,12 @@ for (z of foo) {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "initialized": "never" }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { "initialized": "never" }]*/
/*eslint-env es6*/
@@ -546,8 +622,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "initialized": "never" }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { "initialized": "never" }]*/
@@ -558,8 +638,12 @@ function foo() {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "initialized": "consecutive", "uninitialized": "never" }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { "initialized": "consecutive", "uninitialized": "never" }]*/
@@ -573,8 +657,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "initialized": "consecutive", "uninitialized": "never" }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { "initialized": "consecutive", "uninitialized": "never" }]*/
@@ -588,8 +676,12 @@ function foo() {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "initialized": "consecutive" }` option:
+::: incorrect
+
```js
/*eslint one-var: ["error", { "initialized": "consecutive" }]*/
@@ -604,8 +696,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "initialized": "consecutive" }` option:
+::: correct
+
```js
/*eslint one-var: ["error", { "initialized": "consecutive" }]*/
@@ -620,6 +716,8 @@ function foo() {
}
```
+:::
+
## Compatibility
* **JSHint**: This rule maps to the `onevar` JSHint rule, but allows `let` and `const` to be configured separately.
diff --git a/docs/src/rules/operator-assignment.md b/docs/src/rules/operator-assignment.md
index 3f535fad92a..9b6d4e3c9b0 100644
--- a/docs/src/rules/operator-assignment.md
+++ b/docs/src/rules/operator-assignment.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/operator-as
rule_type: suggestion
---
-
-Requires or disallows assignment operator shorthand where possible.
JavaScript provides shorthand operators that combine variable assignment and some simple mathematical operations. For example, `x = x + 4` can be shortened to `x += 4`. The supported shorthand forms are as follows:
@@ -45,6 +43,8 @@ This rule has a single string option:
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint operator-assignment: ["error", "always"]*/
@@ -54,8 +54,12 @@ x[0] = x[0] / y;
x.y = x.y << z;
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint operator-assignment: ["error", "always"]*/
@@ -68,10 +72,14 @@ x[foo()] = x[foo()] % 2;
x = y + x; // `+` is not always commutative (e.g. x = "abc")
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint operator-assignment: ["error", "never"]*/
@@ -79,8 +87,12 @@ x *= y;
x ^= (y + z) / foo();
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint operator-assignment: ["error", "never"]*/
@@ -88,6 +100,8 @@ x = x + y;
x.y = x.y / a.b;
```
+:::
+
## When Not To Use It
Use of operator assignment shorthand is a stylistic choice. Leaving this rule turned off would allow developers to choose which style is more readable on a case-by-case basis.
diff --git a/docs/src/rules/operator-linebreak.md b/docs/src/rules/operator-linebreak.md
index 34efbc6fcb3..fedb7e92a32 100644
--- a/docs/src/rules/operator-linebreak.md
+++ b/docs/src/rules/operator-linebreak.md
@@ -7,9 +7,7 @@ related_rules:
- comma-style
---
-
-Enforces consistent linebreak style for operators.
When a statement is too long to fit on a single line, line breaks are generally inserted next to the operators separating expressions. The first style coming to mind would be to place the operator at the end of the line, following the English punctuation rules.
@@ -51,6 +49,8 @@ The default configuration is `"after", { "overrides": { "?": "before", ":": "bef
Examples of **incorrect** code for this rule with the `"after"` option:
+::: incorrect
+
```js
/*eslint operator-linebreak: ["error", "after"]*/
@@ -83,8 +83,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule with the `"after"` option:
+::: correct
+
```js
/*eslint operator-linebreak: ["error", "after"]*/
@@ -116,10 +120,14 @@ class Foo {
}
```
+:::
+
### before
Examples of **incorrect** code for this rule with the `"before"` option:
+::: incorrect
+
```js
/*eslint operator-linebreak: ["error", "before"]*/
@@ -148,8 +156,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule with the `"before"` option:
+::: correct
+
```js
/*eslint operator-linebreak: ["error", "before"]*/
@@ -181,10 +193,14 @@ class Foo {
}
```
+:::
+
### none
Examples of **incorrect** code for this rule with the `"none"` option:
+::: incorrect
+
```js
/*eslint operator-linebreak: ["error", "none"]*/
@@ -228,8 +244,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule with the `"none"` option:
+::: correct
+
```js
/*eslint operator-linebreak: ["error", "none"]*/
@@ -254,10 +274,14 @@ class Foo {
}
```
+:::
+
### overrides
Examples of additional **incorrect** code for this rule with the `{ "overrides": { "+=": "before" } }` option:
+::: incorrect
+
```js
/*eslint operator-linebreak: ["error", "after", { "overrides": { "+=": "before" } }]*/
@@ -266,8 +290,12 @@ thing +=
's';
```
+:::
+
Examples of additional **correct** code for this rule with the `{ "overrides": { "+=": "before" } }` option:
+::: correct
+
```js
/*eslint operator-linebreak: ["error", "after", { "overrides": { "+=": "before" } }]*/
@@ -276,8 +304,12 @@ thing
+= 's';
```
+:::
+
Examples of additional **correct** code for this rule with the `{ "overrides": { "?": "ignore", ":": "ignore" } }` option:
+::: correct
+
```js
/*eslint operator-linebreak: ["error", "after", { "overrides": { "?": "ignore", ":": "ignore" } }]*/
@@ -292,8 +324,12 @@ answer = everything
foo;
```
+:::
+
Examples of **incorrect** code for this rule with the default `"after", { "overrides": { "?": "before", ":": "before" } }` option:
+::: incorrect
+
```js
/*eslint operator-linebreak: ["error", "after", { "overrides": { "?": "before", ":": "before" } }]*/
@@ -316,8 +352,12 @@ answer = everything ?
foo;
```
+:::
+
Examples of **correct** code for this rule with the default `"after", { "overrides": { "?": "before", ":": "before" } }` option:
+::: correct
+
```js
/*eslint operator-linebreak: ["error", "after", { "overrides": { "?": "before", ":": "before" } }]*/
@@ -338,6 +378,8 @@ answer = everything
: foo;
```
+:::
+
## When Not To Use It
If your project will not be using a common operator line break style, turn this rule off.
diff --git a/docs/src/rules/padded-blocks.md b/docs/src/rules/padded-blocks.md
index 7667c0a02df..2665620d4b5 100644
--- a/docs/src/rules/padded-blocks.md
+++ b/docs/src/rules/padded-blocks.md
@@ -8,9 +8,7 @@ related_rules:
- padding-line-between-statements
---
-
-Requires or disallows padding within blocks.
Some style guides require block statements to start and end with blank lines. The goal is
to improve readability by visually separating the block content and the surrounding code.
@@ -56,6 +54,8 @@ Object option:
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", "always"]*/
@@ -88,8 +88,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint padded-blocks: ["error", "always"]*/
@@ -124,10 +128,14 @@ class C {
}
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", "never"]*/
@@ -165,8 +173,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint padded-blocks: ["error", "never"]*/
@@ -186,10 +198,14 @@ class C {
}
```
+:::
+
### blocks
Examples of **incorrect** code for this rule with the `{ "blocks": "always" }` option:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", { "blocks": "always" }]*/
@@ -229,8 +245,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "blocks": "always" }` option:
+::: correct
+
```js
/*eslint padded-blocks: ["error", { "blocks": "always" }]*/
@@ -274,8 +294,12 @@ class D {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "blocks": "never" }` option:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", { "blocks": "never" }]*/
@@ -311,8 +335,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "blocks": "never" }` option:
+::: correct
+
```js
/*eslint padded-blocks: ["error", { "blocks": "never" }]*/
@@ -340,10 +368,14 @@ class D {
}
```
+:::
+
### classes
Examples of **incorrect** code for this rule with the `{ "classes": "always" }` option:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", { "classes": "always" }]*/
@@ -353,8 +385,12 @@ class A {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "classes": "always" }` option:
+::: correct
+
```js
/*eslint padded-blocks: ["error", { "classes": "always" }]*/
@@ -366,8 +402,12 @@ class A {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "classes": "never" }` option:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", { "classes": "never" }]*/
@@ -379,8 +419,12 @@ class A {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "classes": "never" }` option:
+::: correct
+
```js
/*eslint padded-blocks: ["error", { "classes": "never" }]*/
@@ -390,10 +434,14 @@ class A {
}
```
+:::
+
### switches
Examples of **incorrect** code for this rule with the `{ "switches": "always" }` option:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", { "switches": "always" }]*/
@@ -402,8 +450,12 @@ switch (a) {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "switches": "always" }` option:
+::: correct
+
```js
/*eslint padded-blocks: ["error", { "switches": "always" }]*/
@@ -418,8 +470,12 @@ if (a) {
}
```
+:::
+
Examples of **incorrect** code for this rule with the `{ "switches": "never" }` option:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", { "switches": "never" }]*/
@@ -430,8 +486,12 @@ switch (a) {
}
```
+:::
+
Examples of **correct** code for this rule with the `{ "switches": "never" }` option:
+::: correct
+
```js
/*eslint padded-blocks: ["error", { "switches": "never" }]*/
@@ -446,10 +506,14 @@ if (a) {
}
```
+:::
+
### always + allowSingleLineBlocks
Examples of **incorrect** code for this rule with the `"always", {"allowSingleLineBlocks": true}` options:
+::: incorrect
+
```js
/*eslint padded-blocks: ["error", "always", { allowSingleLineBlocks: true }]*/
@@ -468,8 +532,12 @@ if (a) {
}
```
+:::
+
Examples of **correct** code for this rule with the `"always", {"allowSingleLineBlocks": true}` options:
+::: correct
+
```js
/*eslint padded-blocks: ["error", "always", { allowSingleLineBlocks: true }]*/
@@ -482,6 +550,8 @@ if (a) {
}
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of padding within blocks.
diff --git a/docs/src/rules/padding-line-between-statements.md b/docs/src/rules/padding-line-between-statements.md
index 3cd684236cf..8eef570e1b5 100644
--- a/docs/src/rules/padding-line-between-statements.md
+++ b/docs/src/rules/padding-line-between-statements.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/padding-lin
rule_type: layout
---
-
-Requires or disallows padding lines between statements.
This rule requires or disallows blank lines between the given 2 kinds of statements.
Properly blank lines help developers to understand the code.
@@ -98,6 +96,8 @@ This configuration would require blank lines before all `return` statements, lik
Examples of **incorrect** code for the `[{ blankLine: "always", prev: "*", next: "return" }]` configuration:
+::: incorrect
+
```js
/*eslint padding-line-between-statements: [
"error",
@@ -110,8 +110,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for the `[{ blankLine: "always", prev: "*", next: "return" }]` configuration:
+::: correct
+
```js
/*eslint padding-line-between-statements: [
"error",
@@ -129,12 +133,16 @@ function foo() {
}
```
+:::
+
----
This configuration would require blank lines after every sequence of variable declarations, like the [newline-after-var](newline-after-var) rule.
Examples of **incorrect** code for the `[{ blankLine: "always", prev: ["const", "let", "var"], next: "*"}, { blankLine: "any", prev: ["const", "let", "var"], next: ["const", "let", "var"]}]` configuration:
+::: incorrect
+
```js
/*eslint padding-line-between-statements: [
"error",
@@ -165,8 +173,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for the `[{ blankLine: "always", prev: ["const", "let", "var"], next: "*"}, { blankLine: "any", prev: ["const", "let", "var"], next: ["const", "let", "var"]}]` configuration:
+::: correct
+
```js
/*eslint padding-line-between-statements: [
"error",
@@ -205,12 +217,16 @@ class C {
}
```
+:::
+
----
This configuration would require blank lines after all directive prologues, like the [lines-around-directive](lines-around-directive) rule.
Examples of **incorrect** code for the `[{ blankLine: "always", prev: "directive", next: "*" }, { blankLine: "any", prev: "directive", next: "directive" }]` configuration:
+::: incorrect
+
```js
/*eslint padding-line-between-statements: [
"error",
@@ -222,8 +238,12 @@ Examples of **incorrect** code for the `[{ blankLine: "always", prev: "directive
foo();
```
+:::
+
Examples of **correct** code for the `[{ blankLine: "always", prev: "directive", next: "*" }, { blankLine: "any", prev: "directive", next: "directive" }]` configuration:
+::: correct
+
```js
/*eslint padding-line-between-statements: [
"error",
@@ -237,12 +257,16 @@ Examples of **correct** code for the `[{ blankLine: "always", prev: "directive",
foo();
```
+:::
+
----
This configuration would require blank lines between clauses in `switch` statements.
Examples of **incorrect** code for the `[{ blankLine: "always", prev: ["case", "default"], next: "*" }]` configuration:
+::: incorrect
+
```js
/*eslint padding-line-between-statements: [
"error",
@@ -262,8 +286,12 @@ switch (foo) {
}
```
+:::
+
Examples of **correct** code for the `[{ blankLine: "always", prev: ["case", "default"], next: "*" }]` configuration:
+::: correct
+
```js
/*eslint padding-line-between-statements: [
"error",
@@ -286,6 +314,8 @@ switch (foo) {
}
```
+:::
+
## When Not To Use It
If you don't want to notify warnings about linebreaks, then it's safe to disable this rule.
diff --git a/docs/src/rules/prefer-arrow-callback.md b/docs/src/rules/prefer-arrow-callback.md
index 0d0dbd9477c..37f5c9d3b21 100644
--- a/docs/src/rules/prefer-arrow-callback.md
+++ b/docs/src/rules/prefer-arrow-callback.md
@@ -7,9 +7,7 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
---
-
-Requires using arrow functions for callbacks.
Arrow functions can be an attractive alternative to function expressions for callbacks or function arguments.
diff --git a/docs/src/rules/prefer-const.md b/docs/src/rules/prefer-const.md
index 7bf20de6904..1e9268f84c4 100644
--- a/docs/src/rules/prefer-const.md
+++ b/docs/src/rules/prefer-const.md
@@ -8,9 +8,7 @@ related_rules:
- no-use-before-define
---
-
-Requires `const` declarations for variables that are never reassigned after declared.
If a variable is never reassigned, using the `const` declaration is better.
@@ -22,6 +20,8 @@ This rule is aimed at flagging variables that are declared using `let` keyword,
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-const: "error"*/
@@ -52,8 +52,12 @@ for (let a of [1, 2, 3]) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-const: "error"*/
@@ -120,6 +124,8 @@ var b = 3;
console.log(b);
```
+:::
+
## Options
```json
@@ -141,6 +147,8 @@ There are 2 values:
Examples of **incorrect** code for the default `{"destructuring": "any"}` option:
+::: incorrect
+
```js
/*eslint prefer-const: "error"*/
/*eslint-env es6*/
@@ -149,8 +157,12 @@ let {a, b} = obj; /*error 'b' is never reassigned, use 'const' instead.*/
a = a + 1;
```
+:::
+
Examples of **correct** code for the default `{"destructuring": "any"}` option:
+::: correct
+
```js
/*eslint prefer-const: "error"*/
/*eslint-env es6*/
@@ -165,8 +177,12 @@ a = a + 1;
b = b + 1;
```
+:::
+
Examples of **incorrect** code for the `{"destructuring": "all"}` option:
+::: incorrect
+
```js
/*eslint prefer-const: ["error", {"destructuring": "all"}]*/
/*eslint-env es6*/
@@ -176,8 +192,12 @@ let {a, b} = obj; /*error 'a' is never reassigned, use 'const' instead.
'b' is never reassigned, use 'const' instead.*/
```
+:::
+
Examples of **correct** code for the `{"destructuring": "all"}` option:
+::: correct
+
```js
/*eslint prefer-const: ["error", {"destructuring": "all"}]*/
/*eslint-env es6*/
@@ -187,6 +207,8 @@ let {a, b} = obj;
a = a + 1;
```
+:::
+
### ignoreReadBeforeAssign
This is an option to avoid conflicting with `no-use-before-define` rule (without `"nofunc"` option).
@@ -195,6 +217,8 @@ Default is `false`.
Examples of **correct** code for the `{"ignoreReadBeforeAssign": true}` option:
+::: correct
+
```js
/*eslint prefer-const: ["error", {"ignoreReadBeforeAssign": true}]*/
/*eslint-env es6*/
@@ -208,8 +232,12 @@ function initialize() {
timer = setInterval(initialize, 100);
```
+:::
+
Examples of **correct** code for the default `{"ignoreReadBeforeAssign": false}` option:
+::: correct
+
```js
/*eslint prefer-const: ["error", {"ignoreReadBeforeAssign": false}]*/
/*eslint-env es6*/
@@ -222,6 +250,8 @@ function initialize() {
}
```
+:::
+
## When Not To Use It
If you don't want to be notified about variables that are never reassigned after initial assignment, you can safely disable this rule.
diff --git a/docs/src/rules/prefer-destructuring.md b/docs/src/rules/prefer-destructuring.md
index e49efb2b02c..3ee5a5b74d2 100644
--- a/docs/src/rules/prefer-destructuring.md
+++ b/docs/src/rules/prefer-destructuring.md
@@ -8,9 +8,7 @@ further_reading:
- https://2ality.com/2015/01/es6-destructuring.html
---
-
-Requires destructuring from arrays and/or objects.
With JavaScript ES6, a new syntax was added for creating variables from an array index or object property, called [destructuring](#further-reading). This rule enforces usage of destructuring instead of accessing a property through a member expression.
@@ -37,6 +35,8 @@ The `--fix` option on the command line fixes only problems reported in variable
Examples of **incorrect** code for this rule:
+::: incorrect
+
```javascript
// With `array` enabled
var foo = array[0];
@@ -46,8 +46,12 @@ var foo = object.foo;
var foo = object['foo'];
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```javascript
// With `array` enabled
var [ foo ] = array;
@@ -62,20 +66,32 @@ let foo;
({ foo } = object);
```
+:::
+
Examples of **incorrect** code when `enforceForRenamedProperties` is enabled:
+::: incorrect
+
```javascript
var foo = object.bar;
```
+:::
+
Examples of **correct** code when `enforceForRenamedProperties` is enabled:
+::: correct
+
```javascript
var { bar: foo } = object;
```
+:::
+
Examples of additional **correct** code when `enforceForRenamedProperties` is enabled:
+::: correct
+
```javascript
class C {
#x;
@@ -85,6 +101,8 @@ class C {
}
```
+:::
+
An example configuration, with the defaults `array` and `object` filled in, looks like this:
```json
@@ -159,18 +177,26 @@ For example, the following configuration enforces object destructuring in variab
Examples of **correct** code when object destructuring in `VariableDeclarator` is enforced:
+::: correct
+
```javascript
/* eslint prefer-destructuring: ["error", {VariableDeclarator: {object: true}}] */
var {bar: foo} = object;
```
+:::
+
Examples of **correct** code when array destructuring in `AssignmentExpression` is enforced:
+::: correct
+
```javascript
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: true}}] */
[bar] = array;
```
+:::
+
## When Not To Use It
If you want to be able to access array indices or object properties directly, you can either configure the rule to your tastes or disable the rule entirely.
diff --git a/docs/src/rules/prefer-exponentiation-operator.md b/docs/src/rules/prefer-exponentiation-operator.md
index 08759f14fbe..c814948366c 100644
--- a/docs/src/rules/prefer-exponentiation-operator.md
+++ b/docs/src/rules/prefer-exponentiation-operator.md
@@ -4,13 +4,11 @@ layout: doc
edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/prefer-exponentiation-operator.md
rule_type: suggestion
further_reading:
-- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation
+- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation
- https://bugs.chromium.org/p/v8/issues/detail?id=5848
---
-
-Disallows the use of `Math.pow` in favor of the `**` operator.
Introduced in ES2016, the infix exponentiation operator `**` is an alternative for the standard `Math.pow` function.
@@ -22,6 +20,8 @@ This rule disallows calls to `Math.pow` and suggests using the `**` operator ins
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-exponentiation-operator: "error"*/
@@ -34,8 +34,12 @@ let baz = Math.pow(a + b, c + d);
let quux = Math.pow(-1, n);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-exponentiation-operator: "error"*/
@@ -48,6 +52,8 @@ let baz = (a + b) ** (c + d);
let quux = (-1) ** n;
```
+:::
+
## When Not To Use It
This rule should not be used unless ES2016 is supported in your codebase.
diff --git a/docs/src/rules/prefer-named-capture-group.md b/docs/src/rules/prefer-named-capture-group.md
index 59f9638940d..c67847d2348 100644
--- a/docs/src/rules/prefer-named-capture-group.md
+++ b/docs/src/rules/prefer-named-capture-group.md
@@ -7,7 +7,6 @@ related_rules:
- no-invalid-regexp
---
-Suggest using named capture group in regular expression.
## Rule Details
@@ -26,6 +25,8 @@ const regex = /(?:cauli|sun)flower/;
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-named-capture-group: "error"*/
@@ -36,8 +37,12 @@ const baz = RegExp('(ba[rz])');
foo.exec('bar')[1]; // Retrieve the group result.
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-named-capture-group: "error"*/
@@ -49,6 +54,8 @@ const xyz = /xyz(?:zy|abc)/;
foo.exec('bar').groups.id; // Retrieve the group result.
```
+:::
+
## When Not To Use It
If you are targeting ECMAScript 2017 and/or older environments, you should not use this rule, because this ECMAScript feature is only supported in ECMAScript 2018 and/or newer environments.
diff --git a/docs/src/rules/prefer-numeric-literals.md b/docs/src/rules/prefer-numeric-literals.md
index 379bbb7fe48..c0506d1b6b1 100644
--- a/docs/src/rules/prefer-numeric-literals.md
+++ b/docs/src/rules/prefer-numeric-literals.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/prefer-nume
rule_type: suggestion
---
-
-Disallows `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals.
The `parseInt()` and `Number.parseInt()` functions can be used to turn binary, octal, and hexadecimal strings into integers. As binary, octal, and hexadecimal literals are supported in ES6, this rule encourages use of those numeric literals instead of `parseInt()` or `Number.parseInt()`.
@@ -22,6 +20,8 @@ This rule disallows calls to `parseInt()` or `Number.parseInt()` if called with
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-numeric-literals: "error"*/
@@ -34,8 +34,12 @@ Number.parseInt("767", 8) === 503;
Number.parseInt("1F7", 16) === 503;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-numeric-literals: "error"*/
/*eslint-env es6*/
@@ -57,6 +61,8 @@ Number.parseInt(foo);
Number.parseInt(foo, 2);
```
+:::
+
## When Not To Use It
If you want to allow use of `parseInt()` or `Number.parseInt()` for binary, octal, or hexadecimal integers, or if you are not using ES6 (because binary and octal literals are not supported in ES5 and below), you may wish to disable this rule.
diff --git a/docs/src/rules/prefer-object-has-own.md b/docs/src/rules/prefer-object-has-own.md
index 3608bc6b3f2..3445ae17836 100644
--- a/docs/src/rules/prefer-object-has-own.md
+++ b/docs/src/rules/prefer-object-has-own.md
@@ -7,9 +7,7 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
---
-
-Prefer `Object.hasOwn()` over `Object.prototype.hasOwnProperty.call()`.
It is very common to write code like:
@@ -33,6 +31,8 @@ if (Object.hasOwn(object, "foo")) {
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-object-has-own: "error"*/
@@ -45,8 +45,12 @@ Object.hasOwnProperty.call(obj, "a");
const hasProperty = Object.prototype.hasOwnProperty.call(object, property);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-object-has-own: "error"*/
@@ -55,6 +59,8 @@ Object.hasOwn(obj, "a");
const hasProperty = Object.hasOwn(object, property);
```
+:::
+
## When Not To Use It
This rule should not be used unless ES2022 is supported in your codebase.
diff --git a/docs/src/rules/prefer-object-spread.md b/docs/src/rules/prefer-object-spread.md
index dd495867690..73b9aa8c498 100644
--- a/docs/src/rules/prefer-object-spread.md
+++ b/docs/src/rules/prefer-object-spread.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/prefer-obje
rule_type: suggestion
---
-
-Prefer use of an object spread over `Object.assign`.
When Object.assign is called using an object literal as the first argument, this rule requires using the object spread syntax instead. This rule also warns on cases where an `Object.assign` call is made using a single argument that is an object literal, in this case, the `Object.assign` call is not needed.
@@ -17,6 +15,8 @@ Introduced in ES2018, object spread is a declarative alternative which may perfo
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-object-spread: "error"*/
@@ -36,8 +36,12 @@ Object.assign({});
Object.assign({ foo: bar });
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-object-spread: "error"*/
@@ -55,6 +59,8 @@ Object.assign(foo, { bar, baz });
Object.assign(foo, { ...baz });
```
+:::
+
## When Not To Use It
This rule should not be used unless ES2018 is supported in your codebase.
diff --git a/docs/src/rules/prefer-promise-reject-errors.md b/docs/src/rules/prefer-promise-reject-errors.md
index 6c83c525dc7..9959737a680 100644
--- a/docs/src/rules/prefer-promise-reject-errors.md
+++ b/docs/src/rules/prefer-promise-reject-errors.md
@@ -9,7 +9,6 @@ further_reading:
- http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-rejected-with-a-non-error
---
-Requires using Error objects as Promise rejection reasons.
It is considered good practice to only pass instances of the built-in `Error` object to the `reject()` function for user-defined errors in Promises. `Error` objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non-`Error` value, it can be difficult to determine where the rejection occurred.
@@ -25,6 +24,8 @@ This rule takes one optional object argument:
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-promise-reject-errors: "error"*/
@@ -44,8 +45,12 @@ new Promise(function(resolve, reject) {
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-promise-reject-errors: "error"*/
@@ -61,8 +66,12 @@ var foo = getUnknownValue();
Promise.reject(foo);
```
+:::
+
Examples of **correct** code for this rule with the `allowEmptyReject: true` option:
+::: correct
+
```js
/*eslint prefer-promise-reject-errors: ["error", {"allowEmptyReject": true}]*/
@@ -73,6 +82,8 @@ new Promise(function(resolve, reject) {
});
```
+:::
+
## Known Limitations
Due to the limits of static analysis, this rule cannot guarantee that you will only reject Promises with `Error` objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an `Error`, it will not report cases where there is uncertainty about whether a given reason is an `Error`. For more information on this caveat, see the [similar limitations](no-throw-literal#known-limitations) in the `no-throw-literal` rule.
diff --git a/docs/src/rules/prefer-reflect.md b/docs/src/rules/prefer-reflect.md
index 59063fd50bf..2d388c413e4 100644
--- a/docs/src/rules/prefer-reflect.md
+++ b/docs/src/rules/prefer-reflect.md
@@ -9,7 +9,6 @@ related_rules:
- no-delete-var
---
-Suggest using Reflect methods where applicable.
This rule was **deprecated** in ESLint v3.9.0 and will not be replaced. The original intent of this rule now seems misguided as we have come to understand that `Reflect` methods are not actually intended to replace the `Object` counterparts the rule suggests, but rather exist as low-level primitives to be used with proxies in order to replicate the default behavior of various previously existing functionality.
@@ -48,6 +47,8 @@ Deprecates `Function.prototype.apply()` and `Function.prototype.call()`
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
@@ -62,8 +63,12 @@ obj.myMethod.call(obj, arg);
obj.myMethod.call(other, arg);
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
@@ -77,8 +82,12 @@ Reflect.apply(obj.myMethod, obj, [arg]);
Reflect.apply(obj.myMethod, other, [arg]);
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["apply"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["apply"] }]*/
@@ -89,8 +98,12 @@ obj.myMethod.apply(obj, args);
obj.myMethod.apply(other, args);
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["call"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["call"] }]*/
@@ -101,28 +114,40 @@ obj.myMethod.call(obj, arg);
obj.myMethod.call(other, arg);
```
+:::
+
### Reflect.defineProperty
Deprecates `Object.defineProperty()`
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
Object.defineProperty({}, 'foo', {value: 1})
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
Reflect.defineProperty({}, 'foo', {value: 1})
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["defineProperty"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["defineProperty"] }]*/
@@ -130,28 +155,40 @@ Object.defineProperty({}, 'foo', {value: 1})
Reflect.defineProperty({}, 'foo', {value: 1})
```
+:::
+
### Reflect.getOwnPropertyDescriptor
Deprecates `Object.getOwnPropertyDescriptor()`
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
Object.getOwnPropertyDescriptor({}, 'foo')
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
Reflect.getOwnPropertyDescriptor({}, 'foo')
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["getOwnPropertyDescriptor"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["getOwnPropertyDescriptor"] }]*/
@@ -159,28 +196,40 @@ Object.getOwnPropertyDescriptor({}, 'foo')
Reflect.getOwnPropertyDescriptor({}, 'foo')
```
+:::
+
### Reflect.getPrototypeOf
Deprecates `Object.getPrototypeOf()`
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
Object.getPrototypeOf({}, 'foo')
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
Reflect.getPrototypeOf({}, 'foo')
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["getPrototypeOf"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["getPrototypeOf"] }]*/
@@ -188,28 +237,40 @@ Object.getPrototypeOf({}, 'foo')
Reflect.getPrototypeOf({}, 'foo')
```
+:::
+
### Reflect.setPrototypeOf
Deprecates `Object.setPrototypeOf()`
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
Object.setPrototypeOf({}, Object.prototype)
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
Reflect.setPrototypeOf({}, Object.prototype)
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["setPrototypeOf"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["setPrototypeOf"] }]*/
@@ -217,28 +278,40 @@ Object.setPrototypeOf({}, Object.prototype)
Reflect.setPrototypeOf({}, Object.prototype)
```
+:::
+
### Reflect.isExtensible
Deprecates `Object.isExtensible`
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
Object.isExtensible({})
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
Reflect.isExtensible({})
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["isExtensible"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["isExtensible"] }]*/
@@ -246,28 +319,40 @@ Object.isExtensible({})
Reflect.isExtensible({})
```
+:::
+
### Reflect.getOwnPropertyNames
Deprecates `Object.getOwnPropertyNames()`
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
Object.getOwnPropertyNames({})
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
Reflect.getOwnPropertyNames({})
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["getOwnPropertyNames"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["getOwnPropertyNames"] }]*/
@@ -275,28 +360,40 @@ Object.getOwnPropertyNames({})
Reflect.getOwnPropertyNames({})
```
+:::
+
### Reflect.preventExtensions
Deprecates `Object.preventExtensions()`
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
Object.preventExtensions({})
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
Reflect.preventExtensions({})
```
+:::
+
Examples of **correct** code for this rule with the `{ "exceptions": ["preventExtensions"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["preventExtensions"] }]*/
@@ -304,20 +401,28 @@ Object.preventExtensions({})
Reflect.preventExtensions({})
```
+:::
+
### Reflect.deleteProperty
Deprecates the `delete` keyword
Examples of **incorrect** code for this rule when used without exceptions:
+::: incorrect
+
```js
/*eslint prefer-reflect: "error"*/
delete foo.bar; // deleting object property
```
+:::
+
Examples of **correct** code for this rule when used without exceptions:
+::: correct
+
```js
/*eslint prefer-reflect: "error"*/
@@ -325,10 +430,14 @@ delete bar; // deleting variable
Reflect.deleteProperty(foo, 'bar');
```
+:::
+
Note: For a rule preventing deletion of variables, see [no-delete-var instead](no-delete-var)
Examples of **correct** code for this rule with the `{ "exceptions": ["delete"] }` option:
+::: correct
+
```js
/*eslint prefer-reflect: ["error", { "exceptions": ["delete"] }]*/
@@ -337,6 +446,8 @@ delete foo.bar
Reflect.deleteProperty(foo, 'bar');
```
+:::
+
## When Not To Use It
This rule should not be used in ES3/5 environments.
diff --git a/docs/src/rules/prefer-regex-literals.md b/docs/src/rules/prefer-regex-literals.md
index c8821095299..34ac8aaa341 100644
--- a/docs/src/rules/prefer-regex-literals.md
+++ b/docs/src/rules/prefer-regex-literals.md
@@ -8,9 +8,7 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
---
-
-Disallows use of the `RegExp` constructor in favor of regular expression literals.
There are two ways to create a regular expression:
@@ -56,6 +54,8 @@ dynamically generated regular expressions.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-regex-literals: "error"*/
@@ -74,8 +74,12 @@ RegExp(`^\\d\\.$`);
new RegExp(String.raw`^\d\.$`);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-regex-literals: "error"*/
@@ -100,6 +104,8 @@ RegExp(`${prefix}abc`);
new RegExp(String.raw`^\d\. ${suffix}`);
```
+:::
+
## Options
This rule has an object option:
diff --git a/docs/src/rules/prefer-rest-params.md b/docs/src/rules/prefer-rest-params.md
index 3583f8371b8..2962713ffd8 100644
--- a/docs/src/rules/prefer-rest-params.md
+++ b/docs/src/rules/prefer-rest-params.md
@@ -7,7 +7,6 @@ related_rules:
- prefer-spread
---
-Suggests using rest parameters instead of `arguments`.
There are rest parameters in ES2015.
We can use that feature for variadic functions instead of the `arguments` variable.
@@ -22,6 +21,8 @@ This rule is aimed to flag usage of `arguments` variables.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-rest-params: "error"*/
@@ -40,8 +41,12 @@ function foo(action) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-rest-params: "error"*/
@@ -63,6 +68,8 @@ function foo() {
}
```
+:::
+
## When Not To Use It
This rule should not be used in ES3/5 environments.
diff --git a/docs/src/rules/prefer-spread.md b/docs/src/rules/prefer-spread.md
index f3f1fedce56..24febc0841f 100644
--- a/docs/src/rules/prefer-spread.md
+++ b/docs/src/rules/prefer-spread.md
@@ -7,7 +7,6 @@ related_rules:
- no-useless-call
---
-Suggests using spread syntax instead of `.apply()`.
Before ES2015, one must use `Function.prototype.apply()` to call variadic functions.
@@ -33,6 +32,8 @@ This rule is aimed to flag usage of `Function.prototype.apply()` in situations w
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-spread: "error"*/
@@ -41,8 +42,12 @@ foo.apply(null, args);
obj.foo.apply(obj, args);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-spread: "error"*/
@@ -62,6 +67,8 @@ foo.apply(null, [1, 2, 3]);
obj.foo.apply(obj, [1, 2, 3]);
```
+:::
+
Known limitations:
This rule analyzes code statically to check whether or not the `this` argument is changed. So, if the `this` argument is computed in a dynamic expression, this rule cannot detect a violation.
diff --git a/docs/src/rules/prefer-template.md b/docs/src/rules/prefer-template.md
index c47f81f1ba9..026992e0aec 100644
--- a/docs/src/rules/prefer-template.md
+++ b/docs/src/rules/prefer-template.md
@@ -8,9 +8,7 @@ related_rules:
- quotes
---
-
-Suggests using template literals instead of string concatenation.
In ES2015 (ES6), we can use template literals instead of string concatenation.
@@ -32,6 +30,8 @@ This rule is aimed to flag usage of `+` operators with strings.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint prefer-template: "error"*/
@@ -39,8 +39,12 @@ var str = "Hello, " + name + "!";
var str = "Time: " + (12 * 60 * 60 * 1000);
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint prefer-template: "error"*/
/*eslint-env es6*/
@@ -53,6 +57,8 @@ var str = `Time: ${12 * 60 * 60 * 1000}`;
var str = "Hello, " + "World!";
```
+:::
+
## When Not To Use It
This rule should not be used in ES3/5 environments.
diff --git a/docs/src/rules/quote-props.md b/docs/src/rules/quote-props.md
index 796278f980f..8e93e98ba43 100644
--- a/docs/src/rules/quote-props.md
+++ b/docs/src/rules/quote-props.md
@@ -8,9 +8,7 @@ further_reading:
- https://mathiasbynens.be/notes/javascript-properties
---
-
-Requires quotes around object literal property names.
Object literal property names can be defined in two ways: using literals or using strings. For example, these two objects are equivalent:
@@ -68,6 +66,8 @@ Object option:
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint quote-props: ["error", "always"]*/
@@ -77,8 +77,12 @@ var object = {
};
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint quote-props: ["error", "always"]*/
/*eslint-env es6*/
@@ -102,10 +106,14 @@ var object3 = {
};
```
+:::
+
### as-needed
Examples of **incorrect** code for this rule with the `"as-needed"` option:
+::: incorrect
+
```js
/*eslint quote-props: ["error", "as-needed"]*/
@@ -117,8 +125,12 @@ var object = {
};
```
+:::
+
Examples of **correct** code for this rule with the `"as-needed"` option:
+::: correct
+
```js
/*eslint quote-props: ["error", "as-needed"]*/
/*eslint-env es6*/
@@ -144,10 +156,14 @@ var object3 = {
};
```
+:::
+
### consistent
Examples of **incorrect** code for this rule with the `"consistent"` option:
+::: incorrect
+
```js
/*eslint quote-props: ["error", "consistent"]*/
@@ -163,8 +179,12 @@ var object2 = {
};
```
+:::
+
Examples of **correct** code for this rule with the `"consistent"` option:
+::: correct
+
```js
/*eslint quote-props: ["error", "consistent"]*/
@@ -185,10 +205,14 @@ var object3 = {
};
```
+:::
+
### consistent-as-needed
Examples of **incorrect** code for this rule with the `"consistent-as-needed"` option:
+::: incorrect
+
```js
/*eslint quote-props: ["error", "consistent-as-needed"]*/
@@ -204,8 +228,12 @@ var object2 = {
};
```
+:::
+
Examples of **correct** code for this rule with the `"consistent-as-needed"` option:
+::: correct
+
```js
/*eslint quote-props: ["error", "consistent-as-needed"]*/
@@ -221,10 +249,14 @@ var object2 = {
};
```
+:::
+
### keywords
Examples of additional **incorrect** code for this rule with the `"as-needed", { "keywords": true }` options:
+::: incorrect
+
```js
/*eslint quote-props: ["error", "as-needed", { "keywords": true }]*/
@@ -234,8 +266,12 @@ var x = {
};
```
+:::
+
Examples of additional **incorrect** code for this rule with the `"consistent-as-needed", { "keywords": true }` options:
+::: incorrect
+
```js
/*eslint quote-props: ["error", "consistent-as-needed", { "keywords": true }]*/
@@ -245,10 +281,14 @@ var x = {
};
```
+:::
+
### unnecessary
Examples of additional **correct** code for this rule with the `"as-needed", { "unnecessary": false }` options:
+::: correct
+
```js
/*eslint quote-props: ["error", "as-needed", { "keywords": true, "unnecessary": false }]*/
@@ -258,10 +298,14 @@ var x = {
};
```
+:::
+
### numbers
Examples of additional **incorrect** code for this rule with the `"as-needed", { "numbers": true }` options:
+::: incorrect
+
```js
/*eslint quote-props: ["error", "as-needed", { "numbers": true }]*/
@@ -270,6 +314,8 @@ var x = {
}
```
+:::
+
## When Not To Use It
If you don't care if property names are consistently wrapped in quotes or not, and you don't target legacy ES3 environments, turn this rule off.
diff --git a/docs/src/rules/quotes.md b/docs/src/rules/quotes.md
index be42f89b717..9260c442339 100644
--- a/docs/src/rules/quotes.md
+++ b/docs/src/rules/quotes.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/quotes.md
rule_type: layout
---
-
-Enforces the consistent use of either backticks, double, or single quotes.
JavaScript allows you to define strings in one of three ways: double quotes, single quotes, and backticks (as of ECMAScript 6). For example:
@@ -48,6 +46,8 @@ Object option:
Examples of **incorrect** code for this rule with the default `"double"` option:
+::: incorrect
+
```js
/*eslint quotes: ["error", "double"]*/
@@ -56,8 +56,12 @@ var unescaped = 'a string containing "double" quotes';
var backtick = `back\ntick`; // you can use \n in single or double quoted strings
```
+:::
+
Examples of **correct** code for this rule with the default `"double"` option:
+::: correct
+
```js
/*eslint quotes: ["error", "double"]*/
/*eslint-env es6*/
@@ -68,10 +72,14 @@ tick`; // backticks are allowed due to newline
var backtick = tag`backtick`; // backticks are allowed due to tag
```
+:::
+
### single
Examples of **incorrect** code for this rule with the `"single"` option:
+::: incorrect
+
```js
/*eslint quotes: ["error", "single"]*/
@@ -79,8 +87,12 @@ var double = "double";
var unescaped = "a string containing 'single' quotes";
```
+:::
+
Examples of **correct** code for this rule with the `"single"` option:
+::: correct
+
```js
/*eslint quotes: ["error", "single"]*/
/*eslint-env es6*/
@@ -89,10 +101,14 @@ var single = 'single';
var backtick = `back${x}tick`; // backticks are allowed due to substitution
```
+:::
+
### backticks
Examples of **incorrect** code for this rule with the `"backtick"` option:
+::: incorrect
+
```js
/*eslint quotes: ["error", "backtick"]*/
@@ -101,8 +117,12 @@ var double = "double";
var unescaped = 'a string containing `backticks`';
```
+:::
+
Examples of **correct** code for this rule with the `"backtick"` option:
+::: correct
+
```js
/*eslint quotes: ["error", "backtick"]*/
/*eslint-env es6*/
@@ -110,36 +130,52 @@ Examples of **correct** code for this rule with the `"backtick"` option:
var backtick = `backtick`;
```
+:::
+
### avoidEscape
Examples of additional **correct** code for this rule with the `"double", { "avoidEscape": true }` options:
+::: correct
+
```js
/*eslint quotes: ["error", "double", { "avoidEscape": true }]*/
var single = 'a string containing "double" quotes';
```
+:::
+
Examples of additional **correct** code for this rule with the `"single", { "avoidEscape": true }` options:
+::: correct
+
```js
/*eslint quotes: ["error", "single", { "avoidEscape": true }]*/
var double = "a string containing 'single' quotes";
```
+:::
+
Examples of additional **correct** code for this rule with the `"backtick", { "avoidEscape": true }` options:
+::: correct
+
```js
/*eslint quotes: ["error", "backtick", { "avoidEscape": true }]*/
var double = "a string containing `backtick` quotes"
```
+:::
+
### allowTemplateLiterals
Examples of additional **correct** code for this rule with the `"double", { "allowTemplateLiterals": true }` options:
+::: correct
+
```js
/*eslint quotes: ["error", "double", { "allowTemplateLiterals": true }]*/
@@ -147,8 +183,12 @@ var double = "double";
var double = `double`;
```
+:::
+
Examples of additional **correct** code for this rule with the `"single", { "allowTemplateLiterals": true }` options:
+::: correct
+
```js
/*eslint quotes: ["error", "single", { "allowTemplateLiterals": true }]*/
@@ -156,6 +196,8 @@ var single = 'single';
var single = `single`;
```
+:::
+
`{ "allowTemplateLiterals": false }` will not disallow the usage of all template literals. If you want to forbid any instance of template literals, use [no-restricted-syntax](no-restricted-syntax) and target the `TemplateLiteral` selector.
## When Not To Use It
diff --git a/docs/src/rules/radix.md b/docs/src/rules/radix.md
index 09a67df4c63..e9220d71cab 100644
--- a/docs/src/rules/radix.md
+++ b/docs/src/rules/radix.md
@@ -7,9 +7,7 @@ further_reading:
- https://davidwalsh.name/parseint-radix
---
-
-Enforces the consistent use of the radix argument when using `parseInt()`.
When using the `parseInt()` function it is common to omit the second argument, the radix, and let the function try to determine from the first argument what type of number it is. By default, `parseInt()` will autodetect decimal and hexadecimal (via `0x` prefix). Prior to ECMAScript 5, `parseInt()` also autodetected octal literals, which caused problems because many developers assumed a leading `0` would be ignored.
@@ -44,6 +42,8 @@ There are two options for this rule:
Examples of **incorrect** code for the default `"always"` option:
+::: incorrect
+
```js
/*eslint radix: "error"*/
@@ -58,8 +58,12 @@ var num = parseInt("071", 37);
var num = parseInt();
```
+:::
+
Examples of **correct** code for the default `"always"` option:
+::: correct
+
```js
/*eslint radix: "error"*/
@@ -70,10 +74,14 @@ var num = parseInt("071", 8);
var num = parseFloat(someValue);
```
+:::
+
### as-needed
Examples of **incorrect** code for the `"as-needed"` option:
+::: incorrect
+
```js
/*eslint radix: ["error", "as-needed"]*/
@@ -84,8 +92,12 @@ var num = parseInt("071", "abc");
var num = parseInt();
```
+:::
+
Examples of **correct** code for the `"as-needed"` option:
+::: correct
+
```js
/*eslint radix: ["error", "as-needed"]*/
@@ -96,6 +108,8 @@ var num = parseInt("071", 8);
var num = parseFloat(someValue);
```
+:::
+
## When Not To Use It
If you don't want to enforce either presence or omission of the `10` radix value you can turn this rule off.
diff --git a/docs/src/rules/require-atomic-updates.md b/docs/src/rules/require-atomic-updates.md
index ee58f8115b0..43797e5079e 100644
--- a/docs/src/rules/require-atomic-updates.md
+++ b/docs/src/rules/require-atomic-updates.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/require-ato
rule_type: problem
---
-Disallows assignments that can lead to race conditions due to usage of `await` or `yield`.
When writing asynchronous code, it is possible to create subtle race condition bugs. Consider the following example:
@@ -64,6 +63,8 @@ Note that the rule does not report the assignment in step 3 in any of the follow
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/* eslint require-atomic-updates: error */
@@ -92,8 +93,12 @@ function* generator() {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/* eslint require-atomic-updates: error */
@@ -127,6 +132,8 @@ function* generator() {
}
```
+:::
+
### Properties
This rule reports an assignment to a property through a variable when it detects the following execution flow in a generator or async function:
@@ -139,6 +146,8 @@ This logic is similar to the logic for variables, but stricter because the prope
Example of **incorrect** code for this rule:
+::: incorrect
+
```js
/* eslint require-atomic-updates: error */
@@ -149,8 +158,12 @@ async function foo(obj) {
}
```
+:::
+
Example of **correct** code for this rule:
+::: correct
+
```js
/* eslint require-atomic-updates: error */
@@ -164,6 +177,8 @@ async function foo(obj) {
}
```
+:::
+
## Options
This rule has an object option:
@@ -174,6 +189,8 @@ This rule has an object option:
Example of **correct** code for this rule with the `{ "allowProperties": true }` option:
+::: correct
+
```js
/* eslint require-atomic-updates: ["error", { "allowProperties": true }] */
@@ -184,6 +201,8 @@ async function foo(obj) {
}
```
+:::
+
## When Not To Use It
If you don't use async or generator functions, you don't need to enable this rule.
diff --git a/docs/src/rules/require-await.md b/docs/src/rules/require-await.md
index 94226b129f3..f2f0bd948a3 100644
--- a/docs/src/rules/require-await.md
+++ b/docs/src/rules/require-await.md
@@ -7,7 +7,6 @@ related_rules:
- require-yield
---
-Disallows async functions which have no `await` expression.
Asynchronous functions in JavaScript behave differently than other functions in two important ways:
@@ -35,6 +34,8 @@ This rule warns async functions which have no `await` expression.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint require-await: "error"*/
@@ -47,8 +48,12 @@ bar(async () => {
});
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint require-await: "error"*/
@@ -72,6 +77,8 @@ bar(() => {
async function noop() {}
```
+:::
+
## When Not To Use It
Asynchronous functions are designed to work with promises such that throwing an error will cause a promise's rejection handler (such as `catch()`) to be called. For example:
diff --git a/docs/src/rules/require-jsdoc.md b/docs/src/rules/require-jsdoc.md
index 8bd899e79e1..6802a31f107 100644
--- a/docs/src/rules/require-jsdoc.md
+++ b/docs/src/rules/require-jsdoc.md
@@ -7,7 +7,6 @@ related_rules:
- valid-jsdoc
---
-Requires JSDoc comments.
This rule was [**deprecated**](https://eslint.org/blog/2018/11/jsdoc-end-of-life) in ESLint v5.10.0.
@@ -63,6 +62,8 @@ Default option settings are:
Examples of **incorrect** code for this rule with the `{ "require": { "FunctionDeclaration": true, "MethodDefinition": true, "ClassDeclaration": true, "ArrowFunctionExpression": true, "FunctionExpression": true } }` option:
+::: incorrect
+
```js
/*eslint "require-jsdoc": ["error", {
"require": {
@@ -103,8 +104,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule with the `{ "require": { "FunctionDeclaration": true, "MethodDefinition": true, "ClassDeclaration": true, "ArrowFunctionExpression": true, "FunctionExpression": true } }` option:
+::: correct
+
```js
/*eslint "require-jsdoc": ["error", {
"require": {
@@ -189,6 +194,8 @@ var foo = {
setTimeout(() => {}, 10); // since it's an anonymous arrow function
```
+:::
+
## When Not To Use It
If you do not require JSDoc for your functions, then you can leave this rule off.
diff --git a/docs/src/rules/require-unicode-regexp.md b/docs/src/rules/require-unicode-regexp.md
index 96d03569eb8..8b914281232 100644
--- a/docs/src/rules/require-unicode-regexp.md
+++ b/docs/src/rules/require-unicode-regexp.md
@@ -5,7 +5,6 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/require-uni
rule_type: suggestion
---
-Enforces the use of `u` flag on RegExp.
RegExp `u` flag has two effects:
@@ -32,6 +31,8 @@ This rule aims to enforce the use of `u` flag on regular expressions.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint require-unicode-regexp: error */
@@ -41,8 +42,12 @@ const c = new RegExp("ccc")
const d = new RegExp("ddd", "gi")
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint require-unicode-regexp: error */
@@ -57,6 +62,8 @@ function f(flags) {
}
```
+:::
+
## When Not To Use It
If you don't want to notify regular expressions with no `u` flag, then it's safe to disable this rule.
diff --git a/docs/src/rules/require-yield.md b/docs/src/rules/require-yield.md
index 08d183c1b79..1086eb5a587 100644
--- a/docs/src/rules/require-yield.md
+++ b/docs/src/rules/require-yield.md
@@ -7,9 +7,7 @@ related_rules:
- require-await
---
-
-Disallows generator functions that do not have `yield`.
## Rule Details
@@ -19,6 +17,8 @@ This rule generates warnings for generator functions that do not have the `yield
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint require-yield: "error"*/
/*eslint-env es6*/
@@ -28,8 +28,12 @@ function* foo() {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint require-yield: "error"*/
/*eslint-env es6*/
@@ -47,6 +51,8 @@ function foo() {
function* foo() { }
```
+:::
+
## When Not To Use It
If you don't want to notify generator functions that have no `yield` expression, then it's safe to disable this rule.
diff --git a/docs/src/rules/rest-spread-spacing.md b/docs/src/rules/rest-spread-spacing.md
index 1a9e71f8fdb..c124bb01ee8 100644
--- a/docs/src/rules/rest-spread-spacing.md
+++ b/docs/src/rules/rest-spread-spacing.md
@@ -7,9 +7,7 @@ further_reading:
- https://github.com/tc39/proposal-object-rest-spread
---
-
-Enforces spacing between rest and spread operators and their expressions.
ES2015 introduced the rest and spread operators, which expand an iterable structure into its individual parts. Some examples of their usage are as follows:
@@ -84,6 +82,8 @@ rest-spread-spacing: ["error", "never"]
Examples of **incorrect** code for this rule with `"never"`:
+::: incorrect
+
```js
/*eslint rest-spread-spacing: ["error", "never"]*/
@@ -95,8 +95,12 @@ let { x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 };
let n = { x, y, ... z };
```
+:::
+
Examples of **correct** code for this rule with `"never"`:
+::: correct
+
```js
/*eslint rest-spread-spacing: ["error", "never"]*/
@@ -108,6 +112,8 @@ let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
let n = { x, y, ...z };
```
+:::
+
### "always"
When using the `"always"` option, whitespace is required between spread operators and their expressions.
@@ -118,6 +124,8 @@ rest-spread-spacing: ["error", "always"]
Examples of **incorrect** code for this rule with `"always"`:
+::: incorrect
+
```js
/*eslint rest-spread-spacing:["error", "always"]*/
@@ -129,8 +137,12 @@ let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
let n = { x, y, ...z };
```
+:::
+
Examples of **correct** code for this rule with `"always"`:
+::: correct
+
```js
/*eslint rest-spread-spacing: ["error", "always"]*/
@@ -142,6 +154,8 @@ let { x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 };
let n = { x, y, ... z };
```
+:::
+
## When Not To Use It
You can safely disable this rule if you do not care about enforcing consistent spacing between spread operators and their expressions.
diff --git a/docs/src/rules/semi-spacing.md b/docs/src/rules/semi-spacing.md
index 8b60e16bf21..b7131b40a34 100644
--- a/docs/src/rules/semi-spacing.md
+++ b/docs/src/rules/semi-spacing.md
@@ -11,9 +11,7 @@ related_rules:
- space-in-parens
---
-
-Enforces spacing before and after semicolons.
JavaScript allows you to place unnecessary spaces before or after a semicolon.
@@ -56,6 +54,8 @@ This is the default option. It enforces spacing after semicolons and disallows s
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint semi-spacing: "error"*/
@@ -67,8 +67,12 @@ for (i = 0 ; i < 10 ; i++) {}
for (i = 0;i < 10;i++) {}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint semi-spacing: "error"*/
@@ -82,12 +86,16 @@ if (true) {;}
;foo();
```
+:::
+
### `{"before": true, "after": false}`
This option enforces spacing before semicolons and disallows spacing after semicolons.
Examples of **incorrect** code for this rule with the `{"before": true, "after": false}` option:
+::: incorrect
+
```js
/*eslint semi-spacing: ["error", { "before": true, "after": false }]*/
@@ -99,8 +107,12 @@ for (i = 0;i < 10;i++) {}
for (i = 0; i < 10; i++) {}
```
+:::
+
Examples of **correct** code for this rule with the `{"before": true, "after": false}` option:
+::: correct
+
```js
/*eslint semi-spacing: ["error", { "before": true, "after": false }]*/
@@ -111,6 +123,8 @@ while (a) {break ;}
for (i = 0 ;i < 10 ;i++) {}
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing before or after semicolons.
diff --git a/docs/src/rules/semi-style.md b/docs/src/rules/semi-style.md
index 0cf379c3bcd..2082539ffe2 100644
--- a/docs/src/rules/semi-style.md
+++ b/docs/src/rules/semi-style.md
@@ -9,9 +9,7 @@ related_rules:
- semi-spacing
---
-
-Enforces location of semicolons.
Generally, semicolons are at the end of lines. However, in semicolon-less style, semicolons are at the beginning of lines. This rule enforces that semicolons are at the configured location.
@@ -32,6 +30,8 @@ This rule has an option.
Examples of **incorrect** code for this rule with `"last"` option:
+::: incorrect
+
```js
/*eslint semi-style: ["error", "last"]*/
@@ -54,8 +54,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with `"last"` option:
+::: correct
+
```js
/*eslint semi-style: ["error", "last"]*/
@@ -78,8 +82,12 @@ class C {
}
```
+:::
+
Examples of **incorrect** code for this rule with `"first"` option:
+::: incorrect
+
```js
/*eslint semi-style: ["error", "first"]*/
@@ -102,8 +110,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule with `"first"` option:
+::: correct
+
```js
/*eslint semi-style: ["error", "first"]*/
@@ -126,6 +138,8 @@ class C {
}
```
+:::
+
## When Not To Use It
If you don't want to notify the location of semicolons, then it's safe to disable this rule.
diff --git a/docs/src/rules/semi.md b/docs/src/rules/semi.md
index 10147935769..cb5a37b0f28 100644
--- a/docs/src/rules/semi.md
+++ b/docs/src/rules/semi.md
@@ -12,9 +12,7 @@ further_reading:
- https://web.archive.org/web/20200420230322/http://inimino.org/~inimino/blog/javascript_semicolons
---
-
-Requires or disallows semicolons instead of ASI.
JavaScript doesn't require semicolons at the end of each statement. In many cases, the JavaScript engine can determine that a semicolon should be in a certain spot and will automatically add it. This feature is known as **automatic semicolon insertion (ASI)** and is considered one of the more controversial features of JavaScript. For example, the following lines are both valid:
@@ -98,6 +96,8 @@ Object option (when `"never"`):
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint semi: ["error", "always"]*/
@@ -112,8 +112,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint semi: "error"*/
@@ -128,10 +132,14 @@ class Foo {
}
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint semi: ["error", "never"]*/
@@ -146,8 +154,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint semi: ["error", "never"]*/
@@ -178,10 +190,14 @@ class Foo {
}
```
+:::
+
#### omitLastInOneLineBlock
Examples of additional **correct** code for this rule with the `"always", { "omitLastInOneLineBlock": true }` options:
+::: correct
+
```js
/*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */
@@ -198,10 +214,14 @@ class C {
}
```
+:::
+
#### beforeStatementContinuationChars
Examples of additional **incorrect** code for this rule with the `"never", { "beforeStatementContinuationChars": "always" }` options:
+::: incorrect
+
```js
/*eslint semi: ["error", "never", { "beforeStatementContinuationChars": "always"}] */
import a from "a"
@@ -211,8 +231,12 @@ import a from "a"
})()
```
+:::
+
Examples of additional **incorrect** code for this rule with the `"never", { "beforeStatementContinuationChars": "never" }` options:
+::: incorrect
+
```js
/*eslint semi: ["error", "never", { "beforeStatementContinuationChars": "never"}] */
import a from "a"
@@ -222,6 +246,8 @@ import a from "a"
})()
```
+:::
+
## When Not To Use It
If you do not want to enforce semicolon usage (or omission) in any particular way, then you can turn this rule off.
diff --git a/docs/src/rules/sort-imports.md b/docs/src/rules/sort-imports.md
index 9f8459fda99..f82c892c6bc 100644
--- a/docs/src/rules/sort-imports.md
+++ b/docs/src/rules/sort-imports.md
@@ -8,9 +8,7 @@ related_rules:
- sort-vars
---
-
-Enforces sorted import declarations within modules.
The import statement is used to import members (functions, objects or primitives) that have been exported from an external module. Using a specific member syntax:
@@ -75,6 +73,8 @@ Default option settings are:
Examples of **correct** code for this rule when using default options:
+::: correct
+
```js
/*eslint sort-imports: "error"*/
import 'module-without-export.js';
@@ -101,8 +101,12 @@ import {d} from 'quux.js';
import {a, b, c} from 'foo.js'
```
+:::
+
Examples of **incorrect** code for this rule when using default options:
+::: incorrect
+
```js
/*eslint sort-imports: "error"*/
import b from 'foo.js';
@@ -132,12 +136,16 @@ import * as b from 'bar.js';
import {b, a, c} from 'foo.js'
```
+:::
+
### `ignoreCase`
When `true` the rule ignores the case-sensitivity of the imports local name.
Examples of **incorrect** code for this rule with the `{ "ignoreCase": true }` option:
+::: incorrect
+
```js
/*eslint sort-imports: ["error", { "ignoreCase": true }]*/
@@ -145,8 +153,12 @@ import B from 'foo.js';
import a from 'bar.js';
```
+:::
+
Examples of **correct** code for this rule with the `{ "ignoreCase": true }` option:
+::: correct
+
```js
/*eslint sort-imports: ["error", { "ignoreCase": true }]*/
@@ -155,6 +167,8 @@ import B from 'bar.js';
import c from 'baz.js';
```
+:::
+
Default is `false`.
### `ignoreDeclarationSort`
@@ -163,26 +177,38 @@ Ignores the sorting of import declaration statements.
Examples of **incorrect** code for this rule with the default `{ "ignoreDeclarationSort": false }` option:
+::: incorrect
+
```js
/*eslint sort-imports: ["error", { "ignoreDeclarationSort": false }]*/
import b from 'foo.js'
import a from 'bar.js'
```
+:::
+
Examples of **correct** code for this rule with the `{ "ignoreDeclarationSort": true }` option:
+::: correct
+
```js
/*eslint sort-imports: ["error", { "ignoreDeclarationSort": true }]*/
import a from 'foo.js'
import b from 'bar.js'
```
+:::
+
+::: correct
+
```js
/*eslint sort-imports: ["error", { "ignoreDeclarationSort": true }]*/
import b from 'foo.js'
import a from 'bar.js'
```
+:::
+
Default is `false`.
### `ignoreMemberSort`
@@ -191,18 +217,26 @@ Ignores the member sorting within a `multiple` member import declaration.
Examples of **incorrect** code for this rule with the default `{ "ignoreMemberSort": false }` option:
+::: incorrect
+
```js
/*eslint sort-imports: ["error", { "ignoreMemberSort": false }]*/
import {b, a, c} from 'foo.js'
```
+:::
+
Examples of **correct** code for this rule with the `{ "ignoreMemberSort": true }` option:
+::: correct
+
```js
/*eslint sort-imports: ["error", { "ignoreMemberSort": true }]*/
import {b, a, c} from 'foo.js'
```
+:::
+
Default is `false`.
### `memberSyntaxSortOrder`
@@ -218,14 +252,20 @@ All four options must be specified in the array, but you can customize their ord
Examples of **incorrect** code for this rule with the default `{ "memberSyntaxSortOrder": ["none", "all", "multiple", "single"] }` option:
+::: incorrect
+
```js
/*eslint sort-imports: "error"*/
import a from 'foo.js';
import * as b from 'bar.js';
```
+:::
+
Examples of **correct** code for this rule with the `{ "memberSyntaxSortOrder": ['single', 'all', 'multiple', 'none'] }` option:
+::: correct
+
```js
/*eslint sort-imports: ["error", { "memberSyntaxSortOrder": ['single', 'all', 'multiple', 'none'] }]*/
@@ -233,8 +273,12 @@ import a from 'foo.js';
import * as b from 'bar.js';
```
+:::
+
Examples of **correct** code for this rule with the `{ "memberSyntaxSortOrder": ['all', 'single', 'multiple', 'none'] }` option:
+::: correct
+
```js
/*eslint sort-imports: ["error", { "memberSyntaxSortOrder": ['all', 'single', 'multiple', 'none'] }]*/
@@ -243,6 +287,8 @@ import z from 'zoo.js';
import {a, b} from 'foo.js';
```
+:::
+
Default is `["none", "all", "multiple", "single"]`.
### `allowSeparatedGroups`
@@ -253,6 +299,8 @@ In other words, a blank line or a comment line or line with any other statement
Examples of **incorrect** code for this rule with the `{ "allowSeparatedGroups": true }` option:
+::: incorrect
+
```js
/*eslint sort-imports: ["error", { "allowSeparatedGroups": true }]*/
@@ -261,8 +309,12 @@ import c from 'bar.js';
import a from 'baz.js';
```
+:::
+
Examples of **correct** code for this rule with the `{ "allowSeparatedGroups": true }` option:
+::: correct
+
```js
/*eslint sort-imports: ["error", { "allowSeparatedGroups": true }]*/
@@ -272,6 +324,10 @@ import c from 'bar.js';
import a from 'baz.js';
```
+:::
+
+::: correct
+
```js
/*eslint sort-imports: ["error", { "allowSeparatedGroups": true }]*/
@@ -281,6 +337,10 @@ import c from 'bar.js';
import a from 'baz.js';
```
+:::
+
+::: correct
+
```js
/*eslint sort-imports: ["error", { "allowSeparatedGroups": true }]*/
@@ -290,6 +350,8 @@ quux();
import a from 'baz.js';
```
+:::
+
Default is `false`.
## When Not To Use It
diff --git a/docs/src/rules/sort-keys.md b/docs/src/rules/sort-keys.md
index 1a803b19c22..f4047cde3e5 100644
--- a/docs/src/rules/sort-keys.md
+++ b/docs/src/rules/sort-keys.md
@@ -8,7 +8,6 @@ related_rules:
- sort-vars
---
-Requires object keys to be sorted.
When declaring multiple properties, some developers prefer to sort property names alphabetically to more easily find and/or diff necessary properties at a later time. Others feel that it adds complexity and becomes burden to maintain.
@@ -18,6 +17,8 @@ This rule checks all property definitions of object expressions and verifies tha
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint sort-keys: "error"*/
/*eslint-env es6*/
@@ -38,8 +39,12 @@ let obj = {a: 1, ["c"]: 3, b: 2};
let obj = {a: 1, [S]: 3, b: 2};
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint sort-keys: "error"*/
/*eslint-env es6*/
@@ -67,6 +72,8 @@ let obj = {a: 1, [tag`c`]: 3, b: 2};
let obj = {b: 1, ...c, a: 2};
```
+:::
+
## Options
```json
@@ -85,6 +92,7 @@ The 2nd option is an object which has 3 properties.
* `caseSensitive` - if `true`, enforce properties to be in case-sensitive order. Default is `true`.
* `minKeys` - Specifies the minimum number of keys that an object should have in order for the object's unsorted keys to produce an error. Default is `2`, which means by default all objects with unsorted keys will result in lint errors.
* `natural` - if `true`, enforce properties to be in natural order. Default is `false`. Natural Order compares strings containing combination of letters and numbers in the way a human being would sort. It basically sorts numerically, instead of sorting alphabetically. So the number 10 comes after the number 3 in Natural Sorting.
+* `allowLineSeparatedGroups` - if `true`, the rule allows to group object keys through line breaks. In other words, a blank line after a property will reset the sorting of keys. Default is `false`.
Example for a list:
@@ -106,6 +114,8 @@ With `natural` as false, the ordering would be
Examples of **incorrect** code for the `"desc"` option:
+::: incorrect
+
```js
/*eslint sort-keys: ["error", "desc"]*/
/*eslint-env es6*/
@@ -120,8 +130,12 @@ let obj = {C: 1, b: 3, a: 2};
let obj = {10: b, 2: c, 1: a};
```
+:::
+
Examples of **correct** code for the `"desc"` option:
+::: correct
+
```js
/*eslint sort-keys: ["error", "desc"]*/
/*eslint-env es6*/
@@ -136,10 +150,14 @@ let obj = {b: 3, a: 2, C: 1};
let obj = {2: c, 10: b, 1: a};
```
+:::
+
### insensitive
Examples of **incorrect** code for the `{caseSensitive: false}` option:
+::: incorrect
+
```js
/*eslint sort-keys: ["error", "asc", {caseSensitive: false}]*/
/*eslint-env es6*/
@@ -148,8 +166,12 @@ let obj = {a: 1, c: 3, C: 4, b: 2};
let obj = {a: 1, C: 3, c: 4, b: 2};
```
+:::
+
Examples of **correct** code for the `{caseSensitive: false}` option:
+::: correct
+
```js
/*eslint sort-keys: ["error", "asc", {caseSensitive: false}]*/
/*eslint-env es6*/
@@ -158,10 +180,14 @@ let obj = {a: 1, b: 2, c: 3, C: 4};
let obj = {a: 1, b: 2, C: 3, c: 4};
```
+:::
+
### natural
Examples of **incorrect** code for the `{natural: true}` option:
+::: incorrect
+
```js
/*eslint sort-keys: ["error", "asc", {natural: true}]*/
/*eslint-env es6*/
@@ -169,8 +195,12 @@ Examples of **incorrect** code for the `{natural: true}` option:
let obj = {1: a, 10: c, 2: b};
```
+:::
+
Examples of **correct** code for the `{natural: true}` option:
+::: correct
+
```js
/*eslint sort-keys: ["error", "asc", {natural: true}]*/
/*eslint-env es6*/
@@ -178,10 +208,14 @@ Examples of **correct** code for the `{natural: true}` option:
let obj = {1: a, 2: b, 10: c};
```
+:::
+
### minKeys
Examples of **incorrect** code for the `{minKeys: 4}` option:
+::: incorrect
+
```js
/*eslint sort-keys: ["error", "asc", {minKeys: 4}]*/
/*eslint-env es6*/
@@ -204,8 +238,12 @@ let obj = {
};
```
+:::
+
Examples of **correct** code for the `{minKeys: 4}` option:
+::: correct
+
```js
/*eslint sort-keys: ["error", "asc", {minKeys: 4}]*/
/*eslint-env es6*/
@@ -224,6 +262,130 @@ let obj = {
};
```
+:::
+
+### allowLineSeparatedGroups
+
+Examples of **incorrect** code for the `{allowLineSeparatedGroups: true}` option:
+
+::: incorrect
+
+```js
+/*eslint sort-keys: ["error", "asc", {allowLineSeparatedGroups: true}]*/
+/*eslint-env es6*/
+
+let obj1 = {
+ b: 1,
+ c () {
+
+ },
+ a: 3
+}
+
+let obj2 = {
+ b: 1,
+ c: 2,
+
+ z () {
+
+ },
+ y: 3
+}
+
+let obj3 = {
+ b: 1,
+ c: 2,
+
+ z () {
+
+ },
+ // comment
+ y: 3,
+}
+
+let obj4 = {
+ b: 1
+ // comment before comma
+ , a: 2
+};
+```
+
+:::
+
+Examples of **correct** code for the `{allowLineSeparatedGroups: true}` option:
+
+::: correct
+
+```js
+/*eslint sort-keys: ["error", "asc", {allowLineSeparatedGroups: true}]*/
+/*eslint-env es6*/
+
+let obj = {
+ e: 1,
+ f: 2,
+ g: 3,
+
+ a: 4,
+ b: 5,
+ c: 6
+}
+
+let obj = {
+ b: 1,
+
+ // comment
+ a: 4,
+ c: 5,
+}
+
+let obj = {
+ c: 1,
+ d: 2,
+
+ b () {
+
+ },
+ e: 3,
+}
+
+let obj = {
+ c: 1,
+ d: 2,
+ // comment
+
+ // comment
+ b() {
+
+ },
+ e: 4
+}
+
+let obj = {
+ b,
+
+ [foo + bar]: 1,
+ a
+}
+
+let obj = {
+ b: 1
+ // comment before comma
+
+ ,
+ a: 2
+};
+
+var obj = {
+ b: 1,
+
+ a: 2,
+ ...z,
+ c: 3
+}
+```
+
+:::
+
## When Not To Use It
If you don't want to notify about properties' order, then it's safe to disable this rule.
diff --git a/docs/src/rules/sort-vars.md b/docs/src/rules/sort-vars.md
index a0282a65f82..bcb82427471 100644
--- a/docs/src/rules/sort-vars.md
+++ b/docs/src/rules/sort-vars.md
@@ -8,9 +8,7 @@ related_rules:
- sort-imports
---
-
-Requires variables within the same declaration block to be sorted.
When declaring multiple variables within the same block, some developers prefer to sort variable names alphabetically to be able to find necessary variable easier at the later time. Others feel that it adds complexity and becomes burden to maintain.
@@ -21,6 +19,8 @@ The default configuration of the rule is case-sensitive.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint sort-vars: "error"*/
@@ -31,8 +31,12 @@ var a, B, c;
var a, A;
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint sort-vars: "error"*/
@@ -46,6 +50,8 @@ var A, a;
var B, a, c;
```
+:::
+
Alphabetical list is maintained starting from the first variable and excluding any that are considered problems. So the following code will produce two problems:
```js
@@ -72,6 +78,8 @@ This rule has an object option:
Examples of **correct** code for this rule with the `{ "ignoreCase": true }` option:
+::: correct
+
```js
/*eslint sort-vars: ["error", { "ignoreCase": true }]*/
@@ -80,6 +88,8 @@ var a, A;
var a, B, c;
```
+:::
+
## When Not To Use It
This rule is a formatting preference and not following it won't negatively affect the quality of your code. If you alphabetizing variables isn't a part of your coding standards, then you can leave this rule off.
diff --git a/docs/src/rules/space-after-function-name.md b/docs/src/rules/space-after-function-name.md
index 390198fdd47..047f7be757a 100644
--- a/docs/src/rules/space-after-function-name.md
+++ b/docs/src/rules/space-after-function-name.md
@@ -29,6 +29,8 @@ This rule aims to enforce a consistent spacing after function names. It takes on
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
function foo (x) {
// ...
@@ -42,8 +44,12 @@ function bar(x) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
function foo(x) {
// ...
@@ -56,3 +62,5 @@ function bar (x) {
// ...
}
```
+
+:::
diff --git a/docs/src/rules/space-after-keywords.md b/docs/src/rules/space-after-keywords.md
index 36ff74aa194..a7805adebb1 100644
--- a/docs/src/rules/space-after-keywords.md
+++ b/docs/src/rules/space-after-keywords.md
@@ -36,6 +36,8 @@ then there should be no spaces following. The default is `"always"`.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint space-after-keywords: "error"*/
@@ -46,14 +48,22 @@ if (a) {} else{}
do{} while (a);
```
+:::
+
+::: incorrect
+
```js
/*eslint space-after-keywords: ["error", "never"]*/
if (a) {}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint space-after-keywords: "error"*/
@@ -62,8 +72,14 @@ if (a) {}
if (a) {} else {}
```
+:::
+
+::: correct
+
```js
/*eslint space-after-keywords: ["error", "never"]*/
if(a) {}
```
+
+:::
diff --git a/docs/src/rules/space-before-blocks.md b/docs/src/rules/space-before-blocks.md
index 0af8e7d0b9b..742665f529f 100644
--- a/docs/src/rules/space-before-blocks.md
+++ b/docs/src/rules/space-before-blocks.md
@@ -11,9 +11,7 @@ related_rules:
- brace-style
---
-
-Requires Or disallows space before blocks.
Consistency is an important part of any style guide.
While it is a personal preference where to put the opening brace of blocks,
@@ -43,6 +41,8 @@ The default is `"always"`.
Examples of **incorrect** code for this rule with the "always" option:
+::: incorrect
+
```js
/*eslint space-before-blocks: "error"*/
@@ -63,8 +63,12 @@ class Foo{
}
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint space-before-blocks: "error"*/
@@ -91,10 +95,14 @@ for (;;) {
try {} catch(a) {}
```
+:::
+
### "never"
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint space-before-blocks: ["error", "never"]*/
@@ -111,8 +119,12 @@ for (;;) {
try {} catch(a) {}
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint space-before-blocks: ["error", "never"]*/
@@ -133,8 +145,12 @@ class Foo{
}
```
+:::
+
Examples of **incorrect** code for this rule when configured `{ "functions": "never", "keywords": "always", "classes": "never" }`:
+::: incorrect
+
```js
/*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "always", "classes": "never" }]*/
/*eslint-env es6*/
@@ -148,8 +164,12 @@ class Foo{
}
```
+:::
+
Examples of **correct** code for this rule when configured `{ "functions": "never", "keywords": "always", "classes": "never" }`:
+::: correct
+
```js
/*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "always", "classes": "never" }]*/
/*eslint-env es6*/
@@ -167,8 +187,12 @@ class Foo{
}
```
+:::
+
Examples of **incorrect** code for this rule when configured `{ "functions": "always", "keywords": "never", "classes": "never" }`:
+::: incorrect
+
```js
/*eslint space-before-blocks: ["error", { "functions": "always", "keywords": "never", "classes": "never" }]*/
/*eslint-env es6*/
@@ -182,8 +206,12 @@ class Foo {
}
```
+:::
+
Examples of **correct** code for this rule when configured `{ "functions": "always", "keywords": "never", "classes": "never" }`:
+::: correct
+
```js
/*eslint space-before-blocks: ["error", { "functions": "always", "keywords": "never", "classes": "never" }]*/
/*eslint-env es6*/
@@ -199,8 +227,12 @@ class Foo{
}
```
+:::
+
Examples of **incorrect** code for this rule when configured `{ "functions": "never", "keywords": "never", "classes": "always" }`:
+::: incorrect
+
```js
/*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "never", "classes": "always" }]*/
/*eslint-env es6*/
@@ -210,8 +242,12 @@ class Foo{
}
```
+:::
+
Examples of **correct** code for this rule when configured `{ "functions": "never", "keywords": "never", "classes": "always" }`:
+::: correct
+
```js
/*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "never", "classes": "always" }]*/
/*eslint-env es6*/
@@ -221,6 +257,8 @@ class Foo {
}
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing before blocks.
diff --git a/docs/src/rules/space-before-function-paren.md b/docs/src/rules/space-before-function-paren.md
index ad0a20b57a4..f825ee9d779 100644
--- a/docs/src/rules/space-before-function-paren.md
+++ b/docs/src/rules/space-before-function-paren.md
@@ -8,9 +8,7 @@ related_rules:
- space-return-throw-case
---
-
-Requires or disallows a space before function parenthesis.
When formatting a function, whitespace is allowed between the function name or `function` keyword and the opening paren. Named functions also require a space between the `function` keyword and the function name, but anonymous functions require no whitespace. For example:
@@ -66,6 +64,8 @@ Each of the following options can be set to `"always"`, `"never"`, or `"ignore"`
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint space-before-function-paren: "error"*/
/*eslint-env es6*/
@@ -97,8 +97,12 @@ var foo = {
var foo = async() => 1
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint space-before-function-paren: "error"*/
/*eslint-env es6*/
@@ -130,10 +134,14 @@ var foo = {
var foo = async () => 1
```
+:::
+
### "never"
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint space-before-function-paren: ["error", "never"]*/
/*eslint-env es6*/
@@ -165,8 +173,12 @@ var foo = {
var foo = async () => 1
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint space-before-function-paren: ["error", "never"]*/
/*eslint-env es6*/
@@ -198,10 +210,14 @@ var foo = {
var foo = async() => 1
```
+:::
+
### `{"anonymous": "always", "named": "never", "asyncArrow": "always"}`
Examples of **incorrect** code for this rule with the `{"anonymous": "always", "named": "never", "asyncArrow": "always"}` option:
+::: incorrect
+
```js
/*eslint space-before-function-paren: ["error", {"anonymous": "always", "named": "never", "asyncArrow": "always"}]*/
/*eslint-env es6*/
@@ -229,8 +245,12 @@ var foo = {
var foo = async(a) => await a
```
+:::
+
Examples of **correct** code for this rule with the `{"anonymous": "always", "named": "never", "asyncArrow": "always"}` option:
+::: correct
+
```js
/*eslint space-before-function-paren: ["error", {"anonymous": "always", "named": "never", "asyncArrow": "always"}]*/
/*eslint-env es6*/
@@ -258,10 +278,14 @@ var foo = {
var foo = async (a) => await a
```
+:::
+
### `{"anonymous": "never", "named": "always"}`
Examples of **incorrect** code for this rule with the `{"anonymous": "never", "named": "always"}` option:
+::: incorrect
+
```js
/*eslint space-before-function-paren: ["error", { "anonymous": "never", "named": "always" }]*/
/*eslint-env es6*/
@@ -287,8 +311,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule with the `{"anonymous": "never", "named": "always"}` option:
+::: correct
+
```js
/*eslint space-before-function-paren: ["error", { "anonymous": "never", "named": "always" }]*/
/*eslint-env es6*/
@@ -314,10 +342,14 @@ var foo = {
};
```
+:::
+
### `{"anonymous": "ignore", "named": "always"}`
Examples of **incorrect** code for this rule with the `{"anonymous": "ignore", "named": "always"}` option:
+::: incorrect
+
```js
/*eslint space-before-function-paren: ["error", { "anonymous": "ignore", "named": "always" }]*/
/*eslint-env es6*/
@@ -339,8 +371,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule with the `{"anonymous": "ignore", "named": "always"}` option:
+::: correct
+
```js
/*eslint space-before-function-paren: ["error", { "anonymous": "ignore", "named": "always" }]*/
/*eslint-env es6*/
@@ -370,6 +406,8 @@ var foo = {
};
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing before function parenthesis.
diff --git a/docs/src/rules/space-before-function-parentheses.md b/docs/src/rules/space-before-function-parentheses.md
index 2bc0e3b7433..1b2ed43e6e6 100644
--- a/docs/src/rules/space-before-function-parentheses.md
+++ b/docs/src/rules/space-before-function-parentheses.md
@@ -38,6 +38,8 @@ This rule takes one argument. If it is `"always"`, which is the default option,
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint-env es6*/
@@ -66,8 +68,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint-env es6*/
@@ -96,8 +102,12 @@ var foo = {
};
```
+:::
+
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint-env es6*/
@@ -126,8 +136,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint-env es6*/
@@ -156,8 +170,12 @@ var foo = {
};
```
+:::
+
Examples of **incorrect** code for this rule with the `{"anonymous": "always", "named": "never"}` option:
+::: incorrect
+
```js
/*eslint-env es6*/
@@ -182,8 +200,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule with the `{"anonymous": "always", "named": "never"}` option:
+::: correct
+
```js
/*eslint-env es6*/
@@ -208,8 +230,12 @@ var foo = {
};
```
+:::
+
Examples of **incorrect** code for this rule with the `{"anonymous": "never", "named": "always"}` option:
+::: incorrect
+
```js
/*eslint-env es6*/
@@ -234,8 +260,12 @@ var foo = {
};
```
+:::
+
Examples of **correct** code for this rule with the `{"anonymous": "never", "named": "always"}` option:
+::: correct
+
```js
/*eslint-env es6*/
@@ -260,6 +290,8 @@ var foo = {
};
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing before function parenthesis.
diff --git a/docs/src/rules/space-before-keywords.md b/docs/src/rules/space-before-keywords.md
index 361a2626804..bc484717779 100644
--- a/docs/src/rules/space-before-keywords.md
+++ b/docs/src/rules/space-before-keywords.md
@@ -45,6 +45,8 @@ this behavior, consider using the [block-spacing](block-spacing) rule.
Examples of **incorrect** code for this rule with the default `"always"` option:
+::: incorrect
+
```js
/*eslint space-before-keywords: ["error", "always"]*/
/*eslint-env es6*/
@@ -62,8 +64,12 @@ function bar() {
}
```
+:::
+
Examples of **correct** code for this rule with the default `"always"` option:
+::: correct
+
```js
/*eslint space-before-keywords: ["error", "always"]*/
/*eslint-env es6*/
@@ -79,8 +85,12 @@ if (foo) {
for (let foo of ['bar', 'baz', 'qux']) {}
```
+:::
+
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint space-before-keywords: ["error", "never"]*/
@@ -98,8 +108,12 @@ try {} finally {}
try {} catch(e) {}
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint space-before-keywords: ["error", "never"]*/
@@ -114,6 +128,8 @@ try {}finally {}
try{}catch(e) {}
```
+:::
+
## When Not To Use It
If you do not wish to enforce consistency on keyword spacing.
diff --git a/docs/src/rules/space-in-brackets.md b/docs/src/rules/space-in-brackets.md
index 4deafc6dde5..15941dedb84 100644
--- a/docs/src/rules/space-in-brackets.md
+++ b/docs/src/rules/space-in-brackets.md
@@ -47,6 +47,8 @@ Depending on your coding conventions, you can choose either option by specifying
Examples of **incorrect** code for this rule with the default `"never"` option:
+::: incorrect
+
```js
/*eslint-env es6*/
@@ -67,8 +69,12 @@ var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux' }, bar};
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+::: correct
+
```js
// When options are ["error", "never"]
@@ -107,10 +113,14 @@ var obj = {
var obj = {};
```
+:::
+
### "always"
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint-env es6*/
@@ -140,8 +150,12 @@ var obj = {
'foo':'bar'};
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
foo[ 'bar' ];
foo[
@@ -166,6 +180,8 @@ var obj = {
};
```
+:::
+
Note that `"always"` has a special case where `{}` and `[]` are not considered problems.
### Exceptions
@@ -213,6 +229,8 @@ In each of the following examples, the `"always"` option is assumed.
Examples of **incorrect** code for this rule when `"singleValue"` is set to `false`:
+::: incorrect
+
```js
var foo = [ 'foo' ];
var foo = [ 'foo'];
@@ -224,8 +242,12 @@ var foo = [ [ 1, 2 ] ];
var foo = [ { 'foo': 'bar' } ];
```
+:::
+
Examples of **correct** code for this rule when `"singleValue"` is set to `false`:
+::: correct
+
```js
var foo = ['foo'];
var foo = [1];
@@ -233,8 +255,12 @@ var foo = [[ 1, 1 ]];
var foo = [{ 'foo': 'bar' }];
```
+:::
+
Examples of **incorrect** code when `"objectsInArrays"` is set to `false`:
+::: incorrect
+
```js
var arr = [ { 'foo': 'bar' } ];
var arr = [ {
@@ -242,8 +268,12 @@ var arr = [ {
} ]
```
+:::
+
Examples of **correct** code when `"objectsInArrays"` is set to `false`:
+::: correct
+
```js
var arr = [{ 'foo': 'bar' }];
var arr = [{
@@ -251,62 +281,96 @@ var arr = [{
}];
```
+:::
+
Examples of **incorrect** code when `"arraysInArrays"` is set to `false`:
+::: incorrect
+
```js
var arr = [ [ 1, 2 ], 2, 3, 4 ];
var arr = [ [ 1, 2 ], 2, [ 3, 4 ] ];
```
+:::
+
Examples of **correct** code when `"arraysInArrays"` is set to `false`:
+::: correct
+
```js
var arr = [[ 1, 2 ], 2, 3, 4 ];
var arr = [[ 1, 2 ], 2, [ 3, 4 ]];
```
+:::
+
Examples of **incorrect** code when `"arraysInObjects"` is set to `false`:
+::: incorrect
+
```js
var obj = { "foo": [ 1, 2 ] };
var obj = { "foo": [ "baz", "bar" ] };
```
+:::
+
Examples of **correct** code when `"arraysInObjects"` is set to `false`:
+::: correct
+
```js
var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
```
+:::
+
Examples of **incorrect** code when `"objectsInObjects"` is set to `false`:
+::: incorrect
+
```js
var obj = { "foo": { "baz": 1, "bar": 2 } };
var obj = { "foo": [ "baz", "bar" ], "qux": { "baz": 1, "bar": 2 } };
```
+:::
+
Examples of **correct** code when `"objectsInObjects"` is set to `false`:
+::: correct
+
```js
var obj = { "foo": { "baz": 1, "bar": 2 }};
var obj = { "foo": [ "baz", "bar" ], "qux": { "baz": 1, "bar": 2 }};
```
+:::
+
Examples of **incorrect** code when `"propertyName"` is set to `false`:
+::: incorrect
+
```js
var foo = obj[ 1 ];
var foo = obj[ bar ];
```
+:::
+
Examples of **correct** code when `"propertyName"` is set to `false`:
+::: correct
+
```js
var foo = obj[bar];
var foo = obj[0, 1];
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between brackets.
diff --git a/docs/src/rules/space-in-parens.md b/docs/src/rules/space-in-parens.md
index 0625410ccf6..fea11f6e857 100644
--- a/docs/src/rules/space-in-parens.md
+++ b/docs/src/rules/space-in-parens.md
@@ -9,9 +9,7 @@ related_rules:
- computed-property-spacing
---
-
-Disallows or enforce spaces inside of parentheses.
Some style guides require or disallow spaces inside of parentheses:
@@ -46,6 +44,8 @@ Depending on your coding conventions, you can choose either option by specifying
Examples of **incorrect** code for this rule with the default `"never"` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "never"]*/
@@ -61,8 +61,12 @@ var foo = ( 1 + 2 ) * 3;
( function () { return 'bar'; }() );
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "never"]*/
@@ -76,10 +80,14 @@ var foo = (1 + 2) * 3;
(function () { return 'bar'; }());
```
+:::
+
### "always"
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "always"]*/
@@ -93,8 +101,12 @@ var foo = (1 + 2) * 3;
(function () { return 'bar'; }());
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "always"]*/
@@ -109,6 +121,8 @@ var foo = ( 1 + 2 ) * 3;
( function () { return 'bar'; }() );
```
+:::
+
### Exceptions
An object literal may be used as a third array item to specify exceptions, with the key `"exceptions"` and an array as the value. These exceptions work in the context of the first option. That is, if `"always"` is set to enforce spacing, then any "exception" will *disallow* spacing. Conversely, if `"never"` is set to disallow spacing, then any "exception" will *enforce* spacing.
@@ -130,6 +144,8 @@ Empty parens exception and behavior:
Examples of **incorrect** code for this rule with the `"never", { "exceptions": ["{}"] }` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "never", { "exceptions": ["{}"] }]*/
@@ -137,8 +153,12 @@ foo({bar: 'baz'});
foo(1, {bar: 'baz'});
```
+:::
+
Examples of **correct** code for this rule with the `"never", { "exceptions": ["{}"] }` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "never", { "exceptions": ["{}"] }]*/
@@ -146,8 +166,12 @@ foo( {bar: 'baz'} );
foo(1, {bar: 'baz'} );
```
+:::
+
Examples of **incorrect** code for this rule with the `"always", { "exceptions": ["{}"] }` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["{}"] }]*/
@@ -155,8 +179,12 @@ foo( {bar: 'baz'} );
foo( 1, {bar: 'baz'} );
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "exceptions": ["{}"] }` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["{}"] }]*/
@@ -164,8 +192,12 @@ foo({bar: 'baz'});
foo( 1, {bar: 'baz'});
```
+:::
+
Examples of **incorrect** code for this rule with the `"never", { "exceptions": ["[]"] }` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "never", { "exceptions": ["[]"] }]*/
@@ -173,8 +205,12 @@ foo([bar, baz]);
foo([bar, baz], 1);
```
+:::
+
Examples of **correct** code for this rule with the `"never", { "exceptions": ["[]"] }` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "never", { "exceptions": ["[]"] }]*/
@@ -182,8 +218,12 @@ foo( [bar, baz] );
foo( [bar, baz], 1);
```
+:::
+
Examples of **incorrect** code for this rule with the `"always", { "exceptions": ["[]"] }` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["[]"] }]*/
@@ -191,8 +231,12 @@ foo( [bar, baz] );
foo( [bar, baz], 1 );
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "exceptions": ["[]"] }` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["[]"] }]*/
@@ -200,8 +244,12 @@ foo([bar, baz]);
foo([bar, baz], 1 );
```
+:::
+
Examples of **incorrect** code for this rule with the `"never", { "exceptions": ["()"] }]` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "never", { "exceptions": ["()"] }]*/
@@ -210,8 +258,12 @@ foo((1 + 2), 1);
foo(bar());
```
+:::
+
Examples of **correct** code for this rule with the `"never", { "exceptions": ["()"] }]` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "never", { "exceptions": ["()"] }]*/
@@ -220,8 +272,12 @@ foo( (1 + 2), 1);
foo(bar() );
```
+:::
+
Examples of **incorrect** code for this rule with the `"always", { "exceptions": ["()"] }]` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["()"] }]*/
@@ -229,8 +285,12 @@ foo( ( 1 + 2 ) );
foo( ( 1 + 2 ), 1 );
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "exceptions": ["()"] }]` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["()"] }]*/
@@ -238,44 +298,64 @@ foo(( 1 + 2 ));
foo(( 1 + 2 ), 1 );
```
+:::
+
The `"empty"` exception concerns empty parentheses, and works the same way as the other exceptions, inverting the first option.
Example of **incorrect** code for this rule with the `"never", { "exceptions": ["empty"] }]` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "never", { "exceptions": ["empty"] }]*/
foo();
```
+:::
+
Example of **correct** code for this rule with the `"never", { "exceptions": ["empty"] }]` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "never", { "exceptions": ["empty"] }]*/
foo( );
```
+:::
+
Example of **incorrect** code for this rule with the `"always", { "exceptions": ["empty"] }]` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["empty"] }]*/
foo( );
```
+:::
+
Example of **correct** code for this rule with the `"always", { "exceptions": ["empty"] }]` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["empty"] }]*/
foo();
```
+:::
+
You can include multiple entries in the `"exceptions"` array.
Examples of **incorrect** code for this rule with the `"always", { "exceptions": ["{}", "[]"] }]` option:
+::: incorrect
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["{}", "[]"] }]*/
@@ -284,8 +364,12 @@ baz( 1, [1,2] );
foo( {bar: 'baz'}, [1, 2] );
```
+:::
+
Examples of **correct** code for this rule with the `"always", { "exceptions": ["{}", "[]"] }]` option:
+::: correct
+
```js
/*eslint space-in-parens: ["error", "always", { "exceptions": ["{}", "[]"] }]*/
@@ -294,6 +378,8 @@ baz( 1, [1,2]);
foo({bar: 'baz'}, [1, 2]);
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between parentheses.
diff --git a/docs/src/rules/space-infix-ops.md b/docs/src/rules/space-infix-ops.md
index aa079b51114..c7a7d4ad444 100644
--- a/docs/src/rules/space-infix-ops.md
+++ b/docs/src/rules/space-infix-ops.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/space-infix
rule_type: layout
---
-
-Requires spacing around infix operators.
While formatting preferences are very personal, a number of style guides require spaces around operators, such as:
@@ -45,6 +43,8 @@ var foo = bar|0; // `foo` is forced to be signed 32 bit integer
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint space-infix-ops: "error"*/
/*eslint-env es6*/
@@ -64,8 +64,12 @@ var {a=0}=bar;
function foo(a=0) { }
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint space-infix-ops: "error"*/
/*eslint-env es6*/
@@ -83,6 +87,8 @@ var {a = 0} = bar;
function foo(a = 0) { }
```
+:::
+
## When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing around infix operators.
diff --git a/docs/src/rules/space-return-throw-case.md b/docs/src/rules/space-return-throw-case.md
index 6bf9ba199b2..ca65dd75840 100644
--- a/docs/src/rules/space-return-throw-case.md
+++ b/docs/src/rules/space-return-throw-case.md
@@ -17,6 +17,8 @@ Require spaces following `return`, `throw`, and `case`.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint space-return-throw-case: "error"*/
@@ -27,8 +29,12 @@ function f(){ return-a; }
switch(a){ case'a': break; }
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint space-return-throw-case: "error"*/
@@ -38,3 +44,5 @@ function f(){ return -a; }
switch(a){ case 'a': break; }
```
+
+:::
diff --git a/docs/src/rules/space-unary-ops.md b/docs/src/rules/space-unary-ops.md
index d413ff68651..adac27429f1 100644
--- a/docs/src/rules/space-unary-ops.md
+++ b/docs/src/rules/space-unary-ops.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/space-unary
rule_type: layout
---
-
-Requires or disallow spaces before/after unary operators.
Some style guides require or disallow spaces before or after unary operators. This is mainly a stylistic issue, however, some JavaScript expressions can be written without spacing which makes it harder to read and maintain.
@@ -72,6 +70,8 @@ In this case, spacing will be disallowed after a `new` operator and required bef
Examples of **incorrect** code for this rule with the default `{"words": true, "nonwords": false}` option:
+::: incorrect
+
```js
/*eslint space-unary-ops: "error"*/
@@ -92,6 +92,10 @@ foo --;
+ "3";
```
+:::
+
+::: incorrect
+
```js
/*eslint space-unary-ops: "error"*/
/*eslint-env es6*/
@@ -101,6 +105,10 @@ function *foo() {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint space-unary-ops: "error"*/
@@ -109,8 +117,12 @@ async function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `{"words": true, "nonwords": false}` option:
+::: correct
+
```js
/*eslint space-unary-ops: "error"*/
@@ -139,6 +151,10 @@ foo--;
+"3";
```
+:::
+
+::: correct
+
```js
/*eslint space-unary-ops: "error"*/
/*eslint-env es6*/
@@ -148,6 +164,10 @@ function *foo() {
}
```
+:::
+
+::: correct
+
```js
/*eslint space-unary-ops: "error"*/
@@ -155,3 +175,5 @@ async function foo() {
await (bar);
}
```
+
+:::
diff --git a/docs/src/rules/space-unary-word-ops.md b/docs/src/rules/space-unary-word-ops.md
index eb5d3d95e0c..15629ae821c 100644
--- a/docs/src/rules/space-unary-word-ops.md
+++ b/docs/src/rules/space-unary-word-ops.md
@@ -15,32 +15,60 @@ Require spaces following unary word operators.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
typeof!a
```
+:::
+
+::: incorrect
+
```js
void{a:0}
```
+:::
+
+::: incorrect
+
```js
new[a][0]
```
+:::
+
+::: incorrect
+
```js
delete(a.b)
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
delete a.b
```
+:::
+
+::: correct
+
```js
new C
```
+:::
+
+::: correct
+
```js
void 0
```
+
+:::
diff --git a/docs/src/rules/spaced-comment.md b/docs/src/rules/spaced-comment.md
index 6d9c6398220..35ff1baf486 100644
--- a/docs/src/rules/spaced-comment.md
+++ b/docs/src/rules/spaced-comment.md
@@ -7,9 +7,7 @@ related_rules:
- spaced-line-comment
---
-
-Enforces consistent spacing after the `//` or `/*` in a comment.
Some style guides require or disallow a whitespace immediately after the initial `//` or `/*` of a comment.
Whitespace after the `//` or `/*` makes it easier to read text in comments.
@@ -76,6 +74,8 @@ You can also define separate exceptions and markers for block and line comments.
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint spaced-comment: ["error", "always"]*/
@@ -84,13 +84,21 @@ Examples of **incorrect** code for this rule with the `"always"` option:
/*This is a comment with no whitespace at the beginning */
```
+:::
+
+::: incorrect
+
```js
/* eslint spaced-comment: ["error", "always", { "block": { "balanced": true } }] */
/* This is a comment with whitespace at the beginning but not the end*/
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always"] */
@@ -107,6 +115,10 @@ This comment has a newline
*/
```
+:::
+
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always"] */
@@ -115,10 +127,14 @@ This comment has a newline
*/
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint spaced-comment: ["error", "never"]*/
@@ -129,19 +145,31 @@ Examples of **incorrect** code for this rule with the `"never"` option:
/* \nThis is a comment with a whitespace at the beginning */
```
+:::
+
+::: incorrect
+
```js
/*eslint spaced-comment: ["error", "never", { "block": { "balanced": true } }]*/
/*This is a comment with whitespace at the end */
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint spaced-comment: ["error", "never"]*/
/*This is a comment with no whitespace at the beginning */
```
+:::
+
+::: correct
+
```js
/*eslint spaced-comment: ["error", "never"]*/
@@ -150,10 +178,14 @@ Examples of **correct** code for this rule with the `"never"` option:
*/
```
+:::
+
### exceptions
Examples of **incorrect** code for this rule with the `"always"` option combined with `"exceptions"`:
+::: incorrect
+
```js
/* eslint spaced-comment: ["error", "always", { "block": { "exceptions": ["-"] } }] */
@@ -162,6 +194,10 @@ Examples of **incorrect** code for this rule with the `"always"` option combined
//--------------
```
+:::
+
+::: incorrect
+
```js
/* eslint spaced-comment: ["error", "always", { "exceptions": ["-", "+"] }] */
@@ -170,6 +206,10 @@ Examples of **incorrect** code for this rule with the `"always"` option combined
//------++++++++
```
+:::
+
+::: incorrect
+
```js
/* eslint spaced-comment: ["error", "always", { "exceptions": ["-", "+"] }] */
@@ -178,6 +218,10 @@ Examples of **incorrect** code for this rule with the `"always"` option combined
/*------++++++++*/
```
+:::
+
+::: incorrect
+
```js
/* eslint spaced-comment: ["error", "always", { "line": { "exceptions": ["-+"] } }] */
@@ -186,14 +230,22 @@ Examples of **incorrect** code for this rule with the `"always"` option combined
/*-+-+-+-+-+-+-+*/
```
+:::
+
+::: incorrect
+
```js
/* eslint spaced-comment: ["error", "always", { "block": { "exceptions": ["*"] } }] */
/******** COMMENT *******/
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option combined with `"exceptions"`:
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always", { "exceptions": ["-"] }] */
@@ -202,6 +254,10 @@ Examples of **correct** code for this rule with the `"always"` option combined w
//--------------
```
+:::
+
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always", { "line": { "exceptions": ["-"] } }] */
@@ -210,6 +266,10 @@ Examples of **correct** code for this rule with the `"always"` option combined w
//--------------
```
+:::
+
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always", { "exceptions": ["*"] }] */
@@ -218,6 +278,10 @@ Examples of **correct** code for this rule with the `"always"` option combined w
****************/
```
+:::
+
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always", { "exceptions": ["-+"] }] */
@@ -230,6 +294,10 @@ Examples of **correct** code for this rule with the `"always"` option combined w
/*-+-+-+-+-+-+-+*/
```
+:::
+
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always", { "block": { "exceptions": ["-+"] } }] */
@@ -238,6 +306,10 @@ Examples of **correct** code for this rule with the `"always"` option combined w
/*-+-+-+-+-+-+-+*/
```
+:::
+
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always", { "block": { "exceptions": ["*"] } }] */
@@ -248,34 +320,54 @@ COMMENT
*******/
```
+:::
+
### markers
Examples of **incorrect** code for this rule with the `"always"` option combined with `"markers"`:
+::: incorrect
+
```js
/* eslint spaced-comment: ["error", "always", { "markers": ["/"] }] */
///This is a comment with a marker but without whitespace
```
+:::
+
+::: incorrect
+
```js
/*eslint spaced-comment: ["error", "always", { "block": { "markers": ["!"], "balanced": true } }]*/
/*! This is a comment with a marker but without whitespace at the end*/
```
+:::
+
+::: incorrect
+
```js
/*eslint spaced-comment: ["error", "never", { "block": { "markers": ["!"], "balanced": true } }]*/
/*!This is a comment with a marker but with whitespace at the end */
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option combined with `"markers"`:
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always", { "markers": ["/"] }] */
/// This is a comment with a marker
```
+:::
+
+::: correct
+
```js
/*eslint spaced-comment: ["error", "never", { "markers": ["!<"] }]*/
@@ -286,8 +378,14 @@ subsequent lines are ignored
*/
```
+:::
+
+::: correct
+
```js
/* eslint spaced-comment: ["error", "always", { "markers": ["global"] }] */
/*global ABC*/
```
+
+:::
diff --git a/docs/src/rules/spaced-line-comment.md b/docs/src/rules/spaced-line-comment.md
index ea5247bd6be..78d0ace2d28 100644
--- a/docs/src/rules/spaced-line-comment.md
+++ b/docs/src/rules/spaced-line-comment.md
@@ -30,17 +30,27 @@ Exceptions cannot be mixed.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
// When ["never"]
// This is a comment with a whitespace at the beginning
```
+:::
+
+::: incorrect
+
```js
//When ["always"]
//This is a comment with no whitespace at the beginning
var foo = 5;
```
+:::
+
+::: incorrect
+
```js
// When ["always",{"exceptions":["-","+"]}]
//------++++++++
@@ -48,20 +58,32 @@ var foo = 5;
//------++++++++
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
// When ["always"]
// This is a comment with a whitespace at the beginning
var foo = 5;
```
+:::
+
+::: correct
+
```js
//When ["never"]
//This is a comment with no whitespace at the beginning
var foo = 5;
```
+:::
+
+::: correct
+
```js
// When ["always",{"exceptions":["-"]}]
//--------------
@@ -69,9 +91,15 @@ var foo = 5;
//--------------
```
+:::
+
+::: correct
+
```js
// When ["always",{"exceptions":["-+"]}]
//-+-+-+-+-+-+-+
// Comment block
//-+-+-+-+-+-+-+
```
+
+:::
diff --git a/docs/src/rules/strict.md b/docs/src/rules/strict.md
index df14488edca..4fbf09af1fa 100644
--- a/docs/src/rules/strict.md
+++ b/docs/src/rules/strict.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/strict.md
rule_type: suggestion
---
-
-Requires or disallow strict mode directives.
A strict mode directive is a `"use strict"` literal at the beginning of a script or function body. It enables strict mode semantics.
@@ -86,6 +84,8 @@ Otherwise the `"safe"` option corresponds to the `"function"` option. Note that
Examples of **incorrect** code for this rule with the `"global"` option:
+::: incorrect
+
```js
/*eslint strict: ["error", "global"]*/
@@ -93,6 +93,10 @@ function foo() {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint strict: ["error", "global"]*/
@@ -101,6 +105,10 @@ function foo() {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint strict: ["error", "global"]*/
@@ -111,8 +119,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `"global"` option:
+::: correct
+
```js
/*eslint strict: ["error", "global"]*/
@@ -122,12 +134,16 @@ function foo() {
}
```
+:::
+
### function
This option ensures that all function bodies are strict mode code, while global code is not. Particularly if a build step concatenates multiple scripts, a strict mode directive in global code of one script could unintentionally enable strict mode in another script that was not intended to be strict code.
Examples of **incorrect** code for this rule with the `"function"` option:
+::: incorrect
+
```js
/*eslint strict: ["error", "function"]*/
@@ -137,6 +153,10 @@ function foo() {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint strict: ["error", "function"]*/
@@ -150,6 +170,10 @@ function foo() {
}());
```
+:::
+
+::: incorrect
+
```js
/*eslint strict: ["error", "function"]*/
/*eslint-env es6*/
@@ -166,8 +190,12 @@ function foo(a = 1) {
}
```
+:::
+
Examples of **correct** code for this rule with the `"function"` option:
+::: correct
+
```js
/*eslint strict: ["error", "function"]*/
@@ -193,10 +221,14 @@ var foo = (function() {
}());
```
+:::
+
### never
Examples of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint strict: ["error", "never"]*/
@@ -206,6 +238,10 @@ function foo() {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint strict: ["error", "never"]*/
@@ -214,8 +250,12 @@ function foo() {
}
```
+:::
+
Examples of **correct** code for this rule with the `"never"` option:
+::: correct
+
```js
/*eslint strict: ["error", "never"]*/
@@ -223,6 +263,8 @@ function foo() {
}
```
+:::
+
### earlier default (removed)
(removed) The default option (that is, no string option specified) for this rule was **removed** in ESLint v1.0. The `"function"` option is most similar to the removed option.
@@ -231,6 +273,8 @@ This option ensures that all functions are executed in strict mode. A strict mod
Examples of **incorrect** code for this rule with the earlier default option which has been removed:
+::: incorrect
+
```js
// "strict": "error"
@@ -238,6 +282,10 @@ function foo() {
}
```
+:::
+
+::: incorrect
+
```js
// "strict": "error"
@@ -248,8 +296,12 @@ function foo() {
}());
```
+:::
+
Examples of **correct** code for this rule with the earlier default option which has been removed:
+::: correct
+
```js
// "strict": "error"
@@ -259,6 +311,10 @@ function foo() {
}
```
+:::
+
+::: correct
+
```js
// "strict": "error"
@@ -267,6 +323,10 @@ function foo() {
}
```
+:::
+
+::: correct
+
```js
// "strict": "error"
@@ -278,6 +338,8 @@ function foo() {
}());
```
+:::
+
## When Not To Use It
In a codebase that has both strict and non-strict code, either turn this rule off, or [selectively disable it](/docs/user-guide/configuring/rules#disabling-rules) where necessary. For example, functions referencing `arguments.callee` are invalid in strict mode. A [full list of strict mode differences](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode#Differences_from_non-strict_to_strict) is available on MDN.
diff --git a/docs/src/rules/switch-colon-spacing.md b/docs/src/rules/switch-colon-spacing.md
index 1106bdb8026..4dfff02896d 100644
--- a/docs/src/rules/switch-colon-spacing.md
+++ b/docs/src/rules/switch-colon-spacing.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/switch-colo
rule_type: layout
---
-
-Enforces spacing around colons of switch statements.
Spacing around colons improves readability of `case`/`default` clauses.
@@ -31,6 +29,8 @@ This rule has 2 options that are boolean value.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint switch-colon-spacing: "error"*/
@@ -40,8 +40,12 @@ switch (a) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint switch-colon-spacing: "error"*/
@@ -56,8 +60,12 @@ switch (a) {
}
```
+:::
+
Examples of **incorrect** code for this rule with `{"after": false, "before": true}` option:
+::: incorrect
+
```js
/*eslint switch-colon-spacing: ["error", {"after": false, "before": true}]*/
@@ -67,8 +75,12 @@ switch (a) {
}
```
+:::
+
Examples of **correct** code for this rule with `{"after": false, "before": true}` option:
+::: correct
+
```js
/*eslint switch-colon-spacing: ["error", {"after": false, "before": true}]*/
@@ -83,6 +95,8 @@ switch (a) {
}
```
+:::
+
## When Not To Use It
If you don't want to notify spacing around colons of switch statements, then it's safe to disable this rule.
diff --git a/docs/src/rules/symbol-description.md b/docs/src/rules/symbol-description.md
index d33284a46a0..44be78bd783 100644
--- a/docs/src/rules/symbol-description.md
+++ b/docs/src/rules/symbol-description.md
@@ -7,7 +7,6 @@ further_reading:
- https://www.ecma-international.org/ecma-262/6.0/#sec-symbol-description
---
-Requires symbol descriptions.
The `Symbol` function may have an optional description:
@@ -37,6 +36,8 @@ This rules requires a description when creating symbols.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint symbol-description: "error"*/
/*eslint-env es6*/
@@ -44,8 +45,12 @@ Examples of **incorrect** code for this rule:
var foo = Symbol();
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint symbol-description: "error"*/
/*eslint-env es6*/
@@ -56,6 +61,8 @@ var someString = "some description";
var bar = Symbol(someString);
```
+:::
+
## When Not To Use It
This rule should not be used in ES3/5 environments.
diff --git a/docs/src/rules/template-curly-spacing.md b/docs/src/rules/template-curly-spacing.md
index eff2aa98146..4eca3b980e3 100644
--- a/docs/src/rules/template-curly-spacing.md
+++ b/docs/src/rules/template-curly-spacing.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/template-cu
rule_type: layout
---
-
-Enforces usage of spacing in template strings.
We can embed expressions in template strings with using a pair of `${` and `}`.
@@ -40,6 +38,8 @@ This rule has one option which has either `"never"` or `"always"` as value.
Examples of **incorrect** code for this rule with the default `"never"` option:
+::: incorrect
+
```js
/*eslint template-curly-spacing: "error"*/
@@ -49,8 +49,12 @@ Examples of **incorrect** code for this rule with the default `"never"` option:
`hello, ${ people.name }!`;
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+::: correct
+
```js
/*eslint template-curly-spacing: "error"*/
@@ -61,10 +65,14 @@ Examples of **correct** code for this rule with the default `"never"` option:
}!`;
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint template-curly-spacing: ["error", "always"]*/
@@ -74,8 +82,12 @@ Examples of **incorrect** code for this rule with the `"always"` option:
`hello, ${people.name}!`;
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint template-curly-spacing: ["error", "always"]*/
@@ -86,6 +98,8 @@ Examples of **correct** code for this rule with the `"always"` option:
}!`;
```
+:::
+
## When Not To Use It
If you don't want to be notified about usage of spacing inside of template strings, then it's safe to disable this rule.
diff --git a/docs/src/rules/template-tag-spacing.md b/docs/src/rules/template-tag-spacing.md
index a2ec2d6d68c..7289ddf27f4 100644
--- a/docs/src/rules/template-tag-spacing.md
+++ b/docs/src/rules/template-tag-spacing.md
@@ -8,9 +8,7 @@ further_reading:
- https://exploringjs.com/es6/ch_template-literals.html#_examples-of-using-tagged-template-literals
---
-
-Requires or disallow spacing between template tags and their literals.
With ES6, it's possible to create functions called [tagged template literals](#further-reading) where the function parameters consist of a template literal's strings and expressions.
@@ -44,38 +42,54 @@ This rule has one option whose value can be set to `"never"` or `"always"`
Examples of **incorrect** code for this rule with the default `"never"` option:
+::: incorrect
+
```js
/*eslint template-tag-spacing: "error"*/
func `Hello world`;
```
+:::
+
Examples of **correct** code for this rule with the default `"never"` option:
+::: correct
+
```js
/*eslint template-tag-spacing: "error"*/
func`Hello world`;
```
+:::
+
### always
Examples of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint template-tag-spacing: ["error", "always"]*/
func`Hello world`;
```
+:::
+
Examples of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint template-tag-spacing: ["error", "always"]*/
func `Hello world`;
```
+:::
+
## When Not To Use It
If you don't want to be notified about usage of spacing between tag functions and their template literals, then it's safe to disable this rule.
diff --git a/docs/src/rules/unicode-bom.md b/docs/src/rules/unicode-bom.md
index 878dfacca4f..fb9857e2cab 100644
--- a/docs/src/rules/unicode-bom.md
+++ b/docs/src/rules/unicode-bom.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/unicode-bom
rule_type: layout
---
-
-Requires or disallows the Unicode Byte Order Mark (BOM).
The Unicode Byte Order Mark (BOM) is used to specify whether code units are big
endian or little endian. That is, whether the most significant or least
@@ -32,6 +30,8 @@ This rule has a string option:
Example of **correct** code for this rule with the `"always"` option:
+::: correct
+
```js
/*eslint unicode-bom: ["error", "always"]*/
@@ -39,26 +39,38 @@ U+FEFF
var abc;
```
+:::
+
Example of **incorrect** code for this rule with the `"always"` option:
+::: incorrect
+
```js
/*eslint unicode-bom: ["error", "always"]*/
var abc;
```
+:::
+
### never
Example of **correct** code for this rule with the default `"never"` option:
+::: correct
+
```js
/*eslint unicode-bom: ["error", "never"]*/
var abc;
```
+:::
+
Example of **incorrect** code for this rule with the `"never"` option:
+::: incorrect
+
```js
/*eslint unicode-bom: ["error", "never"]*/
@@ -66,6 +78,8 @@ U+FEFF
var abc;
```
+:::
+
## When Not To Use It
If you use some UTF-16 or UTF-32 files and you want to allow a file to
diff --git a/docs/src/rules/use-isnan.md b/docs/src/rules/use-isnan.md
index 60a4f055173..cb27f751df2 100644
--- a/docs/src/rules/use-isnan.md
+++ b/docs/src/rules/use-isnan.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/use-isnan.m
rule_type: problem
---
-
-Requires calls to `isNaN()` when checking for `NaN`.
In JavaScript, `NaN` is a special value of the `Number` type. It's used to represent any of the "not-a-number" values represented by the double-precision 64-bit format as specified by the IEEE Standard for Binary Floating-Point Arithmetic.
@@ -24,6 +22,8 @@ This rule disallows comparisons to 'NaN'.
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint use-isnan: "error"*/
@@ -44,8 +44,12 @@ if (foo != Number.NaN) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint use-isnan: "error"*/
@@ -58,6 +62,8 @@ if (!isNaN(foo)) {
}
```
+:::
+
## Options
This rule has an object option, with two options:
@@ -72,6 +78,8 @@ Therefore, it can never match `case NaN`. Also, `switch(NaN)` can never match a
Examples of **incorrect** code for this rule with `"enforceForSwitchCase"` option set to `true` (default):
+::: incorrect
+
```js
/*eslint use-isnan: ["error", {"enforceForSwitchCase": true}]*/
@@ -116,8 +124,12 @@ switch (Number.NaN) {
}
```
+:::
+
Examples of **correct** code for this rule with `"enforceForSwitchCase"` option set to `true` (default):
+::: correct
+
```js
/*eslint use-isnan: ["error", {"enforceForSwitchCase": true}]*/
@@ -139,8 +151,12 @@ if (Number.isNaN(a)) {
} // ...
```
+:::
+
Examples of **correct** code for this rule with `"enforceForSwitchCase"` option set to `false`:
+::: correct
+
```js
/*eslint use-isnan: ["error", {"enforceForSwitchCase": false}]*/
@@ -185,6 +201,8 @@ switch (Number.NaN) {
}
```
+:::
+
### enforceForIndexOf
The following methods internally use the `===` comparison to match the given value with an array element:
@@ -198,6 +216,8 @@ Set `"enforceForIndexOf"` to `true` if you want this rule to report `indexOf(NaN
Examples of **incorrect** code for this rule with `"enforceForIndexOf"` option set to `true`:
+::: incorrect
+
```js
/*eslint use-isnan: ["error", {"enforceForIndexOf": true}]*/
@@ -208,8 +228,12 @@ var firstIndex = myArray.indexOf(NaN);
var lastIndex = myArray.lastIndexOf(NaN);
```
+:::
+
Examples of **correct** code for this rule with `"enforceForIndexOf"` option set to `true`:
+::: correct
+
```js
/*eslint use-isnan: ["error", {"enforceForIndexOf": true}]*/
@@ -253,6 +277,8 @@ var firstIndex = myArray.findIndex(Number.isNaN);
var hasNaN = myArray.includes(NaN);
```
+:::
+
#### Known Limitations
This option checks methods with the given names, *even if* the object which has the method is *not* an array.
diff --git a/docs/src/rules/valid-jsdoc.md b/docs/src/rules/valid-jsdoc.md
index c7bed2ef882..b12f6b96f47 100644
--- a/docs/src/rules/valid-jsdoc.md
+++ b/docs/src/rules/valid-jsdoc.md
@@ -9,9 +9,7 @@ further_reading:
- https://jsdoc.app
---
-
-Enforces valid JSDoc comments.
This rule was [**deprecated**](https://eslint.org/blog/2018/11/jsdoc-end-of-life) in ESLint v5.10.0.
@@ -50,6 +48,8 @@ This rule does not report missing JSDoc comments for classes, functions, or meth
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint valid-jsdoc: "error"*/
@@ -88,8 +88,12 @@ function sum(num1, num2) {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint valid-jsdoc: "error"*/
/*eslint-env es6*/
@@ -165,6 +169,8 @@ class WonderfulWidget extends Widget {
}
```
+:::
+
## Options
This rule has an object option:
@@ -184,6 +190,8 @@ This rule has an object option:
Examples of additional **incorrect** code for this rule with sample `"prefer": { "arg": "param", "argument": "param", "class": "constructor", "return": "returns", "virtual": "abstract" }` options:
+::: incorrect
+
```js
/*eslint valid-jsdoc: ["error", { "prefer": { "arg": "param", "argument": "param", "class": "constructor", "return": "returns", "virtual": "abstract" } }]*/
/*eslint-env es6*/
@@ -222,10 +230,14 @@ class Widget {
}
```
+:::
+
### preferType
Examples of additional **incorrect** code for this rule with sample `"preferType": { "Boolean": "boolean", "Number": "number", "object": "Object", "String": "string" }` options:
+::: incorrect
+
```js
/*eslint valid-jsdoc: ["error", { "preferType": { "Boolean": "boolean", "Number": "number", "object": "Object", "String": "string" } }]*/
/*eslint-env es6*/
@@ -262,10 +274,14 @@ class Widget {
}
```
+:::
+
### requireReturn
Examples of additional **incorrect** code for this rule with the `"requireReturn": false` option:
+::: incorrect
+
```js
/*eslint valid-jsdoc: ["error", { "requireReturn": false }]*/
@@ -291,8 +307,12 @@ class Widget {
}
```
+:::
+
Example of additional **correct** code for this rule with the `"requireReturn": false` option:
+::: correct
+
```js
/*eslint valid-jsdoc: ["error", { "requireReturn": false }]*/
@@ -304,10 +324,14 @@ function greet(name) {
}
```
+:::
+
### requireReturnType
Example of additional **correct** code for this rule with the `"requireReturnType": false` option:
+::: correct
+
```js
/*eslint valid-jsdoc: ["error", { "requireReturnType": false }]*/
@@ -322,10 +346,14 @@ function add(num1, num2) {
}
```
+:::
+
### requireParamType
Example of additional **correct** code for this rule with the `"requireParamType": false` option:
+::: correct
+
```js
/*eslint valid-jsdoc: ["error", { "requireParamType": false }]*/
@@ -340,10 +368,14 @@ function add(num1, num2) {
}
```
+:::
+
### matchDescription
Example of additional **incorrect** code for this rule with a sample `"matchDescription": ".+"` option:
+::: incorrect
+
```js
/*eslint valid-jsdoc: ["error", { "matchDescription": ".+" }]*/
@@ -357,10 +389,14 @@ function greet(name) {
}
```
+:::
+
### requireParamDescription
Example of additional **correct** code for this rule with the `"requireParamDescription": false` option:
+::: correct
+
```js
/*eslint valid-jsdoc: ["error", { "requireParamDescription": false }]*/
@@ -375,10 +411,14 @@ function add(num1, num2) {
}
```
+:::
+
### requireReturnDescription
Example of additional **correct** code for this rule with the `"requireReturnDescription": false` option:
+::: correct
+
```js
/*eslint valid-jsdoc: ["error", { "requireReturnDescription": false }]*/
@@ -393,6 +433,8 @@ function add(num1, num2) {
}
```
+:::
+
## When Not To Use It
If you aren't using JSDoc, then you can safely turn this rule off.
diff --git a/docs/src/rules/valid-typeof.md b/docs/src/rules/valid-typeof.md
index b43884fea1d..45a30a3f368 100644
--- a/docs/src/rules/valid-typeof.md
+++ b/docs/src/rules/valid-typeof.md
@@ -7,11 +7,9 @@ further_reading:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
---
-
-
-Enforces comparing `typeof` expressions against valid strings.
+
For a vast majority of use cases, the result of the `typeof` operator is one of the following string literals: `"undefined"`, `"object"`, `"boolean"`, `"number"`, `"string"`, `"function"`, `"symbol"`, and `"bigint"`. It is usually a typing mistake to compare the result of a `typeof` operator to other string literals.
@@ -27,6 +25,8 @@ This rule has an object option:
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint valid-typeof: "error"*/
@@ -36,8 +36,12 @@ typeof bar != "nunber"
typeof bar !== "fucntion"
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint valid-typeof: "error"*/
@@ -47,8 +51,12 @@ typeof foo === baz
typeof bar === typeof qux
```
+:::
+
Examples of **incorrect** code with the `{ "requireStringLiterals": true }` option:
+::: incorrect
+
```js
/*eslint valid-typeof: ["error", { "requireStringLiterals": true }]*/
@@ -60,8 +68,12 @@ typeof baz === anotherVariable
typeof foo == 5
```
+:::
+
Examples of **correct** code with the `{ "requireStringLiterals": true }` option:
+::: correct
+
```js
/*eslint valid-typeof: ["error", { "requireStringLiterals": true }]*/
@@ -71,6 +83,8 @@ typeof baz === "string"
typeof bar === typeof qux
```
+:::
+
## When Not To Use It
You may want to turn this rule off if you will be using the `typeof` operator on host objects.
diff --git a/docs/src/rules/vars-on-top.md b/docs/src/rules/vars-on-top.md
index 39a25c4a483..72384d32935 100644
--- a/docs/src/rules/vars-on-top.md
+++ b/docs/src/rules/vars-on-top.md
@@ -10,7 +10,6 @@ further_reading:
- https://benalman.com/news/2012/05/multiple-var-statements-javascript/
---
-Requires variable declarations to be at the top of their scope.
The `vars-on-top` rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
@@ -23,6 +22,8 @@ Allowing multiple declarations helps promote maintainability and is thus allowed
Examples of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint vars-on-top: "error"*/
@@ -40,6 +41,10 @@ function doSomething() {
}
```
+:::
+
+::: incorrect
+
```js
/*eslint vars-on-top: "error"*/
@@ -48,6 +53,10 @@ f();
var a;
```
+:::
+
+::: incorrect
+
```js
/*eslint vars-on-top: "error"*/
@@ -71,8 +80,12 @@ class C {
}
```
+:::
+
Examples of **correct** code for this rule:
+::: correct
+
```js
/*eslint vars-on-top: "error"*/
@@ -90,6 +103,10 @@ function doSomething() {
}
```
+:::
+
+::: correct
+
```js
/*eslint vars-on-top: "error"*/
@@ -97,6 +114,10 @@ var a;
f();
```
+:::
+
+::: correct
+
```js
/*eslint vars-on-top: "error"*/
@@ -117,6 +138,10 @@ class C {
}
```
+:::
+
+::: correct
+
```js
/*eslint vars-on-top: "error"*/
@@ -133,3 +158,5 @@ function doSomething() {
var second
}
```
+
+:::
diff --git a/docs/src/rules/wrap-iife.md b/docs/src/rules/wrap-iife.md
index 0b9cd2d9748..3c6158f64c8 100644
--- a/docs/src/rules/wrap-iife.md
+++ b/docs/src/rules/wrap-iife.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/wrap-iife.m
rule_type: layout
---
-
-Requires IIFEs to be wrapped.
You can immediately invoke function expressions, but not function declarations. A common technique to create an immediately-invoked function expression (IIFE) is to wrap a function declaration in parentheses. The opening parentheses causes the contained function to be parsed as an expression, rather than a declaration.
@@ -41,6 +39,8 @@ Object option:
Examples of **incorrect** code for the default `"outside"` option:
+::: incorrect
+
```js
/*eslint wrap-iife: ["error", "outside"]*/
@@ -48,18 +48,26 @@ var x = function () { return { y: 1 };}(); // unwrapped
var x = (function () { return { y: 1 };})(); // wrapped function expression
```
+:::
+
Examples of **correct** code for the default `"outside"` option:
+::: correct
+
```js
/*eslint wrap-iife: ["error", "outside"]*/
var x = (function () { return { y: 1 };}()); // wrapped call expression
```
+:::
+
### inside
Examples of **incorrect** code for the `"inside"` option:
+::: incorrect
+
```js
/*eslint wrap-iife: ["error", "inside"]*/
@@ -67,26 +75,38 @@ var x = function () { return { y: 1 };}(); // unwrapped
var x = (function () { return { y: 1 };}()); // wrapped call expression
```
+:::
+
Examples of **correct** code for the `"inside"` option:
+::: correct
+
```js
/*eslint wrap-iife: ["error", "inside"]*/
var x = (function () { return { y: 1 };})(); // wrapped function expression
```
+:::
+
### any
Examples of **incorrect** code for the `"any"` option:
+::: incorrect
+
```js
/*eslint wrap-iife: ["error", "any"]*/
var x = function () { return { y: 1 };}(); // unwrapped
```
+:::
+
Examples of **correct** code for the `"any"` option:
+::: correct
+
```js
/*eslint wrap-iife: ["error", "any"]*/
@@ -94,10 +114,14 @@ var x = (function () { return { y: 1 };}()); // wrapped call expression
var x = (function () { return { y: 1 };})(); // wrapped function expression
```
+:::
+
### functionPrototypeMethods
Examples of **incorrect** code for this rule with the `"inside", { "functionPrototypeMethods": true }` options:
+::: incorrect
+
```js
/* eslint wrap-iife: [2, "inside", { functionPrototypeMethods: true }] */
@@ -107,11 +131,17 @@ var x = function(){ foo(); }.call(bar)
var x = (function(){ foo(); }.call(bar))
```
+:::
+
Examples of **correct** code for this rule with the `"inside", { "functionPrototypeMethods": true }` options:
+::: correct
+
```js
/* eslint wrap-iife: [2, "inside", { functionPrototypeMethods: true }] */
var x = (function(){ foo(); })()
var x = (function(){ foo(); }).call(bar)
```
+
+:::
diff --git a/docs/src/rules/wrap-regex.md b/docs/src/rules/wrap-regex.md
index 9249d703ea2..7b0204ed47d 100644
--- a/docs/src/rules/wrap-regex.md
+++ b/docs/src/rules/wrap-regex.md
@@ -5,9 +5,7 @@ edit_link: https://github.com/eslint/eslint/edit/main/docs/src/rules/wrap-regex.
rule_type: layout
---
-
-Requires regex literals to be wrapped.
When a regular expression is used in certain situations, it can end up looking like a division operator. For example:
@@ -23,6 +21,8 @@ This is used to disambiguate the slash operator and facilitates more readable co
Example of **incorrect** code for this rule:
+::: incorrect
+
```js
/*eslint wrap-regex: "error"*/
@@ -31,8 +31,12 @@ function a() {
}
```
+:::
+
Example of **correct** code for this rule:
+::: correct
+
```js
/*eslint wrap-regex: "error"*/
@@ -40,3 +44,5 @@ function a() {
return (/foo/).test("bar");
}
```
+
+:::
diff --git a/docs/src/rules/yield-star-spacing.md b/docs/src/rules/yield-star-spacing.md
index f97e00b5d69..d1d1ee5f291 100644
--- a/docs/src/rules/yield-star-spacing.md
+++ b/docs/src/rules/yield-star-spacing.md
@@ -7,9 +7,7 @@ further_reading:
- https://leanpub.com/understandinges6/read/#leanpub-auto-generators
---
-
-Enforces spacing around the `*` in `yield*` expressions.
## Rule Details
@@ -48,6 +46,8 @@ The option also has a string shorthand:
Examples of **correct** code for this rule with the default `"after"` option:
+::: correct
+
```js
/*eslint yield-star-spacing: ["error", "after"]*/
/*eslint-env es6*/
@@ -57,10 +57,14 @@ function* generator() {
}
```
+:::
+
### before
Examples of **correct** code for this rule with the `"before"` option:
+::: correct
+
```js
/*eslint yield-star-spacing: ["error", "before"]*/
/*eslint-env es6*/
@@ -70,10 +74,14 @@ function *generator() {
}
```
+:::
+
### both
Examples of **correct** code for this rule with the `"both"` option:
+::: correct
+
```js
/*eslint yield-star-spacing: ["error", "both"]*/
/*eslint-env es6*/
@@ -83,10 +91,14 @@ function * generator() {
}
```
+:::
+
### neither
Examples of **correct** code for this rule with the `"neither"` option:
+::: correct
+
```js
/*eslint yield-star-spacing: ["error", "neither"]*/
/*eslint-env es6*/
@@ -96,6 +108,8 @@ function*generator() {
}
```
+:::
+
## When Not To Use It
If your project will not be using generators or you are not concerned with spacing consistency, you do not need this rule.
diff --git a/docs/src/rules/yoda.md b/docs/src/rules/yoda.md
index 64ad9f4fbe8..4d2ba28cc53 100644
--- a/docs/src/rules/yoda.md
+++ b/docs/src/rules/yoda.md
@@ -8,9 +8,7 @@ further_reading:
- http://thomas.tuerke.net/on/design/?with=1249091668#msg1146181680
---
-
-Requires or disallows "Yoda" conditions.
Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:
@@ -56,6 +54,8 @@ The `onlyEquality` option allows a superset of the exceptions which `exceptRange
Examples of **incorrect** code for the default `"never"` option:
+::: incorrect
+
```js
/*eslint yoda: "error"*/
@@ -88,8 +88,12 @@ if (0 <= x && x < 1) {
}
```
+:::
+
Examples of **correct** code for the default `"never"` option:
+::: correct
+
```js
/*eslint yoda: "error"*/
@@ -110,10 +114,14 @@ if (`${value}` === `red`) {
}
```
+:::
+
### exceptRange
Examples of **correct** code for the `"never", { "exceptRange": true }` options:
+::: correct
+
```js
/*eslint yoda: ["error", "never", { "exceptRange": true }]*/
@@ -138,10 +146,14 @@ function howLong(arr) {
}
```
+:::
+
### onlyEquality
Examples of **correct** code for the `"never", { "onlyEquality": true }` options:
+::: correct
+
```js
/*eslint yoda: ["error", "never", { "onlyEquality": true }]*/
@@ -155,10 +167,14 @@ if (x !== `foo` && `bar` != x) {
}
```
+:::
+
### always
Examples of **incorrect** code for the `"always"` option:
+::: incorrect
+
```js
/*eslint yoda: ["error", "always"]*/
@@ -171,8 +187,12 @@ if (color == `blue`) {
}
```
+:::
+
Examples of **correct** code for the `"always"` option:
+::: correct
+
```js
/*eslint yoda: ["error", "always"]*/
@@ -192,3 +212,5 @@ if (-1 < str.indexOf(substr)) {
// ...
}
```
+
+:::
diff --git a/docs/src/src.json b/docs/src/src.json
new file mode 100644
index 00000000000..be7b6160852
--- /dev/null
+++ b/docs/src/src.json
@@ -0,0 +1,3 @@
+{
+ "permalink": "{{ page.filePathStem }}.html"
+}
diff --git a/docs/src/static/icon.svg b/docs/src/static/icon.svg
index 611d8ed515b..c1024b19c1b 100644
--- a/docs/src/static/icon.svg
+++ b/docs/src/static/icon.svg
@@ -1,23 +1 @@
-
-
-
+
\ No newline at end of file
diff --git a/docs/src/static/robots.njk b/docs/src/static/robots.njk
index 0810671e2ae..a6bf2474790 100644
--- a/docs/src/static/robots.njk
+++ b/docs/src/static/robots.njk
@@ -3,6 +3,5 @@ layout: false
permalink: robots.txt
eleventyExcludeFromCollections: true
---
-Sitemap: {{ metadata.url }}/sitemap.xml
User-agent: *
Disallow: /
diff --git a/docs/src/static/sitemap.njk b/docs/src/static/sitemap.njk
index d3cd92e1096..e92a4e56844 100644
--- a/docs/src/static/sitemap.njk
+++ b/docs/src/static/sitemap.njk
@@ -6,9 +6,9 @@ eleventyExcludeFromCollections: true
{% for page in collections.all %}
- {{ site.url }}{{ page.url | url }}
+ {{ ["https://", site.hostname, page.url | url | prettyURL] | join }}
{{ page.date.toISOString() }}
- {{ page.data.changeFreq or "monthly" }}
+ {{ page.data.changeFreq if page.data.changeFreq else "weekly" }}
{% endfor %}
diff --git a/docs/src/user-guide/command-line-interface.md b/docs/src/user-guide/command-line-interface.md
index ca5cc4869a5..c4f65aade44 100644
--- a/docs/src/user-guide/command-line-interface.md
+++ b/docs/src/user-guide/command-line-interface.md
@@ -10,7 +10,7 @@ eleventyNavigation:
---
-ESLint requires Node.js for installation. Follow the instructions in the [Getting Started Guide](https://eslint.org/docs/user-guide/getting-started) to install ESLint.
+ESLint requires Node.js for installation. Follow the instructions in the [Getting Started Guide](getting-started) to install ESLint.
Most users use [`npx`](https://docs.npmjs.com/cli/v8/commands/npx) to run ESLint on the command line like this:
@@ -106,9 +106,11 @@ Options that accept array values can be specified by repeating the option or wit
Example:
- npx eslint --ext .jsx --ext .js lib/
+```shell
+npx eslint --ext .jsx --ext .js lib/
- npx eslint --ext .jsx,.js lib/
+npx eslint --ext .jsx,.js lib/
+```
### Basic configuration
@@ -118,15 +120,19 @@ Disables use of configuration from `.eslintrc.*` and `package.json` files.
Example:
- npx eslint --no-eslintrc file.js
+```shell
+npx eslint --no-eslintrc file.js
+```
#### `-c`, `--config`
-This option allows you to specify an additional configuration file for ESLint (see [Configuring ESLint](configuring) for more).
+This option allows you to specify an additional configuration file for ESLint (see [Configuring ESLint](configuring/) for more).
Example:
- npx eslint -c ~/my-eslint.json file.js
+```shell
+npx eslint -c ~/my-eslint.json file.js
+```
This example uses the configuration file at `~/my-eslint.json`.
@@ -138,8 +144,10 @@ This option enables specific environments. Details about the global variables de
Examples:
- npx eslint --env browser,node file.js
- npx eslint --env browser --env node file.js
+```shell
+npx eslint --env browser,node file.js
+npx eslint --env browser --env node file.js
+```
#### `--ext`
@@ -148,14 +156,16 @@ By default, ESLint lints `*.js` files and the files that match the `overrides` e
Examples:
- # Use only .ts extension
- npx eslint . --ext .ts
+```shell
+# Use only .ts extension
+npx eslint . --ext .ts
- # Use both .js and .ts
- npx eslint . --ext .js --ext .ts
+# Use both .js and .ts
+npx eslint . --ext .js --ext .ts
- # Also use both .js and .ts
- npx eslint . --ext .js,.ts
+# Also use both .js and .ts
+npx eslint . --ext .js,.ts
+```
**Note:** `--ext` is only used when the arguments are directories. If you use glob patterns or file names, then `--ext` is ignored.
@@ -167,8 +177,10 @@ This option defines global variables so that they will not be flagged as undefin
Examples:
- npx eslint --global require,exports:true file.js
- npx eslint --global require --global exports:true
+```shell
+npx eslint --global require,exports:true file.js
+npx eslint --global require --global exports:true
+```
#### `--parser`
@@ -180,8 +192,10 @@ This option allows you to specify parser options to be used by ESLint. Note that
Examples:
- echo '3 ** 4' | npx eslint --stdin --parser-options=ecmaVersion:6 # will fail with a parsing error
- echo '3 ** 4' | npx eslint --stdin --parser-options=ecmaVersion:7 # succeeds, yay!
+```shell
+echo '3 ** 4' | npx eslint --stdin --parser-options=ecmaVersion:6 # will fail with a parsing error
+echo '3 ** 4' | npx eslint --stdin --parser-options=ecmaVersion:7 # succeeds, yay!
+```
#### `--resolve-plugins-relative-to`
@@ -200,8 +214,10 @@ Before using the plugin, you have to install it using npm.
Examples:
- npx eslint --plugin jquery file.js
- npx eslint --plugin eslint-plugin-mocha file.js
+```shell
+npx eslint --plugin jquery file.js
+npx eslint --plugin eslint-plugin-mocha file.js
+```
#### `--rule`
@@ -211,9 +227,11 @@ If the rule is defined within a plugin, you have to prefix the rule ID with the
Examples:
- npx eslint --rule 'quotes: [error, double]'
- npx eslint --rule 'guard-for-in: error' --rule 'brace-style: [error, 1tbs]'
- npx eslint --rule 'jquery/dollar-sign: error'
+```shell
+npx eslint --rule 'quotes: [error, double]'
+npx eslint --rule 'guard-for-in: error' --rule 'brace-style: [error, 1tbs]'
+npx eslint --rule 'jquery/dollar-sign: error'
+```
#### `--rulesdir`
@@ -223,11 +241,15 @@ This option allows you to specify another directory from which to load rules fil
Example:
- npx eslint --rulesdir my-rules/ file.js
+```shell
+npx eslint --rulesdir my-rules/ file.js
+```
The rules in your custom rules directory must follow the same format as bundled rules to work properly. You can also specify multiple locations for custom rules by including multiple `--rulesdir` options:
- npx eslint --rulesdir my-rules/ --rulesdir my-other-rules/ file.js
+```shell
+npx eslint --rulesdir my-rules/ --rulesdir my-other-rules/ file.js
+```
Note that, as with core rules and plugin rules, you still need to enable the rules in configuration or via the `--rule` CLI option in order to actually run those rules during linting. Specifying a rules directory with `--rulesdir` does not automatically enable the rules within that directory.
@@ -281,8 +303,10 @@ This option allows you to specify the file to use as your `.eslintignore`. By de
Example:
- npx eslint --ignore-path tmp/.eslintignore file.js
- npx eslint --ignore-path .gitignore file.js
+```shell
+npx eslint --ignore-path tmp/.eslintignore file.js
+npx eslint --ignore-path .gitignore file.js
+```
#### `--no-ignore`
@@ -290,7 +314,9 @@ Disables excluding of files from `.eslintignore`, `--ignore-path`, `--ignore-pat
Example:
- npx eslint --no-ignore file.js
+```shell
+npx eslint --no-ignore file.js
+```
#### `--ignore-pattern`
@@ -298,7 +324,9 @@ This option allows you to specify patterns of files to ignore (in addition to th
Example:
- npx eslint --ignore-pattern '/lib/' --ignore-pattern '/src/vendor/*' .
+```shell
+npx eslint --ignore-pattern '/lib/' --ignore-pattern '/src/vendor/*' .
+```
### Using stdin
@@ -308,7 +336,9 @@ This option tells ESLint to read and lint source code from STDIN instead of from
Example:
- cat myfile.js | npx eslint --stdin
+```shell
+cat myfile.js | npx eslint --stdin
+```
#### `--stdin-filename`
@@ -316,7 +346,9 @@ This option allows you to specify a filename to process STDIN as. This is useful
Example
- cat myfile.js | npx eslint --stdin --stdin-filename=myfile.js
+```shell
+cat myfile.js | npx eslint --stdin --stdin-filename=myfile.js
+```
### Handling warnings
@@ -326,7 +358,9 @@ This option allows you to disable reporting on warnings. If you enable this opti
Example:
- npx eslint --quiet file.js
+```shell
+npx eslint --quiet file.js
+```
#### `--max-warnings`
@@ -336,7 +370,9 @@ Normally, if ESLint runs and finds no errors (only warnings), it will exit with
Example:
- npx eslint --max-warnings 10 file.js
+```shell
+npx eslint --max-warnings 10 file.js
+```
### Output
@@ -346,7 +382,9 @@ Enable report to be written to a file.
Example:
- npx eslint -o ./test/test.html
+```shell
+npx eslint -o ./test/test.html
+```
When specified, the given format is output into the provided file name.
@@ -367,28 +405,36 @@ This option specifies the output format for the console. Possible formats are:
Example:
- npx eslint -f compact file.js
+```shell
+npx eslint -f compact file.js
+```
You can also use a custom formatter from the command line by specifying a path to the custom formatter file.
Example:
- npx eslint -f ./customformat.js file.js
+```shell
+npx eslint -f ./customformat.js file.js
+```
An npm-installed formatter is resolved with or without `eslint-formatter-` prefix.
Example:
- npm install eslint-formatter-pretty
+```shell
+npm install eslint-formatter-pretty
- npx eslint -f pretty file.js
+npx eslint -f pretty file.js
- // equivalent:
- npx eslint -f eslint-formatter-pretty file.js
+// equivalent:
+npx eslint -f eslint-formatter-pretty file.js
+```
When specified, the given format is output to the console. If you'd like to save that output into a file, you can do so on the command line like so:
- npx eslint -f compact file.js > results.txt
+```shell
+npx eslint -f compact file.js > results.txt
+```
This saves the output into the `results.txt` file.
@@ -398,8 +444,10 @@ This option forces the enabling/disabling of colorized output. You can use this
Examples:
- npx eslint --color file.js | cat
- npx eslint --no-color file.js
+```shell
+npx eslint --color file.js | cat
+npx eslint --no-color file.js
+```
### Inline configuration comments
@@ -419,7 +467,9 @@ config without files modifying it. All inline config comments are ignored, e.g.:
Example:
- npx eslint --no-inline-config file.js
+```shell
+npx eslint --no-inline-config file.js
+```
#### `--report-unused-disable-directives`
@@ -429,7 +479,9 @@ This option causes ESLint to report directive comments like `// eslint-disable-l
Example:
- npx eslint --report-unused-disable-directives file.js
+```shell
+npx eslint --report-unused-disable-directives file.js
+```
### Caching
@@ -455,7 +507,9 @@ If a directory is specified, a cache file will be created inside the specified f
Example:
- npx eslint "src/**/*.js" --cache --cache-location "/Users/user/.eslintcache/"
+```shell
+npx eslint "src/**/*.js" --cache --cache-location "/Users/user/.eslintcache/"
+```
#### `--cache-strategy`
@@ -465,7 +519,9 @@ The `content` strategy can be useful in cases where the modification time of you
Example:
- npx eslint "src/**/*.js" --cache --cache-strategy content
+```shell
+npx eslint "src/**/*.js" --cache --cache-strategy content
+```
### Miscellaneous
@@ -506,14 +562,18 @@ This option outputs the configuration to be used for the file passed. When prese
Example:
- npx eslint --print-config file.js
+```shell
+npx eslint --print-config file.js
+```
## Ignoring files from linting
ESLint supports `.eslintignore` files to exclude files from the linting process when ESLint operates on a directory. Files given as individual CLI arguments will be exempt from exclusion. The `.eslintignore` file is a plain text file containing one pattern per line. It can be located in any of the target directory's ancestors; it will affect files in its containing directory as well as all sub-directories. Here's a simple example of a `.eslintignore` file:
- temp.js
- **/vendor/*.js
+```text
+temp.js
+**/vendor/*.js
+```
A more detailed breakdown of supported patterns and directories ESLint ignores by default can be found in [Ignoring Code](configuring/ignoring-code).
diff --git a/docs/src/user-guide/configuring/configuration-files-new.md b/docs/src/user-guide/configuring/configuration-files-new.md
new file mode 100644
index 00000000000..98d8a5f3f8b
--- /dev/null
+++ b/docs/src/user-guide/configuring/configuration-files-new.md
@@ -0,0 +1,566 @@
+---
+title: Configuration Files (New)
+layout: doc
+edit_link: https://github.com/eslint/eslint/edit/main/docs/src/user-guide/configuring/configuration-files-new.md
+eleventyNavigation:
+ key: configuration files
+ parent: configuring
+ title: Configuration Files (New)
+ order: 1
+
+---
+
+::: warning
+This is an experimental feature that is not enabled by default. You can use the configuration system described on this page by using the `FlatESLint` class, the `FlatRuleTester` class, or by setting `configType: "flat"` in the `Linter` class.
+:::
+
+## Configuration File
+
+The ESLint configuration file is named `eslint.config.js` and should be placed in the root directory of your project and export an array of configuration objects. Here's an example:
+
+```js
+export default [
+ {
+ rules: {
+ semi: "error",
+ "prefer-const": "error"
+ }
+ }
+]
+```
+
+Here, the configuration array contains just one configuration object. The configuration object enables two rules: `semi` and `prefer-const`. These rules will be applied to all of the files ESLint processes using this config file.
+
+## Configuration Objects
+
+Each configuration object contains all of the information ESLint needs to execute on a set of files. Each configuration object is made up of these properties:
+
+* `files` - An array of glob patterns indicating the files that the configuration object should apply to. If not specified, the configuration object applies to all files.
+* `ignores` - An array of glob patterns indicating the files that the configuration object should not apply to. If not specified, the configuration object applies to all files matched by `files`.
+* `languageOptions` - An object containing settings related to how JavaScript is configured for linting.
+ * `ecmaVersion` - The version of ECMAScript to support. May be any year (i.e., `2022`) or version (i.e., `5`). Set to `"latest"` for the most recent supported version. (default: `"latest"`)
+ * `sourceType` - The type of JavaScript source code. Possible values are `"script"` for traditional script files, `"module"` for ECMAScript modules (ESM), and `"commonjs"` for CommonJS files. (default: `"module"` for `.js` and `.mjs` files; `"commonjs"` for `.cjs` files)
+ * `globals` - An object specifying additional objects that should be added to the global scope during linting.
+ * `parser` - Either an object containing a `parse()` method or a string indicating the name of a parser inside of a plugin (i.e., `"pluginName/parserName"`). (default: `"@/espree"`)
+ * `parserOptions` - An object specifying additional options that are passed directly to the `parser()` method on the parser. The available options are parser-dependent.
+* `linterOptions` - An object containing settings related to the linting process.
+ * `noInlineConfig` - A Boolean value indicating if inline configuration is allowed.
+ * `reportUnusedDisableDirectives` - A Boolean value indicating if unused disable directives should be tracked and reported.
+* `processor` - Either an object containing `preprocess()` and `postprocess()` methods or a string indicating the name of a processor inside of a plugin (i.e., `"pluginName/processorName"`).
+* `plugins` - An object containing a name-value mapping of plugin names to plugin objects. When `files` is specified, these plugins are only available to the matching files.
+* `rules` - An object containing the configured rules. When `files` or `ignores` are specified, these rule configurations are only available to the matching files.
+* `settings` - An object containing name-value pairs of information that should be available to all rules.
+
+### Specifying `files` and `ignores`
+
+::: tip
+Patterns specified in `files` and `ignores` use [`minimatch`](https://www.npmjs.com/package/minimatch) syntax and are evaluated relative to the location of the `eslint.config.js` file.
+:::
+
+You can use a combination of `files` and `ignores` to determine which files should apply the configuration object and which should not. By default, ESLint matches `**/*.js`, `**/*.cjs`, and `**/*.mjs`. Because config objects that don't specify `files` or `ignores` apply to all files that have been matched by any other configuration object, by default config objects will apply to any JavaScript files passed to ESLint. For example:
+
+```js
+export default [
+ {
+ rules: {
+ semi: "error"
+ }
+ }
+];
+```
+
+With this configuration, the `semi` rule is enabled for all files that match the default files in ESLint. So if you pass `example.js` to ESLint, the `semi` rule will be applied. If you pass a non-JavaScript file, like `example.txt`, the `semi` rule will not be applied because there are no other configuration objects that match that filename. (ESLint will output an error message letting you know that the file was ignored due to missing configuration.)
+
+#### Excluding files with `ignores`
+
+You can limit which files a configuration object applies to by specifying a combination of `files` and `ignores` patterns. For example, you may want certain rules to apply only to files in your `src` directory, like this:
+
+```js
+export default [
+ {
+ files: ["src/**/*.js"],
+ rules: {
+ semi: "error"
+ }
+ }
+];
+```
+
+Here, only the JavaScript files in the `src` directory will have the `semi` rule applied. If you run ESLint on files in another directory, this configuration object will be skipped. By adding `ignores`, you can also remove some of the files in `src` from this configuration object:
+
+```js
+export default [
+ {
+ files: ["src/**/*.js"],
+ ignores: ["**/*.config.js"],
+ rules: {
+ semi: "error"
+ }
+ }
+];
+```
+
+This configuration object matches all JavaScript files in the `src` directory except those that end with `.config.js`. You can also use negation patterns in `ignores` to exclude files from the ignore patterns, such as:
+
+```js
+export default [
+ {
+ files: ["src/**/*.js"],
+ ignores: ["**/*.config.js", "!**/eslint.config.js"],
+ rules: {
+ semi: "error"
+ }
+ }
+];
+```
+
+Here, the configuration object excludes files ending with `.config.js` except for `eslint.config.js`. That file will still have `semi` applied.
+
+If `ignores` is used without `files` and any other setting, then the configuration object applies to all files except the ones specified in `ignores`, for example:
+
+```js
+export default [
+ {
+ ignores: ["**/*.config.js"],
+ rules: {
+ semi: "error"
+ }
+ }
+];
+```
+
+This configuration object applies to all files except those ending with `.config.js`. Effectively, this is like having `files` set to `**/*`. In general, it's a good idea to always include `files` if you are specifying `ignores`.
+
+#### Globally ignoring files with `ignores`
+
+If `ignores` is used without any other keys in the configuration object, then the patterns act as additional global ignores, similar to those found in `.eslintignore`. Here's an example:
+
+```js
+export default [
+ {
+ ignores: [".config/*"]
+ }
+];
+```
+
+This configuration specifies that all of the files in the `.config` directory should be ignored. This pattern is added after the patterns found in `.eslintignore`.
+
+#### Cascading configuration objects
+
+When more than one configuration object matches a given filename, the configuration objects are merged with later objects overriding previous objects when there is a conflict. For example:
+
+```js
+export default [
+ {
+ files: ["**/*.js"],
+ languageOptions: {
+ globals: {
+ MY_CUSTOM_GLOBAL: "readonly"
+ }
+ }
+ },
+ {
+ files: ["tests/**/*.js"],
+ languageOptions: {
+ globals: {
+ it: "readonly",
+ describe: "readonly"
+ }
+ }
+ }
+];
+```
+
+Using this configuration, all JavaScript files define a custom global object defined called `MY_CUSTOM_GLOBAL` while those JavaScript files in the `tests` directory have `it` and `describe` defined as global objects in addition to `MY_CUSTOM_GLOBAL`. For any JavaScript file in the tests directory, both configuration objects are applied, so `languageOptions.globals` are merged to create a final result.
+
+### Configuring linter options
+
+Options specific to the linting process can be configured using the `linterOptions` object. These effect how linting proceeds and does not affect how the source code of the file is interpreted.
+
+#### Disabling inline configuration
+
+Inline configuration is implemented using an `/*eslint*/` comment, such as `/*eslint semi: error*/`. You can disallow inline configuration by setting `noInlineConfig` to `true`. When enabled, all inline configuration is ignored. Here's an example:
+
+```js
+export default [
+ {
+ files: ["**/*.js"],
+ linterOptions: {
+ noInlineConfig: true
+ }
+ }
+];
+```
+
+#### Reporting unused disable directives
+
+Disable directives such as `/*eslint-disable*/` and `/*eslint-disable-next-line*/` are used to disable ESLint rules around certain portions of code. As code changes, it's possible for these directives to no longer be needed because the code has changed in such a way that the rule will no longer be triggered. You can enable reporting of these unused disable directives by setting the `reportUnusedDisableDirectives` option to `true`, as in this example:
+
+```js
+export default [
+ {
+ files: ["**/*.js"],
+ linterOptions: {
+ reportUnusedDisableDirectives: true
+ }
+ }
+];
+```
+
+By default, unused disable directives are reported as warnings. You can change this setting using the `--report-unused-disable-directives` command line option.
+
+### Configuring language options
+
+Options specific to how ESLint evaluates your JavaScript code can be configured using the `languageOptions` object.
+
+#### Configuring the JavaScript version
+
+To configure the version of JavaScript (ECMAScript) that ESLint uses to evaluate your JavaScript, use the `ecmaVersion` property. This property determines which global variables and syntax are valid in your code and can be set to the version number (such as `6`), the year number (such as `2022`), or `"latest"` (for the most recent version that ESLint supports). By default, `ecmaVersion` is set to `"latest"` and it's recommended to keep this default unless you need to ensure that your JavaScript code is evaluated as an older version. For example, some older runtimes might only allow ECMAScript 5, in which case you can configure ESLint like this:
+
+```js
+export default [
+ {
+ files: ["**/*.js"],
+ languageOptions: {
+ ecmaVersion: 5
+ }
+ }
+];
+```
+
+#### Configuring the JavaScript source type
+
+ESLint can evaluate your code in one of three ways:
+
+1. ECMAScript module (ESM) - Your code has a module scope and is run in strict mode.
+1. CommonJS - Your code has a top-level function scope and runs in nonstrict mode.
+1. Script - Your code has a shared global scope and runs in nonstrict mode.
+
+You can specify which of these modes your code is intended to run in by specifying the `sourceType` property. This property can be set to `"module"`, `"commonjs"`, or `"script"`. By default, `sourceType` is set to `"module"` for `.js` and `.mjs` files and is set to `"commonjs"` for `.cjs` files. Here's an example:
+
+```js
+export default [
+ {
+ files: ["**/*.js"],
+ languageOptions: {
+ sourceType: "script"
+ }
+ }
+];
+```
+
+#### Configuring a custom parser and its options
+
+In many cases, you can use the default parser that ESLint ships with for parsing your JavaScript code. You can optionally override the default parser by using the `parser` property. The `parser` property can be either a string in the format `"pluginName/parserName"` (indicating to retrieve the parser from a plugin) or an object containing either a `parse()` method or a `parseForESLint()` method. For example, you can use the [`@babel/eslint-parser`](https://www.npmjs.com/package/@babel/eslint-parser) package to allow ESLint to parse experimental syntax:
+
+```js
+import babelParser from "@babel/eslint-parser";
+
+export default [
+ {
+ files: ["**/*.js", "**/*.mjs"],
+ languageOptions: {
+ parser: babelParser
+ }
+ }
+];
+```
+
+This configuration ensures that the Babel parser, rather than the default, will be used to parse all files ending with `.js` and `.mjs`.
+
+You can also pass options directly to the custom parser by using the `parserOptions` property. This property is an object whose name-value pairs are specific to the parser that you are using. For the Babel parser, you might pass in options like this:
+
+```js
+import babelParser from "@babel/eslint-parser";
+
+export default [
+ {
+ files: ["**/*.js", "**/*.mjs"],
+ languageOptions: {
+ parser: babelParser,
+ parserOptions: {
+ requireConfigFile: false,
+ babelOptions: {
+ babelrc: false,
+ configFile: false,
+ // your babel options
+ presets: ["@babel/preset-env"],
+ }
+ }
+ }
+ }
+];
+```
+
+#### Configuring global variables
+
+To configure global variables inside of a configuration object, set the `globals` configuration property to an object containing keys named for each of the global variables you want to use. For each global variable key, set the corresponding value equal to `"writable"` to allow the variable to be overwritten or `"readonly"` to disallow overwriting. For example:
+
+```js
+export default [
+ {
+ files: ["**/*.js"],
+ languageOptions: {
+ globals: {
+ var1: "writable",
+ var2: "readonly"
+ }
+ }
+ }
+];
+```
+
+These examples allow `var1` to be overwritten in your code, but disallow it for `var2`.
+
+Globals can be disabled with the string `"off"`. For example, in an environment where most ES2015 globals are available but `Promise` is unavailable, you might use this config:
+
+```js
+export default [
+ {
+ languageOptions: {
+ globals: {
+ Promise: "off"
+ }
+ }
+ }
+];
+```
+
+For historical reasons, the boolean value `false` and the string value `"readable"` are equivalent to `"readonly"`. Similarly, the boolean value `true` and the string value `"writeable"` are equivalent to `"writable"`. However, the use of older values is deprecated.
+
+### Using plugins in your configuration
+
+Plugins are used to share rules, processors, configurations, parsers, and more across ESLint projects. Plugins are specified in a configuration object using the `plugins` key, which is an object where the name of the plugin is the property name and the value is the plugin object itself. Here's an example:
+
+```js
+import jsdoc from "eslint-plugin-jsdoc";
+
+export default [
+ {
+ files: ["**/*.js"],
+ plugins: {
+ jsdoc: jsdoc
+ }
+ rules: {
+ "jsdoc/require-description": "error",
+ "jsdoc/check-values": "error"
+ }
+ }
+];
+```
+
+In this configuration, the JSDoc plugin is defined to have the name `jsdoc`. The prefix `jsdoc/` in each rule name indicates that the rule is coming from the plugin with that name rather than from ESLint itself.
+
+Because the name of the plugin and the plugin object are both `jsdoc`, you can also shorten the configuration to this:
+
+```js
+import jsdoc from "eslint-plugin-jsdoc";
+
+export default [
+ {
+ files: ["**/*.js"],
+ plugins: {
+ jsdoc
+ }
+ rules: {
+ "jsdoc/require-description": "error",
+ "jsdoc/check-values": "error"
+ }
+ }
+];
+```
+
+While this is the most common convention, you don't need to use the same name that the plugin prescribes. You can specify any prefix that you'd like, such as:
+
+```js
+import jsdoc from "eslint-plugin-jsdoc";
+
+export default [
+ {
+ files: ["**/*.js"],
+ plugins: {
+ jsd: jsdoc
+ }
+ rules: {
+ "jsd/require-description": "error",
+ "jsd/check-values": "error"
+ }
+ }
+];
+```
+
+This configuration object uses `jsd` as the prefix plugin instead of `jsdoc`.
+
+### Using processors
+
+Processors allow ESLint to transform text into pieces of code that ESLint can lint. You can specify the processor to use for a given file type by defining a `processor` property that contains either the processor name in the format `"pluginName/processorName"` to reference a processor in a plugin or an object containing both a `preprocess()` and a `postprocess()` method. For example, to extract JavaScript code blocks from a Markdown file, you might add this to your configuration:
+
+```js
+import markdown from "eslint-plugin-markdown";
+
+export default [
+ {
+ files: ["**/*.md"],
+ plugins: {
+ markdown
+ },
+ processor: "markdown/markdown"
+ settings: {
+ sharedData: "Hello"
+ }
+ }
+];
+```
+
+This configuration object specifies that there is a processor called `"markdown"` contained in the plugin named `"markdown"` and will apply the processor to all files ending with `.md`.
+
+Processors may make named code blocks that function as filenames in configuration objects, such as `0.js` and `1.js`. ESLint handles such a named code block as a child of the original file. You can specify additional configuration objects for named code blocks. For example, the following disables the `strict` rule for the named code blocks which end with `.js` in markdown files.
+
+```js
+import markdown from "eslint-plugin-markdown";
+
+export default [
+ {
+ files: ["**/*.md"],
+ plugins: {
+ markdown
+ },
+ processor: "markdown/markdown"
+ settings: {
+ sharedData: "Hello"
+ }
+ },
+
+ // applies only to code blocks
+ {
+ files: ["**/*.md/*.js"],
+ rules: {
+ strict: "off"
+ }
+ }
+];
+```
+
+### Configuring rules
+
+You can configure any number of rules in a configuration object by add a `rules` property containing an object with your rule configurations. The names in this object are the names of the rules and the values are the configurations for each of those rules. Here's an example:
+
+```js
+export default [
+ {
+ rules: {
+ semi: "error"
+ }
+ }
+];
+```
+
+This configuration object specifies that the [`semi`](/docs/latest/rules/semi) rule should be enabled with a severity of `"error"`. You can also provide options to a rule by specifying an array where the first item is the severity and each item after that is an option for the rule. For example, you can switch the `semi` rule to disallow semicolons by passing `"never"` as an option:
+
+```js
+export default [
+ {
+ rules: {
+ semi: ["error", "never"]
+ }
+ }
+];
+```
+
+Each rule specifies its own options and can be any valid JSON data type. Please check the documentation for the rule you want to configure for more information about its available options.
+
+#### Rule severities
+
+There are three possible severities you can specify for a rule
+
+* `"error"` (or `2`) - the reported problem should be treated as an error. When using the ESLint CLI, errors cause the CLI to exit with a nonzero code.
+* `"warn"` (or `1`) - the reported problem should be treated as a warning. When using the ESLint CLI, warnings are reported but do not change the exit code. If only errors are reported, the exit code will be 0.
+* `"off"` (or `0`) - the rule should be turned off completely.
+
+#### Rule configuration cascade
+
+When more than one configuration object specifies the same rule, the rule configuration is merged with the later object taking precedence over any previous objects. For example:
+
+```js
+export default [
+ {
+ rules: {
+ semi: ["error", "never"]
+ }
+ },
+ {
+ rules: {
+ semi: ["warn", "always"]
+ }
+ }
+];
+```
+
+Using this configuration, the final rule configuration for `semi` is `["warn", "always"]` because it appears last in the array. The array indicates that the configuration is for the severity and any options. You can change just the severity by defining only a string or number, as in this example:
+
+```js
+export default [
+ {
+ rules: {
+ semi: ["error", "never"]
+ }
+ },
+ {
+ rules: {
+ semi: "warn"
+ }
+ }
+];
+```
+
+Here, the second configuration object only overrides the severity, so the final configuration for `semi` is `["warn", "never"]`.
+
+### Configuring shared settings
+
+ESLint supports adding shared settings into configuration files. Plugins use `settings` to specify information that should be shared across all of its rules. You can add a `settings` object to a configuration object and it will be supplied to every rule being executed. This may be useful if you are adding custom rules and want them to have access to the same information. Here's an example:
+
+```js
+export default [
+ {
+ settings: {
+ sharedData: "Hello"
+ }
+ }
+];
+```
+
+### Using predefined configurations
+
+ESLint has two predefined configurations:
+
+* `eslint:recommended` - enables the rules that ESLint recommends everyone use to avoid potential errors
+* `eslint:all` - enables all of the rules shipped with ESLint
+
+To include these predefined configurations, you can insert the string values into the returned array and then make any modifications to other properties in subsequent configuration objects:
+
+```js
+export default [
+ "eslint:recommended",
+ {
+ rules: {
+ semi: ["warn", "always"]
+ }
+ }
+];
+```
+
+Here, the `eslint:recommended` predefined configuration is applied first and then another configuration object adds the desired configuration for `semi`.
+
+## Configuration File Resolution
+
+When ESLint is run on the command line, it first checks the current working directory for `eslint.config.js`, and if not found, will look to the next parent directory for the file. This search continues until either the file is found or the root directory is reached.
+
+You can prevent this search for `eslint.config.js` by using the `-c` or `--config--file` option on the command line to specify an alternate configuration file, such as:
+
+```shell
+npx eslint -c some-other-file.js **/*.js
+```
+
+In this case, ESLint will not search for `eslint.config.js` and will instead use `some-other-file.js`.
+
+Each configuration file exports one or more configuration object. A configuration object
diff --git a/docs/src/user-guide/configuring/configuration-files.md b/docs/src/user-guide/configuring/configuration-files.md
index 24a92bb1483..085b4420fb7 100644
--- a/docs/src/user-guide/configuring/configuration-files.md
+++ b/docs/src/user-guide/configuring/configuration-files.md
@@ -10,14 +10,6 @@ eleventyNavigation:
---
-* [Configuration File Formats](#configuration-file-formats)
-* [Using Configuration Files](#using-configuration-files)
-* [Adding Shared Settings](#adding-shared-settings)
-* [Cascading and Hierarchy](#cascading-and-hierarchy)
-* [Extending Configuration Files](#extending-configuration-files)
-* [Configuration Based on Glob Patterns](#configuration-based-on-glob-patterns)
-* [Personal Configuration Files](#personal-configuration-files-deprecated)
-
## Configuration File Formats
ESLint supports configuration files in several formats:
@@ -45,7 +37,9 @@ The first way to use configuration files is via `.eslintrc.*` and `package.json`
The second way to use configuration files is to save the file wherever you would like and pass its location to the CLI using the `--config` option, such as:
- eslint -c myconfig.json myfiletotest.js
+```shell
+eslint -c myconfig.json myfiletotest.js
+```
If you are using one configuration file and want ESLint to ignore any `.eslintrc.*` files, make sure to use [`--no-eslintrc`](https://eslint.org/docs/user-guide/command-line-interface#--no-eslintrc) along with the [`-c`](https://eslint.org/docs/user-guide/command-line-interface#-c---config) flag.
diff --git a/docs/src/user-guide/configuring/ignoring-code.md b/docs/src/user-guide/configuring/ignoring-code.md
index 7e02d38d265..119d1873b78 100644
--- a/docs/src/user-guide/configuring/ignoring-code.md
+++ b/docs/src/user-guide/configuring/ignoring-code.md
@@ -10,12 +10,6 @@ eleventyNavigation:
---
-* [`ignorePatterns` in Config Files](#ignorepatterns-in-config-files)
-* [The `.eslintignore` File](#the-eslintignore-file)
-* [Using an Alternate File](#using-an-alternate-file)
-* [Using eslintIgnore in package.json](#using-eslintignore-in-packagejson)
-* [Ignored File Warnings](#ignored-file-warnings)
-
## `ignorePatterns` in Config Files
You can tell ESLint to ignore specific files and directories using `ignorePatterns` in your config files. `ignorePatterns` patterns follow the same rules as `.eslintignore`. Please see the [the `.eslintignore` file documentation](./ignoring-code#the-eslintignore-file) to learn more.
@@ -50,7 +44,7 @@ When ESLint is run, it looks in the current working directory to find an `.eslin
Globs are matched using [node-ignore](https://github.com/kaelzhang/node-ignore), so a number of features are available:
* Lines beginning with `#` are treated as comments and do not affect the ignore patterns.
-* Paths are relative to the current working directory. This is also true of paths passed in via the `--ignore-pattern` [command](https://eslint.org/docs/user-guide/command-line-interface#--ignore-pattern).
+* Paths are relative to the current working directory. This is also true of paths passed in via the `--ignore-pattern` [command](../command-line-interface#--ignore-pattern).
* Lines preceded by `!` are negated patterns that re-include a pattern that was ignored by an earlier pattern.
* Ignore patterns behave according to the `.gitignore` [specification](https://git-scm.com/docs/gitignore).
@@ -95,17 +89,23 @@ There are also some exceptions to these rules:
The following `--ignore-pattern` is also equivalent:
- eslint --ignore-pattern '!.build' --ignore-pattern '.build/*' --ignore-pattern '!.build/test.js' parent-folder/
+ ```shell
+ eslint --ignore-pattern '!.build' --ignore-pattern '.build/*' --ignore-pattern '!.build/test.js' parent-folder/
+ ```
## Using an Alternate File
If you'd prefer to use a different file than the `.eslintignore` in the current working directory, you can specify it on the command line using the `--ignore-path` option. For example, you can use `.jshintignore` file because it has the same format:
- eslint --ignore-path .jshintignore file.js
+```shell
+eslint --ignore-path .jshintignore file.js
+```
You can also use your `.gitignore` file:
- eslint --ignore-path .gitignore file.js
+```shell
+eslint --ignore-path .gitignore file.js
+```
Any file that follows the standard ignore file format can be used. Keep in mind that specifying `--ignore-path` means that any existing `.eslintignore` file will not be used. Note that globbing rules in `.eslintignore` follow those of `.gitignore`.
@@ -113,17 +113,19 @@ Any file that follows the standard ignore file format can be used. Keep in mind
If an `.eslintignore` file is not found and an alternate file is not specified, ESLint will look in package.json for an `eslintIgnore` key to check for files to ignore.
- {
- "name": "mypackage",
- "version": "0.0.1",
- "eslintConfig": {
- "env": {
- "browser": true,
- "node": true
- }
- },
- "eslintIgnore": ["hello.js", "world.js"]
- }
+```json
+{
+ "name": "mypackage",
+ "version": "0.0.1",
+ "eslintConfig": {
+ "env": {
+ "browser": true,
+ "node": true
+ }
+ },
+ "eslintIgnore": ["hello.js", "world.js"]
+}
+```
## Ignored File Warnings
@@ -135,7 +137,9 @@ foo.js
And then you run:
- eslint foo.js
+```shell
+eslint foo.js
+```
You'll see this warning:
@@ -150,7 +154,9 @@ This message occurs because ESLint is unsure if you wanted to actually lint the
Consider another scenario where you may want to run ESLint on a specific dot-file or dot-folder, but have forgotten to specifically allow those files in your `.eslintignore` file. You would run something like this:
- eslint .config/foo.js
+```shell
+eslint .config/foo.js
+```
You would see this warning:
diff --git a/docs/src/user-guide/configuring/index.md b/docs/src/user-guide/configuring/index.md
index 76c9ed30a2c..f9351dd75f2 100644
--- a/docs/src/user-guide/configuring/index.md
+++ b/docs/src/user-guide/configuring/index.md
@@ -13,7 +13,7 @@ eleventyNavigation:
ESLint is designed to be flexible and configurable for your use case. You can turn off every rule and run only with basic syntax validation or mix and match the bundled rules and your custom rules to fit the needs of your project. There are two primary ways to configure ESLint:
1. **Configuration Comments** - use JavaScript comments to embed configuration information directly into a file.
-1. **Configuration Files** - use a JavaScript, JSON, or YAML file to specify configuration information for an entire directory and all of its subdirectories. This can be in the form of a [`.eslintrc.*`](./configuration-files#configuration-file-formats) file or an `eslintConfig` field in a [`package.json`](https://docs.npmjs.com/files/package.json) file, both of which ESLint will look for and read automatically, or you can specify a configuration file on the [command line](https://eslint.org/docs/user-guide/command-line-interface).
+1. **Configuration Files** - use a JavaScript, JSON, or YAML file to specify configuration information for an entire directory and all of its subdirectories. This can be in the form of a [`.eslintrc.*`](./configuration-files#configuration-file-formats) file or an `eslintConfig` field in a [`package.json`](https://docs.npmjs.com/files/package.json) file, both of which ESLint will look for and read automatically, or you can specify a configuration file on the [command line](../command-line-interface).
Here are some of the options that you can configure in ESLint:
diff --git a/docs/src/user-guide/configuring/language-options.md b/docs/src/user-guide/configuring/language-options.md
index 858114a838a..379c678f48c 100644
--- a/docs/src/user-guide/configuring/language-options.md
+++ b/docs/src/user-guide/configuring/language-options.md
@@ -10,10 +10,6 @@ eleventyNavigation:
---
-* [Specifying Environments](#specifying-environments)
-* [Specifying Globals](#specifying-globals)
-* [Specifying Parser Options](#specifying-parser-options)
-
## Specifying Environments
An environment provides predefined global variables. The available environments are:
@@ -53,7 +49,7 @@ An environment provides predefined global variables. The available environments
These environments are not mutually exclusive, so you can define more than one at a time.
-Environments can be specified inside of a file, in configuration files or using the `--env` [command line](https://eslint.org/docs/user-guide/command-line-interface) flag.
+Environments can be specified inside of a file, in configuration files or using the `--env` [command line](../command-line-interface) flag.
### Using configuration comments
diff --git a/docs/src/user-guide/configuring/plugins.md b/docs/src/user-guide/configuring/plugins.md
index a811076ee59..3314ef9a130 100644
--- a/docs/src/user-guide/configuring/plugins.md
+++ b/docs/src/user-guide/configuring/plugins.md
@@ -10,16 +10,12 @@ eleventyNavigation:
---
-* [Specifying Parser](#specifying-parser)
-* [Specifying Processor](#specifying-processor)
-* [Configuring Plugins](#configuring-plugins)
-
## Specifying Parser
By default, ESLint uses [Espree](https://github.com/eslint/espree) as its parser. You can optionally specify that a different parser should be used in your configuration file so long as the parser meets the following requirements:
1. It must be a Node module loadable from the config file where the parser is used. Usually, this means you should install the parser package separately using npm.
-1. It must conform to the [parser interface](https://eslint.org/docs/developer-guide/working-with-custom-parsers).
+1. It must conform to the [parser interface](../../developer-guide/working-with-custom-parsers).
Note that even with these compatibilities, there are no guarantees that an external parser will work correctly with ESLint and ESLint will not fix bugs related to incompatibilities with other parsers.
diff --git a/docs/src/user-guide/configuring/rules.md b/docs/src/user-guide/configuring/rules.md
index 5529356c394..ebc070f8cd7 100644
--- a/docs/src/user-guide/configuring/rules.md
+++ b/docs/src/user-guide/configuring/rules.md
@@ -10,9 +10,6 @@ eleventyNavigation:
---
-* [Configuring Rules](#configuring-rules)
-* [Disabling Rules](#disabling-rules)
-
## Configuring Rules
ESLint comes with a large number of built-in rules and you can add more rules through plugins. You can modify which rules your project uses either using configuration comments or configuration files. To change a rule setting, you must set the rule ID equal to one of these values:
@@ -29,7 +26,7 @@ To configure rules inside of a file using configuration comments, use a comment
/* eslint eqeqeq: "off", curly: "error" */
```
-In this example, [`eqeqeq`](https://eslint.org/docs/rules/eqeqeq) is turned off and [`curly`](https://eslint.org/docs/rules/curly) is turned on as an error. You can also use the numeric equivalent for the rule severity:
+In this example, [`eqeqeq`](../../rules/eqeqeq) is turned off and [`curly`](../../rules/curly) is turned on as an error. You can also use the numeric equivalent for the rule severity:
```js
/* eslint eqeqeq: 0, curly: 2 */
@@ -43,7 +40,7 @@ If a rule has additional options, you can specify them using array literal synta
/* eslint quotes: ["error", "double"], curly: 2 */
```
-This comment specifies the "double" option for the [`quotes`](https://eslint.org/docs/rules/quotes) rule. The first item in the array is always the rule severity (number or string).
+This comment specifies the "double" option for the [`quotes`](../../rules/quotes) rule. The first item in the array is always the rule severity (number or string).
Configuration comments can include descriptions to explain why the comment is necessary. The description must occur after the configuration and is separated from the configuration by two or more consecutive `-` characters. For example:
@@ -221,10 +218,10 @@ alert('foo'); /* eslint-disable-line no-alert, quotes, semi */
/* eslint-disable-next-line no-alert, quotes, semi */
alert('foo');
-/* eslint-disable-next-line
- no-alert,
- quotes,
- semi
+/* eslint-disable-next-line
+ no-alert,
+ quotes,
+ semi
*/
alert('foo');
```
@@ -280,7 +277,7 @@ To disable all inline config comments, use the `noInlineConfig` setting. For exa
}
```
-This setting is similar to [--no-inline-config](https://eslint.org/docs/user-guide/command-line-interface#--no-inline-config) CLI option.
+This setting is similar to [--no-inline-config](../command-line-interface#--no-inline-config) CLI option.
#### Report unused `eslint-disable` comments
@@ -293,4 +290,4 @@ To report unused `eslint-disable` comments, use the `reportUnusedDisableDirectiv
}
```
-This setting is similar to [--report-unused-disable-directives](https://eslint.org/docs/user-guide/command-line-interface#--report-unused-disable-directives) CLI option, but doesn't fail linting (reports as `"warn"` severity).
+This setting is similar to [--report-unused-disable-directives](../command-line-interface#--report-unused-disable-directives) CLI option, but doesn't fail linting (reports as `"warn"` severity).
diff --git a/docs/src/user-guide/formatters/html-formatter-example.html b/docs/src/user-guide/formatters/html-formatter-example.html
new file mode 100644
index 00000000000..4f513f305e0
--- /dev/null
+++ b/docs/src/user-guide/formatters/html-formatter-example.html
@@ -0,0 +1,203 @@
+
+
+
+
+ ESLint Report
+
+
+
+
+
+
+
ESLint Report
+
+ 9 problems (5 errors, 4 warnings) - Generated on Mon Aug 01 2022 00:13:38 GMT-0400 (Eastern Daylight Time)
+
+
+
+
+
+
+ [+] /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js
+ 9 problems (5 errors, 4 warnings)
+ |
+
+
+ 1:10 |
+ Error |
+ 'addOne' is defined but never used. |
+
+ no-unused-vars
+ |
+
+
+
+ 2:9 |
+ Error |
+ Use the isNaN function to compare with NaN. |
+
+ use-isnan
+ |
+
+
+
+ 3:16 |
+ Error |
+ Unexpected space before unary operator '++'. |
+
+ space-unary-ops
+ |
+
+
+
+ 3:20 |
+ Warning |
+ Missing semicolon. |
+
+ semi
+ |
+
+
+
+ 4:12 |
+ Warning |
+ Unnecessary 'else' after 'return'. |
+
+ no-else-return
+ |
+
+
+
+ 5:1 |
+ Warning |
+ Expected indentation of 8 spaces but found 6. |
+
+ indent
+ |
+
+
+
+ 5:7 |
+ Error |
+ Function 'addOne' expected a return value. |
+
+ consistent-return
+ |
+
+
+
+ 5:13 |
+ Warning |
+ Missing semicolon. |
+
+ semi
+ |
+
+
+
+ 7:2 |
+ Error |
+ Unnecessary semicolon. |
+
+ no-extra-semi
+ |
+
+
+
+
+
+
+
diff --git a/docs/src/user-guide/formatters/index.md b/docs/src/user-guide/formatters/index.md
new file mode 100644
index 00000000000..074b04a9726
--- /dev/null
+++ b/docs/src/user-guide/formatters/index.md
@@ -0,0 +1,243 @@
+---
+title: Formatters
+layout: doc
+eleventyNavigation:
+ key: formatters
+ parent: user guide
+ title: Formatters
+ order: 5
+edit_link: https://github.com/eslint/eslint/edit/main/templates/formatter-examples.md.ejs
+---
+
+ESLint comes with several built-in formatters to control the appearance of the linting results, and supports third-party formatters as well.
+
+You can specify a formatter using the `--format` or `-f` flag on the command line. For example, `--format json` uses the `json` formatter.
+
+The built-in formatter options are:
+
+* [checkstyle](#checkstyle)
+* [compact](#compact)
+* [html](#html)
+* [jslint-xml](#jslint-xml)
+* [json-with-metadata](#json-with-metadata)
+* [json](#json)
+* [junit](#junit)
+* [stylish](#stylish)
+* [tap](#tap)
+* [unix](#unix)
+* [visualstudio](#visualstudio)
+
+## Example Source
+
+Examples of each formatter were created from linting `fullOfProblems.js` using the `.eslintrc` configuration shown below.
+
+### `fullOfProblems.js`
+
+```js
+function addOne(i) {
+ if (i != NaN) {
+ return i ++
+ } else {
+ return
+ }
+};
+```
+
+### `.eslintrc`:
+
+```json
+{
+ "extends": "eslint:recommended",
+ "rules": {
+ "consistent-return": 2,
+ "indent" : [1, 4],
+ "no-else-return" : 1,
+ "semi" : [1, "always"],
+ "space-unary-ops" : 2
+ }
+}
+```
+
+## Output Examples
+
+### checkstyle
+
+```text
+<?xml version="1.0" encoding="utf-8"?><checkstyle version="4.3"><file name="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js"><error line="1" column="10" severity="error" message="'addOne' is defined but never used. (no-unused-vars)" source="eslint.rules.no-unused-vars" /><error line="2" column="9" severity="error" message="Use the isNaN function to compare with NaN. (use-isnan)" source="eslint.rules.use-isnan" /><error line="3" column="16" severity="error" message="Unexpected space before unary operator '++'. (space-unary-ops)" source="eslint.rules.space-unary-ops" /><error line="3" column="20" severity="warning" message="Missing semicolon. (semi)" source="eslint.rules.semi" /><error line="4" column="12" severity="warning" message="Unnecessary 'else' after 'return'. (no-else-return)" source="eslint.rules.no-else-return" /><error line="5" column="1" severity="warning" message="Expected indentation of 8 spaces but found 6. (indent)" source="eslint.rules.indent" /><error line="5" column="7" severity="error" message="Function 'addOne' expected a return value. (consistent-return)" source="eslint.rules.consistent-return" /><error line="5" column="13" severity="warning" message="Missing semicolon. (semi)" source="eslint.rules.semi" /><error line="7" column="2" severity="error" message="Unnecessary semicolon. (no-extra-semi)" source="eslint.rules.no-extra-semi" /></file></checkstyle>
+```
+
+### compact
+
+```text
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 1, col 10, Error - 'addOne' is defined but never used. (no-unused-vars)
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 2, col 9, Error - Use the isNaN function to compare with NaN. (use-isnan)
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 3, col 16, Error - Unexpected space before unary operator '++'. (space-unary-ops)
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 3, col 20, Warning - Missing semicolon. (semi)
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 4, col 12, Warning - Unnecessary 'else' after 'return'. (no-else-return)
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 5, col 1, Warning - Expected indentation of 8 spaces but found 6. (indent)
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 5, col 7, Error - Function 'addOne' expected a return value. (consistent-return)
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 5, col 13, Warning - Missing semicolon. (semi)
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js: line 7, col 2, Error - Unnecessary semicolon. (no-extra-semi)
+
+9 problems
+```
+
+### html
+
+
+
+### jslint-xml
+
+```text
+<?xml version="1.0" encoding="utf-8"?><jslint><file name="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js"><issue line="1" char="10" evidence="" reason="'addOne' is defined but never used. (no-unused-vars)" /><issue line="2" char="9" evidence="" reason="Use the isNaN function to compare with NaN. (use-isnan)" /><issue line="3" char="16" evidence="" reason="Unexpected space before unary operator '++'. (space-unary-ops)" /><issue line="3" char="20" evidence="" reason="Missing semicolon. (semi)" /><issue line="4" char="12" evidence="" reason="Unnecessary 'else' after 'return'. (no-else-return)" /><issue line="5" char="1" evidence="" reason="Expected indentation of 8 spaces but found 6. (indent)" /><issue line="5" char="7" evidence="" reason="Function 'addOne' expected a return value. (consistent-return)" /><issue line="5" char="13" evidence="" reason="Missing semicolon. (semi)" /><issue line="7" char="2" evidence="" reason="Unnecessary semicolon. (no-extra-semi)" /></file></jslint>
+```
+
+### json-with-metadata
+
+```text
+{"results":[{"filePath":"/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js","messages":[{"ruleId":"no-unused-vars","severity":2,"message":"'addOne' is defined but never used.","line":1,"column":10,"nodeType":"Identifier","messageId":"unusedVar","endLine":1,"endColumn":16},{"ruleId":"use-isnan","severity":2,"message":"Use the isNaN function to compare with NaN.","line":2,"column":9,"nodeType":"BinaryExpression","messageId":"comparisonWithNaN","endLine":2,"endColumn":17},{"ruleId":"space-unary-ops","severity":2,"message":"Unexpected space before unary operator '++'.","line":3,"column":16,"nodeType":"UpdateExpression","messageId":"unexpectedBefore","endLine":3,"endColumn":20,"fix":{"range":[57,58],"text":""}},{"ruleId":"semi","severity":1,"message":"Missing semicolon.","line":3,"column":20,"nodeType":"ReturnStatement","messageId":"missingSemi","endLine":4,"endColumn":1,"fix":{"range":[60,60],"text":";"}},{"ruleId":"no-else-return","severity":1,"message":"Unnecessary 'else' after 'return'.","line":4,"column":12,"nodeType":"BlockStatement","messageId":"unexpected","endLine":6,"endColumn":6,"fix":{"range":[0,94],"text":"function addOne(i) {\n if (i != NaN) {\n return i ++\n } \n return\n \n}"}},{"ruleId":"indent","severity":1,"message":"Expected indentation of 8 spaces but found 6.","line":5,"column":1,"nodeType":"Keyword","messageId":"wrongIndentation","endLine":5,"endColumn":7,"fix":{"range":[74,80],"text":" "}},{"ruleId":"consistent-return","severity":2,"message":"Function 'addOne' expected a return value.","line":5,"column":7,"nodeType":"ReturnStatement","messageId":"missingReturnValue","endLine":5,"endColumn":13},{"ruleId":"semi","severity":1,"message":"Missing semicolon.","line":5,"column":13,"nodeType":"ReturnStatement","messageId":"missingSemi","endLine":6,"endColumn":1,"fix":{"range":[86,86],"text":";"}},{"ruleId":"no-extra-semi","severity":2,"message":"Unnecessary semicolon.","line":7,"column":2,"nodeType":"EmptyStatement","messageId":"unexpected","endLine":7,"endColumn":3,"fix":{"range":[93,95],"text":"}"}}],"suppressedMessages":[],"errorCount":5,"fatalErrorCount":0,"warningCount":4,"fixableErrorCount":2,"fixableWarningCount":4,"source":"function addOne(i) {\n if (i != NaN) {\n return i ++\n } else {\n return\n }\n};"}],"metadata":{"rulesMeta":{"no-else-return":{"type":"suggestion","docs":{"description":"Disallow `else` blocks after `return` statements in `if` statements","recommended":false,"url":"https://eslint.org/docs/rules/no-else-return"},"schema":[{"type":"object","properties":{"allowElseIf":{"type":"boolean","default":true}},"additionalProperties":false}],"fixable":"code","messages":{"unexpected":"Unnecessary 'else' after 'return'."}},"indent":{"type":"layout","docs":{"description":"Enforce consistent indentation","recommended":false,"url":"https://eslint.org/docs/rules/indent"},"fixable":"whitespace","schema":[{"oneOf":[{"enum":["tab"]},{"type":"integer","minimum":0}]},{"type":"object","properties":{"SwitchCase":{"type":"integer","minimum":0,"default":0},"VariableDeclarator":{"oneOf":[{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]},{"type":"object","properties":{"var":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]},"let":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]},"const":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]}},"additionalProperties":false}]},"outerIIFEBody":{"oneOf":[{"type":"integer","minimum":0},{"enum":["off"]}]},"MemberExpression":{"oneOf":[{"type":"integer","minimum":0},{"enum":["off"]}]},"FunctionDeclaration":{"type":"object","properties":{"parameters":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]},"body":{"type":"integer","minimum":0}},"additionalProperties":false},"FunctionExpression":{"type":"object","properties":{"parameters":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]},"body":{"type":"integer","minimum":0}},"additionalProperties":false},"StaticBlock":{"type":"object","properties":{"body":{"type":"integer","minimum":0}},"additionalProperties":false},"CallExpression":{"type":"object","properties":{"arguments":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]}},"additionalProperties":false},"ArrayExpression":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]},"ObjectExpression":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]},"ImportDeclaration":{"oneOf":[{"type":"integer","minimum":0},{"enum":["first","off"]}]},"flatTernaryExpressions":{"type":"boolean","default":false},"offsetTernaryExpressions":{"type":"boolean","default":false},"ignoredNodes":{"type":"array","items":{"type":"string","not":{"pattern":":exit$"}}},"ignoreComments":{"type":"boolean","default":false}},"additionalProperties":false}],"messages":{"wrongIndentation":"Expected indentation of {{expected}} but found {{actual}}."}},"space-unary-ops":{"type":"layout","docs":{"description":"Enforce consistent spacing before or after unary operators","recommended":false,"url":"https://eslint.org/docs/rules/space-unary-ops"},"fixable":"whitespace","schema":[{"type":"object","properties":{"words":{"type":"boolean","default":true},"nonwords":{"type":"boolean","default":false},"overrides":{"type":"object","additionalProperties":{"type":"boolean"}}},"additionalProperties":false}],"messages":{"unexpectedBefore":"Unexpected space before unary operator '{{operator}}'.","unexpectedAfter":"Unexpected space after unary operator '{{operator}}'.","unexpectedAfterWord":"Unexpected space after unary word operator '{{word}}'.","wordOperator":"Unary word operator '{{word}}' must be followed by whitespace.","operator":"Unary operator '{{operator}}' must be followed by whitespace.","beforeUnaryExpressions":"Space is required before unary expressions '{{token}}'."}},"semi":{"type":"layout","docs":{"description":"Require or disallow semicolons instead of ASI","recommended":false,"url":"https://eslint.org/docs/rules/semi"},"fixable":"code","schema":{"anyOf":[{"type":"array","items":[{"enum":["never"]},{"type":"object","properties":{"beforeStatementContinuationChars":{"enum":["always","any","never"]}},"additionalProperties":false}],"minItems":0,"maxItems":2},{"type":"array","items":[{"enum":["always"]},{"type":"object","properties":{"omitLastInOneLineBlock":{"type":"boolean"}},"additionalProperties":false}],"minItems":0,"maxItems":2}]},"messages":{"missingSemi":"Missing semicolon.","extraSemi":"Extra semicolon."}},"consistent-return":{"type":"suggestion","docs":{"description":"Require `return` statements to either always or never specify values","recommended":false,"url":"https://eslint.org/docs/rules/consistent-return"},"schema":[{"type":"object","properties":{"treatUndefinedAsUnspecified":{"type":"boolean","default":false}},"additionalProperties":false}],"messages":{"missingReturn":"Expected to return a value at the end of {{name}}.","missingReturnValue":"{{name}} expected a return value.","unexpectedReturnValue":"{{name}} expected no return value."}}}}}
+```
+
+### json
+
+```text
+[{"filePath":"/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js","messages":[{"ruleId":"no-unused-vars","severity":2,"message":"'addOne' is defined but never used.","line":1,"column":10,"nodeType":"Identifier","messageId":"unusedVar","endLine":1,"endColumn":16},{"ruleId":"use-isnan","severity":2,"message":"Use the isNaN function to compare with NaN.","line":2,"column":9,"nodeType":"BinaryExpression","messageId":"comparisonWithNaN","endLine":2,"endColumn":17},{"ruleId":"space-unary-ops","severity":2,"message":"Unexpected space before unary operator '++'.","line":3,"column":16,"nodeType":"UpdateExpression","messageId":"unexpectedBefore","endLine":3,"endColumn":20,"fix":{"range":[57,58],"text":""}},{"ruleId":"semi","severity":1,"message":"Missing semicolon.","line":3,"column":20,"nodeType":"ReturnStatement","messageId":"missingSemi","endLine":4,"endColumn":1,"fix":{"range":[60,60],"text":";"}},{"ruleId":"no-else-return","severity":1,"message":"Unnecessary 'else' after 'return'.","line":4,"column":12,"nodeType":"BlockStatement","messageId":"unexpected","endLine":6,"endColumn":6,"fix":{"range":[0,94],"text":"function addOne(i) {\n if (i != NaN) {\n return i ++\n } \n return\n \n}"}},{"ruleId":"indent","severity":1,"message":"Expected indentation of 8 spaces but found 6.","line":5,"column":1,"nodeType":"Keyword","messageId":"wrongIndentation","endLine":5,"endColumn":7,"fix":{"range":[74,80],"text":" "}},{"ruleId":"consistent-return","severity":2,"message":"Function 'addOne' expected a return value.","line":5,"column":7,"nodeType":"ReturnStatement","messageId":"missingReturnValue","endLine":5,"endColumn":13},{"ruleId":"semi","severity":1,"message":"Missing semicolon.","line":5,"column":13,"nodeType":"ReturnStatement","messageId":"missingSemi","endLine":6,"endColumn":1,"fix":{"range":[86,86],"text":";"}},{"ruleId":"no-extra-semi","severity":2,"message":"Unnecessary semicolon.","line":7,"column":2,"nodeType":"EmptyStatement","messageId":"unexpected","endLine":7,"endColumn":3,"fix":{"range":[93,95],"text":"}"}}],"suppressedMessages":[],"errorCount":5,"fatalErrorCount":0,"warningCount":4,"fixableErrorCount":2,"fixableWarningCount":4,"source":"function addOne(i) {\n if (i != NaN) {\n return i ++\n } else {\n return\n }\n};"}]
+```
+
+### junit
+
+```text
+<?xml version="1.0" encoding="utf-8"?>
+<testsuites>
+<testsuite package="org.eslint" time="0" tests="9" errors="9" name="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js">
+<testcase time="0" name="org.eslint.no-unused-vars" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="'addOne' is defined but never used."><![CDATA[line 1, col 10, Error - 'addOne' is defined but never used. (no-unused-vars)]]></failure></testcase>
+<testcase time="0" name="org.eslint.use-isnan" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="Use the isNaN function to compare with NaN."><![CDATA[line 2, col 9, Error - Use the isNaN function to compare with NaN. (use-isnan)]]></failure></testcase>
+<testcase time="0" name="org.eslint.space-unary-ops" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="Unexpected space before unary operator '++'."><![CDATA[line 3, col 16, Error - Unexpected space before unary operator '++'. (space-unary-ops)]]></failure></testcase>
+<testcase time="0" name="org.eslint.semi" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="Missing semicolon."><![CDATA[line 3, col 20, Warning - Missing semicolon. (semi)]]></failure></testcase>
+<testcase time="0" name="org.eslint.no-else-return" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="Unnecessary 'else' after 'return'."><![CDATA[line 4, col 12, Warning - Unnecessary 'else' after 'return'. (no-else-return)]]></failure></testcase>
+<testcase time="0" name="org.eslint.indent" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="Expected indentation of 8 spaces but found 6."><![CDATA[line 5, col 1, Warning - Expected indentation of 8 spaces but found 6. (indent)]]></failure></testcase>
+<testcase time="0" name="org.eslint.consistent-return" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="Function 'addOne' expected a return value."><![CDATA[line 5, col 7, Error - Function 'addOne' expected a return value. (consistent-return)]]></failure></testcase>
+<testcase time="0" name="org.eslint.semi" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="Missing semicolon."><![CDATA[line 5, col 13, Warning - Missing semicolon. (semi)]]></failure></testcase>
+<testcase time="0" name="org.eslint.no-extra-semi" classname="/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems"><failure message="Unnecessary semicolon."><![CDATA[line 7, col 2, Error - Unnecessary semicolon. (no-extra-semi)]]></failure></testcase>
+</testsuite>
+</testsuites>
+
+```
+
+### stylish
+
+```text
+
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js
+ 1:10 error 'addOne' is defined but never used no-unused-vars
+ 2:9 error Use the isNaN function to compare with NaN use-isnan
+ 3:16 error Unexpected space before unary operator '++' space-unary-ops
+ 3:20 warning Missing semicolon semi
+ 4:12 warning Unnecessary 'else' after 'return' no-else-return
+ 5:1 warning Expected indentation of 8 spaces but found 6 indent
+ 5:7 error Function 'addOne' expected a return value consistent-return
+ 5:13 warning Missing semicolon semi
+ 7:2 error Unnecessary semicolon no-extra-semi
+
+✖ 9 problems (5 errors, 4 warnings)
+ 2 errors and 4 warnings potentially fixable with the `--fix` option.
+
+```
+
+### tap
+
+```text
+TAP version 13
+1..1
+not ok 1 - /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js
+ ---
+ message: '''addOne'' is defined but never used.'
+ severity: error
+ data:
+ line: 1
+ column: 10
+ ruleId: no-unused-vars
+ messages:
+ - message: Use the isNaN function to compare with NaN.
+ severity: error
+ data:
+ line: 2
+ column: 9
+ ruleId: use-isnan
+ - message: Unexpected space before unary operator '++'.
+ severity: error
+ data:
+ line: 3
+ column: 16
+ ruleId: space-unary-ops
+ - message: Missing semicolon.
+ severity: warning
+ data:
+ line: 3
+ column: 20
+ ruleId: semi
+ - message: Unnecessary 'else' after 'return'.
+ severity: warning
+ data:
+ line: 4
+ column: 12
+ ruleId: no-else-return
+ - message: Expected indentation of 8 spaces but found 6.
+ severity: warning
+ data:
+ line: 5
+ column: 1
+ ruleId: indent
+ - message: Function 'addOne' expected a return value.
+ severity: error
+ data:
+ line: 5
+ column: 7
+ ruleId: consistent-return
+ - message: Missing semicolon.
+ severity: warning
+ data:
+ line: 5
+ column: 13
+ ruleId: semi
+ - message: Unnecessary semicolon.
+ severity: error
+ data:
+ line: 7
+ column: 2
+ ruleId: no-extra-semi
+ ...
+
+```
+
+### unix
+
+```text
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:1:10: 'addOne' is defined but never used. [Error/no-unused-vars]
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:2:9: Use the isNaN function to compare with NaN. [Error/use-isnan]
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:3:16: Unexpected space before unary operator '++'. [Error/space-unary-ops]
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:3:20: Missing semicolon. [Warning/semi]
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:4:12: Unnecessary 'else' after 'return'. [Warning/no-else-return]
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:5:1: Expected indentation of 8 spaces but found 6. [Warning/indent]
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:5:7: Function 'addOne' expected a return value. [Error/consistent-return]
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:5:13: Missing semicolon. [Warning/semi]
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js:7:2: Unnecessary semicolon. [Error/no-extra-semi]
+
+9 problems
+```
+
+### visualstudio
+
+```text
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(1,10): error no-unused-vars : 'addOne' is defined but never used.
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(2,9): error use-isnan : Use the isNaN function to compare with NaN.
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(3,16): error space-unary-ops : Unexpected space before unary operator '++'.
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(3,20): warning semi : Missing semicolon.
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(4,12): warning no-else-return : Unnecessary 'else' after 'return'.
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,1): warning indent : Expected indentation of 8 spaces but found 6.
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,7): error consistent-return : Function 'addOne' expected a return value.
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,13): warning semi : Missing semicolon.
+/var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(7,2): error no-extra-semi : Unnecessary semicolon.
+
+9 problems
+```
diff --git a/docs/src/user-guide/getting-started.md b/docs/src/user-guide/getting-started.md
index 184ea122732..0004f40522b 100644
--- a/docs/src/user-guide/getting-started.md
+++ b/docs/src/user-guide/getting-started.md
@@ -20,24 +20,10 @@ ESLint is a tool for identifying and reporting on patterns found in ECMAScript/J
Prerequisites: [Node.js](https://nodejs.org/en/) (`^12.22.0`, `^14.17.0`, or `>=16.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.)
-You can install ESLint using npm or yarn:
-
-```shell
-npm install eslint --save-dev
-
-# or
-
-yarn add eslint --dev
-```
-
-You should then set up a configuration file, and the easiest way to do that is:
+You can install and configure ESLint using this command:
```shell
npm init @eslint/config
-
-# or
-
-yarn create @eslint/config
```
**Note:** `npm init @eslint/config` assumes you have a `package.json` file already. If you don't, make sure to run `npm init` or `yarn init` beforehand.
diff --git a/docs/src/user-guide/index.md b/docs/src/user-guide/index.md
index c99097354e1..558195fe9c5 100644
--- a/docs/src/user-guide/index.md
+++ b/docs/src/user-guide/index.md
@@ -3,18 +3,18 @@ title: User Guide
layout: doc
edit_link: https://github.com/eslint/eslint/edit/main/docs/src/user-guide/index.md
eleventyNavigation:
- key: user guide
- title: User Guide
+ key: user guide
+ title: User Guide
order: 1
---
-This guide is intended for those who wish to use ESLint as an end-user. If you're looking for how to extend ESLint or work with the ESLint source code, please see the [Developer Guide](../developer-guide).
+This guide is intended for those who wish to use ESLint as an end-user. If you're looking for how to extend ESLint or work with the ESLint source code, please see the [Developer Guide](../developer-guide/).
## [Getting Started](getting-started)
Want to skip ahead and just start using ESLint? This section gives a high-level overview of installation, setup, and configuration options.
-## [Rules](../rules)
+## [Rules](../rules/)
ESLint has a lot of rules that you can configure to fine-tune it to your project. This section is an exhaustive list of every rule and link to each rule's documentation.
@@ -45,3 +45,4 @@ If you were using a prior version of ESLint, you can get help with the transitio
* [migrating-to-5.0.0](migrating-to-5.0.0)
* [migrating-to-6.0.0](migrating-to-6.0.0)
* [migrating-to-7.0.0](migrating-to-7.0.0)
+* [migrating-to-8.0.0](migrating-to-8.0.0)
diff --git a/eslint.config.js b/eslint.config.js
new file mode 100644
index 00000000000..50f375d3316
--- /dev/null
+++ b/eslint.config.js
@@ -0,0 +1,227 @@
+/**
+ * @fileoverview ESLint configuration file
+ * @author Nicholas C. Zakas
+ */
+
+"use strict";
+
+//-----------------------------------------------------------------------------
+// Requirements
+//-----------------------------------------------------------------------------
+
+const path = require("path");
+const internalPlugin = require("eslint-plugin-internal-rules");
+const { FlatCompat } = require("@eslint/eslintrc");
+const globals = require("globals");
+
+//-----------------------------------------------------------------------------
+// Helpers
+//-----------------------------------------------------------------------------
+
+const compat = new FlatCompat({
+ baseDirectory: __dirname
+});
+
+const INTERNAL_FILES = {
+ CLI_ENGINE_PATTERN: "lib/cli-engine/**/*",
+ INIT_PATTERN: "lib/init/**/*",
+ LINTER_PATTERN: "lib/linter/**/*",
+ RULE_TESTER_PATTERN: "lib/rule-tester/**/*",
+ RULES_PATTERN: "lib/rules/**/*",
+ SOURCE_CODE_PATTERN: "lib/source-code/**/*"
+};
+
+/**
+ * Resolve an absolute path or glob pattern.
+ * @param {string} pathOrPattern the path or glob pattern.
+ * @returns {string} The resolved path or glob pattern.
+ */
+function resolveAbsolutePath(pathOrPattern) {
+ return path.resolve(__dirname, pathOrPattern);
+}
+
+/**
+ * Create an array of `no-restricted-require` entries for ESLint's core files.
+ * @param {string} [pattern] The glob pattern to create the entries for.
+ * @returns {Object[]} The array of `no-restricted-require` entries.
+ */
+function createInternalFilesPatterns(pattern = null) {
+ return Object.values(INTERNAL_FILES)
+ .filter(p => p !== pattern)
+ .map(p => ({
+ name: [
+
+ // Disallow all children modules.
+ resolveAbsolutePath(p),
+
+ // Allow the main `index.js` module.
+ `!${resolveAbsolutePath(p.replace(/\*\*\/\*$/u, "index.js"))}`
+ ]
+ }));
+}
+
+
+//-----------------------------------------------------------------------------
+// Config
+//-----------------------------------------------------------------------------
+
+module.exports = [
+ ...compat.extends("eslint", "plugin:eslint-plugin/recommended"),
+ {
+ plugins: {
+ "internal-rules": internalPlugin
+ },
+ languageOptions: {
+ ecmaVersion: "latest"
+ },
+
+ /*
+ * it fixes eslint-plugin-jsdoc's reports: "Invalid JSDoc tag name "template" jsdoc/check-tag-names"
+ * refs: https://github.com/gajus/eslint-plugin-jsdoc#check-tag-names
+ */
+ settings: {
+ jsdoc: {
+ mode: "typescript"
+ }
+ },
+ rules: {
+ "eslint-plugin/consistent-output": "error",
+ "eslint-plugin/no-deprecated-context-methods": "error",
+ "eslint-plugin/no-only-tests": "error",
+ "eslint-plugin/prefer-message-ids": "error",
+ "eslint-plugin/prefer-output-null": "error",
+ "eslint-plugin/prefer-placeholders": "error",
+ "eslint-plugin/prefer-replace-text": "error",
+ "eslint-plugin/report-message-format": ["error", "[^a-z].*\\.$"],
+ "eslint-plugin/require-meta-docs-description": "error",
+ "eslint-plugin/require-meta-has-suggestions": "error",
+ "eslint-plugin/require-meta-schema": "error",
+ "eslint-plugin/require-meta-type": "error",
+ "eslint-plugin/test-case-property-ordering": "error",
+ "eslint-plugin/test-case-shorthand-strings": "error",
+ "internal-rules/multiline-comment-style": "error"
+ }
+
+ },
+ {
+ files: ["lib/rules/*", "tools/internal-rules/*"],
+ ignores: ["index.js"],
+ rules: {
+ "eslint-plugin/prefer-object-rule": "error",
+ "internal-rules/no-invalid-meta": "error"
+ }
+ },
+ {
+ files: ["lib/rules/*"],
+ ignores: ["index.js"],
+ rules: {
+ "eslint-plugin/require-meta-docs-url": ["error", { pattern: "https://eslint.org/docs/rules/{{name}}" }]
+ }
+ },
+ {
+ files: ["tests/**/*"],
+ languageOptions: {
+ globals: {
+ ...globals.mocha
+ }
+ },
+ rules: {
+ "no-restricted-syntax": ["error", {
+ selector: "CallExpression[callee.object.name='assert'][callee.property.name='doesNotThrow']",
+ message: "`assert.doesNotThrow()` should be replaced with a comment next to the code."
+ }]
+ }
+ },
+
+ // Restrict relative path imports
+ {
+ files: ["lib/*"],
+ ignores: ["lib/unsupported-api.js"],
+ rules: {
+ "n/no-restricted-require": ["error", [
+ ...createInternalFilesPatterns()
+ ]]
+ }
+ },
+ {
+ files: [INTERNAL_FILES.CLI_ENGINE_PATTERN],
+ rules: {
+ "n/no-restricted-require": ["error", [
+ ...createInternalFilesPatterns(INTERNAL_FILES.CLI_ENGINE_PATTERN),
+ resolveAbsolutePath("lib/init/index.js")
+ ]]
+ }
+ },
+ {
+ files: [INTERNAL_FILES.INIT_PATTERN],
+ rules: {
+ "n/no-restricted-require": ["error", [
+ ...createInternalFilesPatterns(INTERNAL_FILES.INIT_PATTERN),
+ resolveAbsolutePath("lib/rule-tester/index.js")
+ ]]
+ }
+ },
+ {
+ files: [INTERNAL_FILES.LINTER_PATTERN],
+ rules: {
+ "n/no-restricted-require": ["error", [
+ ...createInternalFilesPatterns(INTERNAL_FILES.LINTER_PATTERN),
+ "fs",
+ resolveAbsolutePath("lib/cli-engine/index.js"),
+ resolveAbsolutePath("lib/init/index.js"),
+ resolveAbsolutePath("lib/rule-tester/index.js")
+ ]]
+ }
+ },
+ {
+ files: [INTERNAL_FILES.RULES_PATTERN],
+ rules: {
+ "n/no-restricted-require": ["error", [
+ ...createInternalFilesPatterns(INTERNAL_FILES.RULES_PATTERN),
+ "fs",
+ resolveAbsolutePath("lib/cli-engine/index.js"),
+ resolveAbsolutePath("lib/init/index.js"),
+ resolveAbsolutePath("lib/linter/index.js"),
+ resolveAbsolutePath("lib/rule-tester/index.js"),
+ resolveAbsolutePath("lib/source-code/index.js")
+ ]]
+ }
+ },
+ {
+ files: ["lib/shared/**/*"],
+ rules: {
+ "n/no-restricted-require": ["error", [
+ ...createInternalFilesPatterns(),
+ resolveAbsolutePath("lib/cli-engine/index.js"),
+ resolveAbsolutePath("lib/init/index.js"),
+ resolveAbsolutePath("lib/linter/index.js"),
+ resolveAbsolutePath("lib/rule-tester/index.js"),
+ resolveAbsolutePath("lib/source-code/index.js")
+ ]]
+ }
+ },
+ {
+ files: [INTERNAL_FILES.SOURCE_CODE_PATTERN],
+ rules: {
+ "n/no-restricted-require": ["error", [
+ ...createInternalFilesPatterns(INTERNAL_FILES.SOURCE_CODE_PATTERN),
+ "fs",
+ resolveAbsolutePath("lib/cli-engine/index.js"),
+ resolveAbsolutePath("lib/init/index.js"),
+ resolveAbsolutePath("lib/linter/index.js"),
+ resolveAbsolutePath("lib/rule-tester/index.js"),
+ resolveAbsolutePath("lib/rules/index.js")
+ ]]
+ }
+ },
+ {
+ files: [INTERNAL_FILES.RULE_TESTER_PATTERN],
+ rules: {
+ "n/no-restricted-require": ["error", [
+ ...createInternalFilesPatterns(INTERNAL_FILES.RULE_TESTER_PATTERN),
+ resolveAbsolutePath("lib/cli-engine/index.js"),
+ resolveAbsolutePath("lib/init/index.js")
+ ]]
+ }
+ }
+];
diff --git a/lib/config/default-config.js b/lib/config/default-config.js
index a655a6d83ca..c48551a4f2a 100644
--- a/lib/config/default-config.js
+++ b/lib/config/default-config.js
@@ -15,7 +15,6 @@ const Rules = require("../rules");
// Helpers
//-----------------------------------------------------------------------------
-
exports.defaultConfig = [
{
plugins: {
@@ -41,21 +40,31 @@ exports.defaultConfig = [
})
}
},
- ignores: [
- "**/node_modules/**",
- ".git/**"
- ],
languageOptions: {
- ecmaVersion: "latest",
sourceType: "module",
+ ecmaVersion: "latest",
parser: "@/espree",
parserOptions: {}
}
},
+
+ // default ignores are listed here
+ {
+ ignores: [
+ "**/node_modules/**",
+ ".git/**"
+ ]
+ },
+
+ // intentionally empty config to ensure these files are globbed by default
+ {
+ files: ["**/*.js", "**/*.mjs"]
+ },
{
files: ["**/*.cjs"],
languageOptions: {
- sourceType: "commonjs"
+ sourceType: "commonjs",
+ ecmaVersion: "latest"
}
}
];
diff --git a/lib/config/flat-config-array.js b/lib/config/flat-config-array.js
index fbedf139d8b..becf1e10b09 100644
--- a/lib/config/flat-config-array.js
+++ b/lib/config/flat-config-array.js
@@ -36,6 +36,8 @@ function splitPluginIdentifier(identifier) {
};
}
+const originalBaseConfig = Symbol("originalBaseConfig");
+
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
@@ -48,10 +50,14 @@ class FlatConfigArray extends ConfigArray {
/**
* Creates a new instance.
* @param {*[]} configs An array of configuration information.
- * @param {{basePath: string, baseConfig: FlatConfig}} options The options
+ * @param {{basePath: string, shouldIgnore: boolean, baseConfig: FlatConfig}} options The options
* to use for the config array instance.
*/
- constructor(configs, { basePath, baseConfig = defaultConfig } = {}) {
+ constructor(configs, {
+ basePath,
+ shouldIgnore = true,
+ baseConfig = defaultConfig
+ } = {}) {
super(configs, {
basePath,
schema: flatConfigSchema
@@ -62,6 +68,22 @@ class FlatConfigArray extends ConfigArray {
} else {
this.unshift(baseConfig);
}
+
+ /**
+ * The baes config used to build the config array.
+ * @type {Array}
+ */
+ this[originalBaseConfig] = baseConfig;
+ Object.defineProperty(this, originalBaseConfig, { writable: false });
+
+ /**
+ * Determines if `ignores` fields should be honored.
+ * If true, then all `ignores` fields are honored.
+ * if false, then only `ignores` fields in the baseConfig are honored.
+ * @type {boolean}
+ */
+ this.shouldIgnore = shouldIgnore;
+ Object.defineProperty(this, "shouldIgnore", { writable: false });
}
/* eslint-disable class-methods-use-this -- Desired as instance method */
@@ -87,6 +109,23 @@ class FlatConfigArray extends ConfigArray {
return require("../../conf/eslint-all");
}
+ /*
+ * If `shouldIgnore` is false, we remove any ignore patterns specified
+ * in the config so long as it's not a default config and it doesn't
+ * have a `files` entry.
+ */
+ if (
+ !this.shouldIgnore &&
+ !this[originalBaseConfig].includes(config) &&
+ config.ignores &&
+ !config.files
+ ) {
+ /* eslint-disable-next-line no-unused-vars -- need to strip off other keys */
+ const { ignores, ...otherKeys } = config;
+
+ return otherKeys;
+ }
+
return config;
}
diff --git a/lib/config/flat-config-helpers.js b/lib/config/flat-config-helpers.js
index bcc4eb12082..e00c56434cd 100644
--- a/lib/config/flat-config-helpers.js
+++ b/lib/config/flat-config-helpers.js
@@ -20,7 +20,14 @@ function parseRuleId(ruleId) {
// distinguish between core rules and plugin rules
if (ruleId.includes("/")) {
- pluginName = ruleId.slice(0, ruleId.lastIndexOf("/"));
+
+ // mimic scoped npm packages
+ if (ruleId.startsWith("@")) {
+ pluginName = ruleId.slice(0, ruleId.lastIndexOf("/"));
+ } else {
+ pluginName = ruleId.slice(0, ruleId.indexOf("/"));
+ }
+
ruleName = ruleId.slice(pluginName.length + 1);
} else {
pluginName = "@";
@@ -47,6 +54,7 @@ function getRuleFromConfig(ruleId, config) {
const plugin = config.plugins && config.plugins[pluginName];
let rule = plugin && plugin.rules && plugin.rules[ruleName];
+
// normalize function rules into objects
if (rule && typeof rule === "function") {
rule = {
diff --git a/lib/eslint/eslint-helpers.js b/lib/eslint/eslint-helpers.js
new file mode 100644
index 00000000000..bf5c32a646d
--- /dev/null
+++ b/lib/eslint/eslint-helpers.js
@@ -0,0 +1,621 @@
+/**
+ * @fileoverview Helper functions for ESLint class
+ * @author Nicholas C. Zakas
+ */
+
+"use strict";
+
+//-----------------------------------------------------------------------------
+// Requirements
+//-----------------------------------------------------------------------------
+
+const path = require("path");
+const fs = require("fs");
+const fsp = fs.promises;
+const isGlob = require("is-glob");
+const globby = require("globby");
+const hash = require("../cli-engine/hash");
+
+//-----------------------------------------------------------------------------
+// Errors
+//-----------------------------------------------------------------------------
+
+/**
+ * The error type when no files match a glob.
+ */
+class NoFilesFoundError extends Error {
+
+ /**
+ * @param {string} pattern The glob pattern which was not found.
+ * @param {boolean} globEnabled If `false` then the pattern was a glob pattern, but glob was disabled.
+ */
+ constructor(pattern, globEnabled) {
+ super(`No files matching '${pattern}' were found${!globEnabled ? " (glob was disabled)" : ""}.`);
+ this.messageTemplate = "file-not-found";
+ this.messageData = { pattern, globDisabled: !globEnabled };
+ }
+}
+
+/**
+ * The error type when there are files matched by a glob, but all of them have been ignored.
+ */
+class AllFilesIgnoredError extends Error {
+
+ /**
+ * @param {string} pattern The glob pattern which was not found.
+ */
+ constructor(pattern) {
+ super(`All files matched by '${pattern}' are ignored.`);
+ this.messageTemplate = "all-files-ignored";
+ this.messageData = { pattern };
+ }
+}
+
+
+//-----------------------------------------------------------------------------
+// General Helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * Check if a given value is a non-empty string or not.
+ * @param {any} x The value to check.
+ * @returns {boolean} `true` if `x` is a non-empty string.
+ */
+function isNonEmptyString(x) {
+ return typeof x === "string" && x.trim() !== "";
+}
+
+/**
+ * Check if a given value is an array of non-empty stringss or not.
+ * @param {any} x The value to check.
+ * @returns {boolean} `true` if `x` is an array of non-empty stringss.
+ */
+function isArrayOfNonEmptyString(x) {
+ return Array.isArray(x) && x.every(isNonEmptyString);
+}
+
+//-----------------------------------------------------------------------------
+// File-related Helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * Normalizes slashes in a file pattern to posix-style.
+ * @param {string} pattern The pattern to replace slashes in.
+ * @returns {string} The pattern with slashes normalized.
+ */
+function normalizeToPosix(pattern) {
+ return pattern.replace(/\\/gu, "/");
+}
+
+/**
+ * Check if a string is a glob pattern or not.
+ * @param {string} pattern A glob pattern.
+ * @returns {boolean} `true` if the string is a glob pattern.
+ */
+function isGlobPattern(pattern) {
+ return isGlob(path.sep === "\\" ? normalizeToPosix(pattern) : pattern);
+}
+
+/**
+ * Finds all files matching the options specified.
+ * @param {Object} args The arguments objects.
+ * @param {Array} args.patterns An array of glob patterns.
+ * @param {boolean} args.globInputPaths true to interpret glob patterns,
+ * false to not interpret glob patterns.
+ * @param {string} args.cwd The current working directory to find from.
+ * @param {FlatConfigArray} args.configs The configs for the current run.
+ * @returns {Promise>} The fully resolved file paths.
+ * @throws {AllFilesIgnoredError} If there are no results due to an ignore pattern.
+ * @throws {NoFilesFoundError} If no files matched the given patterns.
+ */
+async function findFiles({
+ patterns,
+ globInputPaths,
+ cwd,
+ configs
+}) {
+
+ const results = [];
+ const globbyPatterns = [];
+ const missingPatterns = [];
+
+ // check to see if we have explicit files and directories
+ const filePaths = patterns.map(filePath => path.resolve(cwd, filePath));
+ const stats = await Promise.all(
+ filePaths.map(
+ filePath => fsp.stat(filePath).catch(() => {})
+ )
+ );
+
+ stats.forEach((stat, index) => {
+
+ const filePath = filePaths[index];
+ const pattern = patterns[index];
+
+ if (stat) {
+
+ // files are added directly to the list
+ if (stat.isFile()) {
+ results.push({
+ filePath,
+ ignored: configs.isIgnored(filePath)
+ });
+ }
+
+ // directories need extensions attached
+ if (stat.isDirectory()) {
+
+ // filePatterns are all relative to cwd
+ const filePatterns = configs.files
+ .filter(filePattern => {
+
+ // can only do this for strings, not functions
+ if (typeof filePattern !== "string") {
+ return false;
+ }
+
+ // patterns ending with * are not used for file search
+ if (filePattern.endsWith("*")) {
+ return false;
+ }
+
+ // not sure how to handle negated patterns yet
+ if (filePattern.startsWith("!")) {
+ return false;
+ }
+
+ // check if the pattern would be inside the cwd or not
+ const fullFilePattern = path.join(cwd, filePattern);
+ const relativeFilePattern = path.relative(configs.basePath, fullFilePattern);
+
+ return !relativeFilePattern.startsWith("..");
+ })
+ .map(filePattern => {
+ if (filePattern.startsWith("**")) {
+ return path.join(pattern, filePattern);
+ }
+
+ // adjust the path to be relative to the cwd
+ return path.relative(
+ cwd,
+ path.join(configs.basePath, filePattern)
+ );
+ })
+ .map(normalizeToPosix);
+
+ if (filePatterns.length) {
+ globbyPatterns.push(...filePatterns);
+ }
+
+ }
+
+ return;
+ }
+
+ // save patterns for later use based on whether globs are enabled
+ if (globInputPaths && isGlobPattern(filePath)) {
+ globbyPatterns.push(pattern);
+ } else {
+ missingPatterns.push(pattern);
+ }
+ });
+
+ // note: globbyPatterns can be an empty array
+ const globbyResults = (await globby(globbyPatterns, {
+ cwd,
+ absolute: true,
+ ignore: configs.ignores.filter(matcher => typeof matcher === "string")
+ }));
+
+ // if there are no results, tell the user why
+ if (!results.length && !globbyResults.length) {
+
+ // try globby without ignoring anything
+ /* eslint-disable no-unreachable-loop -- We want to exit early. */
+ for (const globbyPattern of globbyPatterns) {
+
+ /* eslint-disable-next-line no-unused-vars -- Want to exit early. */
+ for await (const filePath of globby.stream(globbyPattern, { cwd, absolute: true })) {
+
+ // files were found but ignored
+ throw new AllFilesIgnoredError(globbyPattern);
+ }
+
+ // no files were found
+ throw new NoFilesFoundError(globbyPattern, globInputPaths);
+ }
+ /* eslint-enable no-unreachable-loop -- Go back to normal. */
+
+ }
+
+ // there were patterns that didn't match anything, tell the user
+ if (missingPatterns.length) {
+ throw new NoFilesFoundError(missingPatterns[0], globInputPaths);
+ }
+
+
+ return [
+ ...results,
+ ...globbyResults.map(filePath => ({
+ filePath: path.resolve(filePath),
+ ignored: false
+ }))
+ ];
+}
+
+
+/**
+ * Checks whether a file exists at the given location
+ * @param {string} resolvedPath A path from the CWD
+ * @throws {Error} As thrown by `fs.statSync` or `fs.isFile`.
+ * @returns {boolean} `true` if a file exists
+ */
+function fileExists(resolvedPath) {
+ try {
+ return fs.statSync(resolvedPath).isFile();
+ } catch (error) {
+ if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
+ return false;
+ }
+ throw error;
+ }
+}
+
+/**
+ * Checks whether a directory exists at the given location
+ * @param {string} resolvedPath A path from the CWD
+ * @throws {Error} As thrown by `fs.statSync` or `fs.isDirectory`.
+ * @returns {boolean} `true` if a directory exists
+ */
+function directoryExists(resolvedPath) {
+ try {
+ return fs.statSync(resolvedPath).isDirectory();
+ } catch (error) {
+ if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
+ return false;
+ }
+ throw error;
+ }
+}
+
+//-----------------------------------------------------------------------------
+// Results-related Helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * Checks if the given message is an error message.
+ * @param {LintMessage} message The message to check.
+ * @returns {boolean} Whether or not the message is an error message.
+ * @private
+ */
+function isErrorMessage(message) {
+ return message.severity === 2;
+}
+
+/**
+ * Returns result with warning by ignore settings
+ * @param {string} filePath File path of checked code
+ * @param {string} baseDir Absolute path of base directory
+ * @returns {LintResult} Result with single warning
+ * @private
+ */
+function createIgnoreResult(filePath, baseDir) {
+ let message;
+ const isHidden = filePath.split(path.sep)
+ .find(segment => /^\./u.test(segment));
+ const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules");
+
+ if (isHidden) {
+ message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!'\") to override.";
+ } else if (isInNodeModules) {
+ message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
+ } else {
+ message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.";
+ }
+
+ return {
+ filePath: path.resolve(filePath),
+ messages: [
+ {
+ fatal: false,
+ severity: 1,
+ message
+ }
+ ],
+ errorCount: 0,
+ warningCount: 1,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0
+ };
+}
+
+//-----------------------------------------------------------------------------
+// Options-related Helpers
+//-----------------------------------------------------------------------------
+
+
+/**
+ * Check if a given value is a valid fix type or not.
+ * @param {any} x The value to check.
+ * @returns {boolean} `true` if `x` is valid fix type.
+ */
+function isFixType(x) {
+ return x === "directive" || x === "problem" || x === "suggestion" || x === "layout";
+}
+
+/**
+ * Check if a given value is an array of fix types or not.
+ * @param {any} x The value to check.
+ * @returns {boolean} `true` if `x` is an array of fix types.
+ */
+function isFixTypeArray(x) {
+ return Array.isArray(x) && x.every(isFixType);
+}
+
+/**
+ * The error for invalid options.
+ */
+class ESLintInvalidOptionsError extends Error {
+ constructor(messages) {
+ super(`Invalid Options:\n- ${messages.join("\n- ")}`);
+ this.code = "ESLINT_INVALID_OPTIONS";
+ Error.captureStackTrace(this, ESLintInvalidOptionsError);
+ }
+}
+
+/**
+ * Validates and normalizes options for the wrapped CLIEngine instance.
+ * @param {FlatESLintOptions} options The options to process.
+ * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors.
+ * @returns {FlatESLintOptions} The normalized options.
+ */
+function processOptions({
+ allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored.
+ baseConfig = null,
+ cache = false,
+ cacheLocation = ".eslintcache",
+ cacheStrategy = "metadata",
+ cwd = process.cwd(),
+ errorOnUnmatchedPattern = true,
+ extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature.
+ fix = false,
+ fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property.
+ globInputPaths = true,
+ ignore = true,
+ ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT.
+ ignorePatterns = null,
+ overrideConfig = null,
+ overrideConfigFile = null,
+ plugins = {},
+ reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that.
+ ...unknownOptions
+}) {
+ const errors = [];
+ const unknownOptionKeys = Object.keys(unknownOptions);
+
+ if (unknownOptionKeys.length >= 1) {
+ errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`);
+ if (unknownOptionKeys.includes("cacheFile")) {
+ errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead.");
+ }
+ if (unknownOptionKeys.includes("configFile")) {
+ errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead.");
+ }
+ if (unknownOptionKeys.includes("envs")) {
+ errors.push("'envs' has been removed.");
+ }
+ if (unknownOptionKeys.includes("resolvePluginsRelativeTo")) {
+ errors.push("'resolvePluginsRelativeTo' has been removed.");
+ }
+ if (unknownOptionKeys.includes("globals")) {
+ errors.push("'globals' has been removed. Please use the 'overrideConfig.languageOptions.globals' option instead.");
+ }
+ if (unknownOptionKeys.includes("ignorePattern")) {
+ errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.");
+ }
+ if (unknownOptionKeys.includes("parser")) {
+ errors.push("'parser' has been removed. Please use the 'overrideConfig.languageOptions.parser' option instead.");
+ }
+ if (unknownOptionKeys.includes("parserOptions")) {
+ errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.languageOptions.parserOptions' option instead.");
+ }
+ if (unknownOptionKeys.includes("rules")) {
+ errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead.");
+ }
+ if (unknownOptionKeys.includes("rulePaths")) {
+ errors.push("'rulePaths' has been removed. Please define your rules using plugins.");
+ }
+ }
+ if (typeof allowInlineConfig !== "boolean") {
+ errors.push("'allowInlineConfig' must be a boolean.");
+ }
+ if (typeof baseConfig !== "object") {
+ errors.push("'baseConfig' must be an object or null.");
+ }
+ if (typeof cache !== "boolean") {
+ errors.push("'cache' must be a boolean.");
+ }
+ if (cache) {
+ errors.push("'cache' option is not yet supported.");
+ }
+ if (!isNonEmptyString(cacheLocation)) {
+ errors.push("'cacheLocation' must be a non-empty string.");
+ }
+ if (
+ cacheStrategy !== "metadata" &&
+ cacheStrategy !== "content"
+ ) {
+ errors.push("'cacheStrategy' must be any of \"metadata\", \"content\".");
+ }
+ if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) {
+ errors.push("'cwd' must be an absolute path.");
+ }
+ if (typeof errorOnUnmatchedPattern !== "boolean") {
+ errors.push("'errorOnUnmatchedPattern' must be a boolean.");
+ }
+ if (!isArrayOfNonEmptyString(extensions) && extensions !== null) {
+ errors.push("'extensions' must be an array of non-empty strings or null.");
+ }
+ if (typeof fix !== "boolean" && typeof fix !== "function") {
+ errors.push("'fix' must be a boolean or a function.");
+ }
+ if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
+ errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".");
+ }
+ if (typeof globInputPaths !== "boolean") {
+ errors.push("'globInputPaths' must be a boolean.");
+ }
+ if (typeof ignore !== "boolean") {
+ errors.push("'ignore' must be a boolean.");
+ }
+ if (!isNonEmptyString(ignorePath) && ignorePath !== null) {
+ errors.push("'ignorePath' must be a non-empty string or null.");
+ }
+ if (typeof overrideConfig !== "object") {
+ errors.push("'overrideConfig' must be an object or null.");
+ }
+ if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null && overrideConfigFile !== true) {
+ errors.push("'overrideConfigFile' must be a non-empty string, null, or true.");
+ }
+ if (typeof plugins !== "object") {
+ errors.push("'plugins' must be an object or null.");
+ } else if (plugins !== null && Object.keys(plugins).includes("")) {
+ errors.push("'plugins' must not include an empty string.");
+ }
+ if (Array.isArray(plugins)) {
+ errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.");
+ }
+ if (
+ reportUnusedDisableDirectives !== "error" &&
+ reportUnusedDisableDirectives !== "warn" &&
+ reportUnusedDisableDirectives !== "off" &&
+ reportUnusedDisableDirectives !== null
+ ) {
+ errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null.");
+ }
+ if (errors.length > 0) {
+ throw new ESLintInvalidOptionsError(errors);
+ }
+
+ return {
+ allowInlineConfig,
+ baseConfig,
+ cache,
+ cacheLocation,
+ cacheStrategy,
+
+ // when overrideConfigFile is true that means don't do config file lookup
+ configFile: overrideConfigFile === true ? false : overrideConfigFile,
+ overrideConfig,
+ cwd,
+ errorOnUnmatchedPattern,
+ extensions,
+ fix,
+ fixTypes,
+ globInputPaths,
+ ignore,
+ ignorePath,
+ ignorePatterns,
+ reportUnusedDisableDirectives
+ };
+}
+
+
+//-----------------------------------------------------------------------------
+// Cache-related helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * return the cacheFile to be used by eslint, based on whether the provided parameter is
+ * a directory or looks like a directory (ends in `path.sep`), in which case the file
+ * name will be the `cacheFile/.cache_hashOfCWD`
+ *
+ * if cacheFile points to a file or looks like a file then in will just use that file
+ * @param {string} cacheFile The name of file to be used to store the cache
+ * @param {string} cwd Current working directory
+ * @returns {string} the resolved path to the cache file
+ */
+function getCacheFile(cacheFile, cwd) {
+
+ /*
+ * make sure the path separators are normalized for the environment/os
+ * keeping the trailing path separator if present
+ */
+ const normalizedCacheFile = path.normalize(cacheFile);
+
+ const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile);
+ const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep;
+
+ /**
+ * return the name for the cache file in case the provided parameter is a directory
+ * @returns {string} the resolved path to the cacheFile
+ */
+ function getCacheFileForDirectory() {
+ return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`);
+ }
+
+ let fileStats;
+
+ try {
+ fileStats = fs.lstatSync(resolvedCacheFile);
+ } catch {
+ fileStats = null;
+ }
+
+
+ /*
+ * in case the file exists we need to verify if the provided path
+ * is a directory or a file. If it is a directory we want to create a file
+ * inside that directory
+ */
+ if (fileStats) {
+
+ /*
+ * is a directory or is a file, but the original file the user provided
+ * looks like a directory but `path.resolve` removed the `last path.sep`
+ * so we need to still treat this like a directory
+ */
+ if (fileStats.isDirectory() || looksLikeADirectory) {
+ return getCacheFileForDirectory();
+ }
+
+ // is file so just use that file
+ return resolvedCacheFile;
+ }
+
+ /*
+ * here we known the file or directory doesn't exist,
+ * so we will try to infer if its a directory if it looks like a directory
+ * for the current operating system.
+ */
+
+ // if the last character passed is a path separator we assume is a directory
+ if (looksLikeADirectory) {
+ return getCacheFileForDirectory();
+ }
+
+ return resolvedCacheFile;
+}
+
+
+//-----------------------------------------------------------------------------
+// Exports
+//-----------------------------------------------------------------------------
+
+module.exports = {
+ isGlobPattern,
+ directoryExists,
+ fileExists,
+ findFiles,
+
+ isNonEmptyString,
+ isArrayOfNonEmptyString,
+
+ createIgnoreResult,
+ isErrorMessage,
+
+ processOptions,
+
+ getCacheFile
+};
diff --git a/lib/eslint/eslint.js b/lib/eslint/eslint.js
index 927b60802a3..9a3bd66e487 100644
--- a/lib/eslint/eslint.js
+++ b/lib/eslint/eslint.js
@@ -104,9 +104,9 @@ function isNonEmptyString(x) {
}
/**
- * Check if a given value is an array of non-empty stringss or not.
+ * Check if a given value is an array of non-empty strings or not.
* @param {any} x The value to check.
- * @returns {boolean} `true` if `x` is an array of non-empty stringss.
+ * @returns {boolean} `true` if `x` is an array of non-empty strings.
*/
function isArrayOfNonEmptyString(x) {
return Array.isArray(x) && x.every(isNonEmptyString);
@@ -599,7 +599,7 @@ class ESLint {
* The following values are allowed:
* - `undefined` ... Load `stylish` builtin formatter.
* - A builtin formatter name ... Load the builtin formatter.
- * - A thirdparty formatter name:
+ * - A third-party formatter name:
* - `foo` → `eslint-formatter-foo`
* - `@foo` → `@foo/eslint-formatter`
* - `@foo/bar` → `@foo/eslint-formatter-bar`
diff --git a/lib/eslint/flat-eslint.js b/lib/eslint/flat-eslint.js
new file mode 100644
index 00000000000..1867050e43f
--- /dev/null
+++ b/lib/eslint/flat-eslint.js
@@ -0,0 +1,1164 @@
+/**
+ * @fileoverview Main class using flat config
+ * @author Nicholas C. Zakas
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+// Note: Node.js 12 does not support fs/promises.
+const fs = require("fs").promises;
+const path = require("path");
+const findUp = require("find-up");
+const { version } = require("../../package.json");
+const { Linter } = require("../linter");
+const { getRuleFromConfig } = require("../config/flat-config-helpers");
+const { gitignoreToMinimatch } = require("@humanwhocodes/gitignore-to-minimatch");
+const {
+ Legacy: {
+ ConfigOps: {
+ getRuleSeverity
+ },
+ ModuleResolver,
+ naming
+ }
+} = require("@eslint/eslintrc");
+
+const {
+ fileExists,
+ findFiles,
+
+ isNonEmptyString,
+ isArrayOfNonEmptyString,
+
+ createIgnoreResult,
+ isErrorMessage,
+
+ processOptions
+} = require("./eslint-helpers");
+const { pathToFileURL } = require("url");
+const { FlatConfigArray } = require("../config/flat-config-array");
+
+/*
+ * This is necessary to allow overwriting writeFile for testing purposes.
+ * We can just use fs/promises once we drop Node.js 12 support.
+ */
+
+//------------------------------------------------------------------------------
+// Typedefs
+//------------------------------------------------------------------------------
+
+// For VSCode IntelliSense
+/** @typedef {import("../shared/types").ConfigData} ConfigData */
+/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
+/** @typedef {import("../shared/types").LintMessage} LintMessage */
+/** @typedef {import("../shared/types").ParserOptions} ParserOptions */
+/** @typedef {import("../shared/types").Plugin} Plugin */
+/** @typedef {import("../shared/types").RuleConf} RuleConf */
+/** @typedef {import("../shared/types").Rule} Rule */
+/** @typedef {ReturnType} ExtractedConfig */
+
+/**
+ * The options with which to configure the ESLint instance.
+ * @typedef {Object} FlatESLintOptions
+ * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
+ * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
+ * @property {boolean} [cache] Enable result caching.
+ * @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
+ * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
+ * @property {string} [cwd] The value to use for the current working directory.
+ * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
+ * @property {string[]} [extensions] An array of file extensions to check.
+ * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
+ * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
+ * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
+ * @property {boolean} [ignore] False disables use of .eslintignore.
+ * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
+ * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to .eslintignore.
+ * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
+ * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy;
+ * doesn't do any config file lookup when `true`; considered to be a config filename
+ * when a string.
+ * @property {Record} [plugins] An array of plugin implementations.
+ * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
+ */
+
+//------------------------------------------------------------------------------
+// Helpers
+//------------------------------------------------------------------------------
+
+const FLAT_CONFIG_FILENAME = "eslint.config.js";
+const debug = require("debug")("eslint:flat-eslint");
+const removedFormatters = new Set(["table", "codeframe"]);
+const privateMembers = new WeakMap();
+
+/**
+ * It will calculate the error and warning count for collection of messages per file
+ * @param {LintMessage[]} messages Collection of messages
+ * @returns {Object} Contains the stats
+ * @private
+ */
+function calculateStatsPerFile(messages) {
+ return messages.reduce((stat, message) => {
+ if (message.fatal || message.severity === 2) {
+ stat.errorCount++;
+ if (message.fatal) {
+ stat.fatalErrorCount++;
+ }
+ if (message.fix) {
+ stat.fixableErrorCount++;
+ }
+ } else {
+ stat.warningCount++;
+ if (message.fix) {
+ stat.fixableWarningCount++;
+ }
+ }
+ return stat;
+ }, {
+ errorCount: 0,
+ fatalErrorCount: 0,
+ warningCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0
+ });
+}
+
+/**
+ * It will calculate the error and warning count for collection of results from all files
+ * @param {LintResult[]} results Collection of messages from all the files
+ * @returns {Object} Contains the stats
+ * @private
+ */
+function calculateStatsPerRun(results) {
+ return results.reduce((stat, result) => {
+ stat.errorCount += result.errorCount;
+ stat.fatalErrorCount += result.fatalErrorCount;
+ stat.warningCount += result.warningCount;
+ stat.fixableErrorCount += result.fixableErrorCount;
+ stat.fixableWarningCount += result.fixableWarningCount;
+ return stat;
+ }, {
+ errorCount: 0,
+ fatalErrorCount: 0,
+ warningCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0
+ });
+}
+
+/**
+ * Loads global ignore patterns from an ignore file (usually .eslintignore).
+ * @param {string} filePath The filename to load.
+ * @returns {ignore} A function encapsulating the ignore patterns.
+ * @throws {Error} If the file cannot be read.
+ * @private
+ */
+async function loadIgnoreFilePatterns(filePath) {
+ debug(`Loading ignore file: ${filePath}`);
+
+ try {
+ const ignoreFileText = await fs.readFile(filePath, { encoding: "utf8" });
+
+ return ignoreFileText
+ .split(/\r?\n/gu)
+ .filter(line => line.trim() !== "" && !line.startsWith("#"));
+
+ } catch (e) {
+ debug(`Error reading ignore file: ${filePath}`);
+ e.message = `Cannot read ignore file: ${filePath}\nError: ${e.message}`;
+ throw e;
+ }
+}
+
+/**
+ * Create rulesMeta object.
+ * @param {Map} rules a map of rules from which to generate the object.
+ * @returns {Object} metadata for all enabled rules.
+ */
+function createRulesMeta(rules) {
+ return Array.from(rules).reduce((retVal, [id, rule]) => {
+ retVal[id] = rule.meta;
+ return retVal;
+ }, {});
+}
+
+/** @type {WeakMap} */
+const usedDeprecatedRulesCache = new WeakMap();
+
+/**
+ * Create used deprecated rule list.
+ * @param {CLIEngine} eslint The CLIEngine instance.
+ * @param {string} maybeFilePath The absolute path to a lint target file or `""`.
+ * @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
+ */
+function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) {
+ const {
+ configs,
+ options: { cwd }
+ } = privateMembers.get(eslint);
+ const filePath = path.isAbsolute(maybeFilePath)
+ ? maybeFilePath
+ : path.join(cwd, "__placeholder__.js");
+ const config = configs.getConfig(filePath);
+
+ // Most files use the same config, so cache it.
+ if (config && !usedDeprecatedRulesCache.has(config)) {
+ const retv = [];
+
+ if (config.rules) {
+ for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
+ if (getRuleSeverity(ruleConf) === 0) {
+ continue;
+ }
+ const rule = getRuleFromConfig(ruleId, config);
+ const meta = rule && rule.meta;
+
+ if (meta && meta.deprecated) {
+ retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
+ }
+ }
+ }
+
+
+ usedDeprecatedRulesCache.set(config, Object.freeze(retv));
+ }
+
+ return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]);
+}
+
+/**
+ * Processes the linting results generated by a CLIEngine linting report to
+ * match the ESLint class's API.
+ * @param {CLIEngine} eslint The CLIEngine instance.
+ * @param {CLIEngineLintReport} report The CLIEngine linting report to process.
+ * @returns {LintResult[]} The processed linting results.
+ */
+function processLintReport(eslint, { results }) {
+ const descriptor = {
+ configurable: true,
+ enumerable: true,
+ get() {
+ return getOrFindUsedDeprecatedRules(eslint, this.filePath);
+ }
+ };
+
+ for (const result of results) {
+ Object.defineProperty(result, "usedDeprecatedRules", descriptor);
+ }
+
+ return results;
+}
+
+/**
+ * An Array.prototype.sort() compatible compare function to order results by their file path.
+ * @param {LintResult} a The first lint result.
+ * @param {LintResult} b The second lint result.
+ * @returns {number} An integer representing the order in which the two results should occur.
+ */
+function compareResultsByFilePath(a, b) {
+ if (a.filePath < b.filePath) {
+ return -1;
+ }
+
+ if (a.filePath > b.filePath) {
+ return 1;
+ }
+
+ return 0;
+}
+
+/**
+ * Searches from the current working directory up until finding the
+ * given flat config filename.
+ * @param {string} cwd The current working directory to search from.
+ * @returns {Promise} The filename if found or `null` if not.
+ */
+function findFlatConfigFile(cwd) {
+ return findUp(
+ FLAT_CONFIG_FILENAME,
+ { cwd }
+ );
+}
+
+/**
+ * Load the config array from the given filename.
+ * @param {string} filePath The filename to load from.
+ * @param {Object} options Options to help load the config file.
+ * @param {string} options.basePath The base path for the config array.
+ * @param {boolean} options.shouldIgnore Whether to honor ignore patterns.
+ * @returns {Promise} The config array loaded from the config file.
+ */
+async function loadFlatConfigFile(filePath, { basePath, shouldIgnore }) {
+ debug(`Loading config from ${filePath}`);
+
+ const fileURL = pathToFileURL(filePath);
+
+ debug(`Config file URL is ${fileURL}`);
+
+ const module = await import(fileURL);
+
+ return new FlatConfigArray(module.default, {
+ basePath,
+ shouldIgnore
+ });
+}
+
+/**
+ * Calculates the config array for this run based on inputs.
+ * @param {FlatESLint} eslint The instance to create the config array for.
+ * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
+ * @returns {FlatConfigArray} The config array for `eslint``.
+ */
+async function calculateConfigArray(eslint, {
+ cwd,
+ overrideConfig,
+ configFile,
+ ignore: shouldIgnore,
+ ignorePath,
+ ignorePatterns,
+ extensions
+}) {
+
+ // check for cached instance
+ const slots = privateMembers.get(eslint);
+
+ if (slots.configs) {
+ return slots.configs;
+ }
+
+ // determine where to load config file from
+ let configFilePath;
+ let basePath = cwd;
+
+ if (typeof configFile === "string") {
+ debug(`Override config file path is ${configFile}`);
+ configFilePath = path.resolve(cwd, configFile);
+ } else if (configFile !== false) {
+ debug("Searching for eslint.config.js");
+ configFilePath = await findFlatConfigFile(cwd);
+
+ if (!configFilePath) {
+ throw new Error("Could not find config file.");
+ }
+
+ basePath = path.resolve(path.dirname(configFilePath));
+ }
+
+ // load config array
+ let configs;
+
+ if (configFilePath) {
+ configs = await loadFlatConfigFile(configFilePath, {
+ basePath,
+ shouldIgnore
+ });
+ } else {
+ configs = new FlatConfigArray([], { basePath, shouldIgnore });
+ }
+
+ // add in any configured defaults
+ configs.push(...slots.defaultConfigs);
+
+ // if there are any extensions, create configs for them for easier matching
+ if (extensions && extensions.length) {
+ configs.push({
+ files: extensions.map(ext => `**/*${ext}`)
+ });
+ }
+
+ let allIgnorePatterns = [];
+ let ignoreFilePath;
+
+ // load ignore file if necessary
+ if (shouldIgnore) {
+ if (ignorePath) {
+ ignoreFilePath = path.resolve(cwd, ignorePath);
+ allIgnorePatterns = await loadIgnoreFilePatterns(ignoreFilePath);
+ } else {
+ ignoreFilePath = path.resolve(cwd, ".eslintignore");
+
+ // no error if .eslintignore doesn't exist`
+ if (fileExists(ignoreFilePath)) {
+ allIgnorePatterns = await loadIgnoreFilePatterns(ignoreFilePath);
+ }
+ }
+ }
+
+ // append command line ignore patterns
+ if (ignorePatterns) {
+ if (typeof ignorePatterns === "string") {
+ allIgnorePatterns.push(ignorePatterns);
+ } else {
+ allIgnorePatterns.push(...ignorePatterns);
+ }
+ }
+
+ /*
+ * If the config file basePath is different than the cwd, then
+ * the ignore patterns won't work correctly. Here, we adjust the
+ * ignore pattern to include the correct relative path. Patterns
+ * loaded from ignore files are always relative to the cwd, whereas
+ * the config file basePath can be an ancestor of the cwd.
+ */
+ if (basePath !== cwd && allIgnorePatterns.length) {
+
+ const relativeIgnorePath = path.relative(basePath, cwd);
+
+ allIgnorePatterns = allIgnorePatterns.map(pattern => {
+ const negated = pattern.startsWith("!");
+ const basePattern = negated ? pattern.slice(1) : pattern;
+
+ /*
+ * Ignore patterns are considered relative to a directory
+ * when the pattern contains a slash in a position other
+ * than the last character. If that's the case, we need to
+ * add the relative ignore path to the current pattern to
+ * get the correct behavior. Otherwise, no change is needed.
+ */
+ if (!basePattern.includes("/") || basePattern.endsWith("/")) {
+ return pattern;
+ }
+
+ return (negated ? "!" : "") +
+ path.posix.join(relativeIgnorePath, basePattern);
+ });
+ }
+
+ if (allIgnorePatterns.length) {
+
+ /*
+ * Ignore patterns are added to the end of the config array
+ * so they can override default ignores.
+ */
+ configs.push({
+ ignores: allIgnorePatterns.map(gitignoreToMinimatch)
+ });
+ }
+
+ if (overrideConfig) {
+ if (Array.isArray(overrideConfig)) {
+ configs.push(...overrideConfig);
+ } else {
+ configs.push(overrideConfig);
+ }
+ }
+
+ await configs.normalize();
+
+ // cache the config array for this instance
+ slots.configs = configs;
+
+ return configs;
+}
+
+/**
+ * Processes an source code using ESLint.
+ * @param {Object} config The config object.
+ * @param {string} config.text The source code to verify.
+ * @param {string} config.cwd The path to the current working directory.
+ * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses ``.
+ * @param {FlatConfigArray} config.configs The config.
+ * @param {boolean} config.fix If `true` then it does fix.
+ * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
+ * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments.
+ * @param {Linter} config.linter The linter instance to verify.
+ * @returns {LintResult} The result of linting.
+ * @private
+ */
+function verifyText({
+ text,
+ cwd,
+ filePath: providedFilePath,
+ configs,
+ fix,
+ allowInlineConfig,
+ reportUnusedDisableDirectives,
+ linter
+}) {
+ const filePath = providedFilePath || "";
+
+ debug(`Lint ${filePath}`);
+
+ /*
+ * Verify.
+ * `config.extractConfig(filePath)` requires an absolute path, but `linter`
+ * doesn't know CWD, so it gives `linter` an absolute path always.
+ */
+ const filePathToVerify = filePath === "" ? path.join(cwd, "__placeholder__.js") : filePath;
+ const { fixed, messages, output } = linter.verifyAndFix(
+ text,
+ configs,
+ {
+ allowInlineConfig,
+ filename: filePathToVerify,
+ fix,
+ reportUnusedDisableDirectives,
+
+ /**
+ * Check if the linter should adopt a given code block or not.
+ * @param {string} blockFilename The virtual filename of a code block.
+ * @returns {boolean} `true` if the linter should adopt the code block.
+ */
+ filterCodeBlock(blockFilename) {
+ return configs.isExplicitMatch(blockFilename);
+ }
+ }
+ );
+
+ // Tweak and return.
+ const result = {
+ filePath: filePath === "" ? filePath : path.resolve(filePath),
+ messages,
+ ...calculateStatsPerFile(messages)
+ };
+
+ if (fixed) {
+ result.output = output;
+ }
+
+ if (
+ result.errorCount + result.warningCount > 0 &&
+ typeof result.output === "undefined"
+ ) {
+ result.source = text;
+ }
+
+ return result;
+}
+
+/**
+ * Checks whether a message's rule type should be fixed.
+ * @param {LintMessage} message The message to check.
+ * @param {FlatConfig} config The config for the file that generated the message.
+ * @param {string[]} fixTypes An array of fix types to check.
+ * @returns {boolean} Whether the message should be fixed.
+ */
+function shouldMessageBeFixed(message, config, fixTypes) {
+ if (!message.ruleId) {
+ return fixTypes.has("directive");
+ }
+
+ const rule = message.ruleId && getRuleFromConfig(message.ruleId, config);
+
+ return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
+}
+
+/**
+ * Collect used deprecated rules.
+ * @param {Array} configs The configs to evaluate.
+ * @returns {IterableIterator} Used deprecated rules.
+ */
+function *iterateRuleDeprecationWarnings(configs) {
+ const processedRuleIds = new Set();
+
+ for (const config of configs) {
+ for (const [ruleId, ruleConfig] of Object.entries(config.rules)) {
+
+ // Skip if it was processed.
+ if (processedRuleIds.has(ruleId)) {
+ continue;
+ }
+ processedRuleIds.add(ruleId);
+
+ // Skip if it's not used.
+ if (!getRuleSeverity(ruleConfig)) {
+ continue;
+ }
+ const rule = getRuleFromConfig(ruleId, config);
+
+ // Skip if it's not deprecated.
+ if (!(rule && rule.meta && rule.meta.deprecated)) {
+ continue;
+ }
+
+ // This rule was used and deprecated.
+ yield {
+ ruleId,
+ replacedBy: rule.meta.replacedBy || []
+ };
+ }
+ }
+}
+
+//-----------------------------------------------------------------------------
+// Main API
+//-----------------------------------------------------------------------------
+
+/**
+ * Primary Node.js API for ESLint.
+ */
+class FlatESLint {
+
+ /**
+ * Creates a new instance of the main ESLint API.
+ * @param {FlatESLintOptions} options The options for this instance.
+ */
+ constructor(options = {}) {
+
+ const defaultConfigs = [];
+ const processedOptions = processOptions(options);
+ const linter = new Linter({
+ cwd: processedOptions.cwd,
+ configType: "flat"
+ });
+
+ privateMembers.set(this, {
+ options: processedOptions,
+ linter,
+ defaultConfigs,
+ defaultIgnores: () => false,
+ configs: null
+ });
+
+ /**
+ * If additional plugins are passed in, add that to the default
+ * configs for this instance.
+ */
+ if (options.plugins) {
+
+ const plugins = {};
+
+ for (const [pluginName, plugin] of Object.entries(options.plugins)) {
+ plugins[naming.getShorthandName(pluginName, "eslint-plugin")] = plugin;
+ }
+
+ defaultConfigs.push({
+ plugins
+ });
+ }
+
+ }
+
+ /**
+ * The version text.
+ * @type {string}
+ */
+ static get version() {
+ return version;
+ }
+
+ /**
+ * Outputs fixes from the given results to files.
+ * @param {LintResult[]} results The lint results.
+ * @returns {Promise} Returns a promise that is used to track side effects.
+ */
+ static async outputFixes(results) {
+ if (!Array.isArray(results)) {
+ throw new Error("'results' must be an array");
+ }
+
+ await Promise.all(
+ results
+ .filter(result => {
+ if (typeof result !== "object" || result === null) {
+ throw new Error("'results' must include only objects");
+ }
+ return (
+ typeof result.output === "string" &&
+ path.isAbsolute(result.filePath)
+ );
+ })
+ .map(r => fs.writeFile(r.filePath, r.output))
+ );
+ }
+
+ /**
+ * Returns results that only contains errors.
+ * @param {LintResult[]} results The results to filter.
+ * @returns {LintResult[]} The filtered results.
+ */
+ static getErrorResults(results) {
+ const filtered = [];
+
+ results.forEach(result => {
+ const filteredMessages = result.messages.filter(isErrorMessage);
+
+ if (filteredMessages.length > 0) {
+ filtered.push({
+ ...result,
+ messages: filteredMessages,
+ errorCount: filteredMessages.length,
+ warningCount: 0,
+ fixableErrorCount: result.fixableErrorCount,
+ fixableWarningCount: 0
+ });
+ }
+ });
+
+ return filtered;
+ }
+
+ /**
+ * Returns meta objects for each rule represented in the lint results.
+ * @param {LintResult[]} results The results to fetch rules meta for.
+ * @returns {Object} A mapping of ruleIds to rule meta objects.
+ * @throws {TypeError} When the results object wasn't created from this ESLint instance.
+ * @throws {TypeError} When a plugin or rule is missing.
+ */
+ getRulesMetaForResults(results) {
+
+ const resultRules = new Map();
+
+ // short-circuit simple case
+ if (results.length === 0) {
+ return resultRules;
+ }
+
+ const { configs } = privateMembers.get(this);
+
+ /*
+ * We can only accurately return rules meta information for linting results if the
+ * results were created by this instance. Otherwise, the necessary rules data is
+ * not available. So if the config array doesn't already exist, just throw an error
+ * to let the user know we can't do anything here.
+ */
+ if (!configs) {
+ throw new TypeError("Results object was not created from this ESLint instance.");
+ }
+
+ for (const result of results) {
+
+ /*
+ * Normalize filename for .
+ */
+ const filePath = result.filePath === ""
+ ? "__placeholder__.js" : result.filePath;
+
+ /*
+ * All of the plugin and rule information is contained within the
+ * calculated config for the given file.
+ */
+ const config = configs.getConfig(filePath);
+
+ for (const { ruleId } of result.messages) {
+ const rule = getRuleFromConfig(ruleId, config);
+
+ // ensure the rule exists exists
+ if (!rule) {
+ throw new TypeError(`Could not find the rule "${ruleId}".`);
+ }
+
+ resultRules.set(ruleId, rule);
+ }
+ }
+
+ return createRulesMeta(resultRules);
+ }
+
+ /**
+ * Executes the current configuration on an array of file and directory names.
+ * @param {string|string[]} patterns An array of file and directory names.
+ * @returns {Promise} The results of linting the file patterns given.
+ */
+ async lintFiles(patterns) {
+ if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
+ throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
+ }
+
+ const {
+ cacheFilePath,
+ lintResultCache,
+ linter,
+ options: eslintOptions
+ } = privateMembers.get(this);
+ const configs = await calculateConfigArray(this, eslintOptions);
+ const {
+ allowInlineConfig,
+ cache,
+ cwd,
+ fix,
+ fixTypes,
+ reportUnusedDisableDirectives,
+ extensions,
+ globInputPaths
+ } = eslintOptions;
+ const startTime = Date.now();
+ const usedConfigs = [];
+ const fixTypesSet = fixTypes ? new Set(fixTypes) : null;
+
+ // Delete cache file; should this be done here?
+ if (!cache && cacheFilePath) {
+ try {
+ await fs.unlink(cacheFilePath);
+ } catch (error) {
+ const errorCode = error && error.code;
+
+ // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
+ if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !(await fs.exists(cacheFilePath)))) {
+ throw error;
+ }
+ }
+ }
+
+ const filePaths = await findFiles({
+ patterns: typeof patterns === "string" ? [patterns] : patterns,
+ cwd,
+ extensions,
+ globInputPaths,
+ configs
+ });
+
+ debug(`${filePaths.length} files found in: ${Date.now() - startTime}ms`);
+
+ /*
+ * Because we need to process multiple files, including reading from disk,
+ * it is most efficient to start by reading each file via promises so that
+ * they can be done in parallel. Then, we can lint the returned text. This
+ * ensures we are waiting the minimum amount of time in between lints.
+ */
+ const results = await Promise.all(
+
+ filePaths.map(({ filePath, ignored }) => {
+
+ /*
+ * If a filename was entered that matches an ignore
+ * pattern, then notify the user.
+ */
+ if (ignored) {
+ return createIgnoreResult(filePath, cwd);
+ }
+
+ const config = configs.getConfig(filePath);
+
+ /*
+ * Sometimes a file found through a glob pattern will
+ * be ignored. In this case, `config` will be undefined
+ * and we just silently ignore the file.
+ */
+ if (!config) {
+ return void 0;
+ }
+
+ /*
+ * Store used configs for:
+ * - this method uses to collect used deprecated rules.
+ * - `--fix-type` option uses to get the loaded rule's meta data.
+ */
+ if (!usedConfigs.includes(config)) {
+ usedConfigs.push(config);
+ }
+
+ // Skip if there is cached result.
+ if (lintResultCache) {
+ const cachedResult =
+ lintResultCache.getCachedLintResults(filePath, config);
+
+ if (cachedResult) {
+ const hadMessages =
+ cachedResult.messages &&
+ cachedResult.messages.length > 0;
+
+ if (hadMessages && fix) {
+ debug(`Reprocessing cached file to allow autofix: ${filePath}`);
+ } else {
+ debug(`Skipping file since it hasn't changed: ${filePath}`);
+ return cachedResult;
+ }
+ }
+ }
+
+
+ // set up fixer for fixtypes if necessary
+ let fixer = fix;
+
+ if (fix && fixTypesSet) {
+
+ // save original value of options.fix in case it's a function
+ const originalFix = (typeof fix === "function")
+ ? fix : () => true;
+
+ fixer = message => shouldMessageBeFixed(message, config, fixTypesSet) && originalFix(message);
+ }
+
+ return fs.readFile(filePath, "utf8")
+ .then(text => {
+
+ // do the linting
+ const result = verifyText({
+ text,
+ filePath,
+ configs,
+ cwd,
+ fix: fixer,
+ allowInlineConfig,
+ reportUnusedDisableDirectives,
+ linter
+ });
+
+ /*
+ * Store the lint result in the LintResultCache.
+ * NOTE: The LintResultCache will remove the file source and any
+ * other properties that are difficult to serialize, and will
+ * hydrate those properties back in on future lint runs.
+ */
+ if (lintResultCache) {
+ lintResultCache.setCachedLintResults(filePath, config, result);
+ }
+
+ return result;
+ });
+
+ })
+ );
+
+ // Persist the cache to disk.
+ if (lintResultCache) {
+ lintResultCache.reconcile();
+ }
+
+ let usedDeprecatedRules;
+ const finalResults = results.filter(result => !!result);
+
+ return processLintReport(this, {
+ results: finalResults,
+ ...calculateStatsPerRun(finalResults),
+
+ // Initialize it lazily because CLI and `ESLint` API don't use it.
+ get usedDeprecatedRules() {
+ if (!usedDeprecatedRules) {
+ usedDeprecatedRules = Array.from(
+ iterateRuleDeprecationWarnings(usedConfigs)
+ );
+ }
+ return usedDeprecatedRules;
+ }
+ });
+ }
+
+ /**
+ * Executes the current configuration on text.
+ * @param {string} code A string of JavaScript code to lint.
+ * @param {Object} [options] The options.
+ * @param {string} [options.filePath] The path to the file of the source code.
+ * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
+ * @returns {Promise} The results of linting the string of code given.
+ */
+ async lintText(code, options = {}) {
+
+ // Parameter validation
+
+ if (typeof code !== "string") {
+ throw new Error("'code' must be a string");
+ }
+
+ if (typeof options !== "object") {
+ throw new Error("'options' must be an object, null, or undefined");
+ }
+
+ // Options validation
+
+ const {
+ filePath,
+ warnIgnored = false,
+ ...unknownOptions
+ } = options || {};
+
+ const unknownOptionKeys = Object.keys(unknownOptions);
+
+ if (unknownOptionKeys.length > 0) {
+ throw new Error(`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`);
+ }
+
+ if (filePath !== void 0 && !isNonEmptyString(filePath)) {
+ throw new Error("'options.filePath' must be a non-empty string or undefined");
+ }
+
+ if (typeof warnIgnored !== "boolean") {
+ throw new Error("'options.warnIgnored' must be a boolean or undefined");
+ }
+
+ // Now we can get down to linting
+
+ const {
+ linter,
+ options: eslintOptions
+ } = privateMembers.get(this);
+ const configs = await calculateConfigArray(this, eslintOptions);
+ const {
+ allowInlineConfig,
+ cwd,
+ fix,
+ reportUnusedDisableDirectives
+ } = eslintOptions;
+ const results = [];
+ const startTime = Date.now();
+ const resolvedFilename = path.resolve(cwd, filePath || "__placeholder__.js");
+ let config;
+
+ // Clear the last used config arrays.
+ if (resolvedFilename && await this.isPathIgnored(resolvedFilename)) {
+ if (warnIgnored) {
+ results.push(createIgnoreResult(resolvedFilename, cwd));
+ }
+ } else {
+
+ // TODO: Needed?
+ config = configs.getConfig(resolvedFilename);
+
+ // Do lint.
+ results.push(verifyText({
+ text: code,
+ filePath: resolvedFilename.endsWith("__placeholder__.js") ? "" : resolvedFilename,
+ configs,
+ cwd,
+ fix,
+ allowInlineConfig,
+ reportUnusedDisableDirectives,
+ linter
+ }));
+ }
+
+ debug(`Linting complete in: ${Date.now() - startTime}ms`);
+ let usedDeprecatedRules;
+
+ return processLintReport(this, {
+ results,
+ ...calculateStatsPerRun(results),
+
+ // Initialize it lazily because CLI and `ESLint` API don't use it.
+ get usedDeprecatedRules() {
+ if (!usedDeprecatedRules) {
+ usedDeprecatedRules = Array.from(
+ iterateRuleDeprecationWarnings(config)
+ );
+ }
+ return usedDeprecatedRules;
+ }
+ });
+
+ }
+
+ /**
+ * Returns the formatter representing the given formatter name.
+ * @param {string} [name] The name of the formatter to load.
+ * The following values are allowed:
+ * - `undefined` ... Load `stylish` builtin formatter.
+ * - A builtin formatter name ... Load the builtin formatter.
+ * - A thirdparty formatter name:
+ * - `foo` → `eslint-formatter-foo`
+ * - `@foo` → `@foo/eslint-formatter`
+ * - `@foo/bar` → `@foo/eslint-formatter-bar`
+ * - A file path ... Load the file.
+ * @returns {Promise} A promise resolving to the formatter object.
+ * This promise will be rejected if the given formatter was not found or not
+ * a function.
+ */
+ async loadFormatter(name = "stylish") {
+ if (typeof name !== "string") {
+ throw new Error("'name' must be a string");
+ }
+
+ // replace \ with / for Windows compatibility
+ const normalizedFormatName = name.replace(/\\/gu, "/");
+ const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
+
+ // grab our options
+ const { cwd } = privateMembers.get(this).options;
+
+
+ let formatterPath;
+
+ // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
+ if (!namespace && normalizedFormatName.includes("/")) {
+ formatterPath = path.resolve(cwd, normalizedFormatName);
+ } else {
+ try {
+ const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
+
+ // TODO: This is pretty dirty...would be nice to clean up at some point.
+ formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js"));
+ } catch {
+ formatterPath = path.resolve(__dirname, "../", "cli-engine", "formatters", `${normalizedFormatName}.js`);
+ }
+ }
+
+ let formatter;
+
+ try {
+ formatter = (await import(pathToFileURL(formatterPath))).default;
+ } catch (ex) {
+
+ // check for formatters that have been removed
+ if (removedFormatters.has(name)) {
+ ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``;
+ } else {
+ ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
+ }
+
+ throw ex;
+ }
+
+
+ if (typeof formatter !== "function") {
+ throw new TypeError(`Formatter must be a function, but got a ${typeof formatter}.`);
+ }
+
+ const eslint = this;
+
+ return {
+
+ /**
+ * The main formatter method.
+ * @param {LintResults[]} results The lint results to format.
+ * @returns {string} The formatted lint results.
+ */
+ format(results) {
+ let rulesMeta = null;
+
+ results.sort(compareResultsByFilePath);
+
+ return formatter(results, {
+ get rulesMeta() {
+ if (!rulesMeta) {
+ rulesMeta = eslint.getRulesMetaForResults(results);
+ }
+
+ return rulesMeta;
+ }
+ });
+ }
+ };
+ }
+
+ /**
+ * Returns a configuration object for the given file based on the CLI options.
+ * This is the same logic used by the ESLint CLI executable to determine
+ * configuration for each file it processes.
+ * @param {string} filePath The path of the file to retrieve a config object for.
+ * @returns {Promise} A configuration object for the file
+ * or `undefined` if there is no configuration data for the object.
+ */
+ async calculateConfigForFile(filePath) {
+ if (!isNonEmptyString(filePath)) {
+ throw new Error("'filePath' must be a non-empty string");
+ }
+ const options = privateMembers.get(this).options;
+ const absolutePath = path.resolve(options.cwd, filePath);
+ const configs = await calculateConfigArray(this, options);
+
+ return configs.getConfig(absolutePath);
+ }
+
+ /**
+ * Checks if a given path is ignored by ESLint.
+ * @param {string} filePath The path of the file to check.
+ * @returns {Promise} Whether or not the given path is ignored.
+ */
+ async isPathIgnored(filePath) {
+ const config = await this.calculateConfigForFile(filePath);
+
+ return config === void 0;
+ }
+}
+
+//------------------------------------------------------------------------------
+// Public Interface
+//------------------------------------------------------------------------------
+
+module.exports = {
+ FlatESLint
+};
diff --git a/lib/eslint/index.js b/lib/eslint/index.js
index c9185ee0eba..017b768ecd0 100644
--- a/lib/eslint/index.js
+++ b/lib/eslint/index.js
@@ -1,7 +1,9 @@
"use strict";
const { ESLint } = require("./eslint");
+const { FlatESLint } = require("./flat-eslint");
module.exports = {
- ESLint
+ ESLint,
+ FlatESLint
};
diff --git a/lib/linter/linter.js b/lib/linter/linter.js
index 5304a612a59..a29ce923792 100644
--- a/lib/linter/linter.js
+++ b/lib/linter/linter.js
@@ -1101,7 +1101,7 @@ function runRules(sourceCode, configuredRules, ruleMapper, parserName, languageO
)
);
- const ruleListeners = createRuleListeners(rule, ruleContext);
+ const ruleListeners = timing.enabled ? timing.time(ruleId, createRuleListeners)(rule, ruleContext) : createRuleListeners(rule, ruleContext);
/**
* Include `ruleId` in error logs
@@ -1119,6 +1119,10 @@ function runRules(sourceCode, configuredRules, ruleMapper, parserName, languageO
};
}
+ if (typeof ruleListeners === "undefined" || ruleListeners === null) {
+ throw new Error(`The create() function for rule '${ruleId}' did not return an object.`);
+ }
+
// add all the selectors from the rule as listeners
Object.keys(ruleListeners).forEach(selector => {
const ruleListener = timing.enabled
@@ -1506,7 +1510,31 @@ class Linter {
options.filterCodeBlock ||
(blockFilename => blockFilename.endsWith(".js"));
const originalExtname = path.extname(filename);
- const messageLists = preprocess(text, filenameToExpose).map((block, i) => {
+
+ let blocks;
+
+ try {
+ blocks = preprocess(text, filenameToExpose);
+ } catch (ex) {
+
+ // If the message includes a leading line number, strip it:
+ const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
+
+ debug("%s\n%s", message, ex.stack);
+
+ return [
+ {
+ ruleId: null,
+ fatal: true,
+ severity: 2,
+ message,
+ line: ex.lineNumber,
+ column: ex.column
+ }
+ ];
+ }
+
+ const messageLists = blocks.map((block, i) => {
debug("A code block was found: %o", block.filename || "(unnamed)");
// Keep the legacy behavior.
@@ -1580,6 +1608,11 @@ class Linter {
...languageOptions.globals
};
+ // double check that there is a parser to avoid mysterious error messages
+ if (!languageOptions.parser) {
+ throw new TypeError(`No parser specified for ${options.filename}`);
+ }
+
// Espree expects this information to be passed in
if (isEspree(languageOptions.parser)) {
const parserOptions = languageOptions.parserOptions;
@@ -1742,12 +1775,24 @@ class Linter {
debug("With flat config: %s", options.filename);
// we need a filename to match configs against
- const filename = options.filename || "";
+ const filename = options.filename || "__placeholder__.js";
// Store the config array in order to get plugin envs and rules later.
internalSlotsMap.get(this).lastConfigArray = configArray;
const config = configArray.getConfig(filename);
+ if (!config) {
+ return [
+ {
+ ruleId: null,
+ severity: 1,
+ message: `No matching configuration found for ${filename}.`,
+ line: 0,
+ column: 0
+ }
+ ];
+ }
+
// Verify.
if (config.processor) {
debug("Apply the processor: %o", config.processor);
@@ -1784,13 +1829,36 @@ class Linter {
const physicalFilename = options.physicalFilename || filenameToExpose;
const text = ensureText(textOrSourceCode);
const preprocess = options.preprocess || (rawText => [rawText]);
-
const postprocess = options.postprocess || (messagesList => messagesList.flat());
const filterCodeBlock =
options.filterCodeBlock ||
(blockFilename => blockFilename.endsWith(".js"));
const originalExtname = path.extname(filename);
- const messageLists = preprocess(text, filenameToExpose).map((block, i) => {
+
+ let blocks;
+
+ try {
+ blocks = preprocess(text, filenameToExpose);
+ } catch (ex) {
+
+ // If the message includes a leading line number, strip it:
+ const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
+
+ debug("%s\n%s", message, ex.stack);
+
+ return [
+ {
+ ruleId: null,
+ fatal: true,
+ severity: 2,
+ message,
+ line: ex.lineNumber,
+ column: ex.column
+ }
+ ];
+ }
+
+ const messageLists = blocks.map((block, i) => {
debug("A code block was found: %o", block.filename || "(unnamed)");
// Keep the legacy behavior.
diff --git a/lib/linter/timing.js b/lib/linter/timing.js
index c9ab01ec649..914cbf05591 100644
--- a/lib/linter/timing.js
+++ b/lib/linter/timing.js
@@ -138,10 +138,11 @@ module.exports = (function() {
return function(...args) {
let t = process.hrtime();
+ const result = fn(...args);
- fn(...args);
t = process.hrtime(t);
data[key] += t[0] * 1e3 + t[1] / 1e6;
+ return result;
};
}
diff --git a/lib/rule-tester/flat-rule-tester.js b/lib/rule-tester/flat-rule-tester.js
index b829484149a..19bd8e354f6 100644
--- a/lib/rule-tester/flat-rule-tester.js
+++ b/lib/rule-tester/flat-rule-tester.js
@@ -480,51 +480,54 @@ class FlatRuleTester {
].concat(scenarioErrors).join("\n"));
}
- const baseConfig = {
- plugins: {
-
- // copy root plugin over
- "@": {
-
- /*
- * Parsers are wrapped to detect more errors, so this needs
- * to be a new object for each call to run(), otherwise the
- * parsers will be wrapped multiple times.
- */
- parsers: {
- ...defaultConfig[0].plugins["@"].parsers
- },
+ const baseConfig = [
+ {
+ plugins: {
- /*
- * The rules key on the default plugin is a proxy to lazy-load
- * just the rules that are needed. So, don't create a new object
- * here, just use the default one to keep that performance
- * enhancement.
- */
- rules: defaultConfig[0].plugins["@"].rules
- },
- "rule-to-test": {
- rules: {
- [ruleName]: Object.assign({}, rule, {
+ // copy root plugin over
+ "@": {
+
+ /*
+ * Parsers are wrapped to detect more errors, so this needs
+ * to be a new object for each call to run(), otherwise the
+ * parsers will be wrapped multiple times.
+ */
+ parsers: {
+ ...defaultConfig[0].plugins["@"].parsers
+ },
+
+ /*
+ * The rules key on the default plugin is a proxy to lazy-load
+ * just the rules that are needed. So, don't create a new object
+ * here, just use the default one to keep that performance
+ * enhancement.
+ */
+ rules: defaultConfig[0].plugins["@"].rules
+ },
+ "rule-to-test": {
+ rules: {
+ [ruleName]: Object.assign({}, rule, {
- // Create a wrapper rule that freezes the `context` properties.
- create(context) {
- freezeDeeply(context.options);
- freezeDeeply(context.settings);
- freezeDeeply(context.parserOptions);
+ // Create a wrapper rule that freezes the `context` properties.
+ create(context) {
+ freezeDeeply(context.options);
+ freezeDeeply(context.settings);
+ freezeDeeply(context.parserOptions);
- // freezeDeeply(context.languageOptions);
+ // freezeDeeply(context.languageOptions);
- return (typeof rule === "function" ? rule : rule.create)(context);
- }
- })
+ return (typeof rule === "function" ? rule : rule.create)(context);
+ }
+ })
+ }
}
+ },
+ languageOptions: {
+ ...defaultConfig[0].languageOptions
}
},
- languageOptions: {
- ...defaultConfig[0].languageOptions
- }
- };
+ ...defaultConfig.slice(1)
+ ];
/**
* Run the rule for the given item
diff --git a/lib/rule-tester/rule-tester.js b/lib/rule-tester/rule-tester.js
index 398f210135b..fe0e468916b 100644
--- a/lib/rule-tester/rule-tester.js
+++ b/lib/rule-tester/rule-tester.js
@@ -305,6 +305,36 @@ function getCommentsDeprecation() {
);
}
+/**
+ * Emit a deprecation warning if function-style format is being used.
+ * @param {string} ruleName Name of the rule.
+ * @returns {void}
+ */
+function emitLegacyRuleAPIWarning(ruleName) {
+ if (!emitLegacyRuleAPIWarning[`warned-${ruleName}`]) {
+ emitLegacyRuleAPIWarning[`warned-${ruleName}`] = true;
+ process.emitWarning(
+ `"${ruleName}" rule is using the deprecated function-style format and will stop working in ESLint v9. Please use object-style format: https://eslint.org/docs/developer-guide/working-with-rules`,
+ "DeprecationWarning"
+ );
+ }
+}
+
+/**
+ * Emit a deprecation warning if rule has options but is missing the "meta.schema" property
+ * @param {string} ruleName Name of the rule.
+ * @returns {void}
+ */
+function emitMissingSchemaWarning(ruleName) {
+ if (!emitMissingSchemaWarning[`warned-${ruleName}`]) {
+ emitMissingSchemaWarning[`warned-${ruleName}`] = true;
+ process.emitWarning(
+ `"${ruleName}" rule has options but is missing the "meta.schema" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/developer-guide/working-with-rules#options-schemas`,
+ "DeprecationWarning"
+ );
+ }
+}
+
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
@@ -521,6 +551,9 @@ class RuleTester {
].concat(scenarioErrors).join("\n"));
}
+ if (typeof rule === "function") {
+ emitLegacyRuleAPIWarning(ruleName);
+ }
linter.defineRule(ruleName, Object.assign({}, rule, {
@@ -578,6 +611,15 @@ class RuleTester {
if (hasOwnProperty(item, "options")) {
assert(Array.isArray(item.options), "options must be an array");
+ if (
+ item.options.length > 0 &&
+ typeof rule === "object" &&
+ (
+ !rule.meta || (rule.meta && (typeof rule.meta.schema === "undefined" || rule.meta.schema === null))
+ )
+ ) {
+ emitMissingSchemaWarning(ruleName);
+ }
config.rules[ruleName] = [1].concat(item.options);
} else {
config.rules[ruleName] = 1;
diff --git a/lib/rules/accessor-pairs.js b/lib/rules/accessor-pairs.js
index 33887affef2..112d0ddb8c1 100644
--- a/lib/rules/accessor-pairs.js
+++ b/lib/rules/accessor-pairs.js
@@ -140,7 +140,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce getter and setter pairs in objects and classes",
+ description: "Enforce getter and setter pairs in objects and classes",
recommended: false,
url: "https://eslint.org/docs/rules/accessor-pairs"
},
diff --git a/lib/rules/array-bracket-newline.js b/lib/rules/array-bracket-newline.js
index 0beb138c4e2..deeae818fb5 100644
--- a/lib/rules/array-bracket-newline.js
+++ b/lib/rules/array-bracket-newline.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce linebreaks after opening and before closing array brackets",
+ description: "Enforce linebreaks after opening and before closing array brackets",
recommended: false,
url: "https://eslint.org/docs/rules/array-bracket-newline"
},
diff --git a/lib/rules/array-bracket-spacing.js b/lib/rules/array-bracket-spacing.js
index e4912ec17a1..5e7cea9ba58 100644
--- a/lib/rules/array-bracket-spacing.js
+++ b/lib/rules/array-bracket-spacing.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing inside array brackets",
+ description: "Enforce consistent spacing inside array brackets",
recommended: false,
url: "https://eslint.org/docs/rules/array-bracket-spacing"
},
diff --git a/lib/rules/array-callback-return.js b/lib/rules/array-callback-return.js
index fba414c1ef4..eb5aa474b27 100644
--- a/lib/rules/array-callback-return.js
+++ b/lib/rules/array-callback-return.js
@@ -139,7 +139,7 @@ module.exports = {
type: "problem",
docs: {
- description: "enforce `return` statements in callbacks of array methods",
+ description: "Enforce `return` statements in callbacks of array methods",
recommended: false,
url: "https://eslint.org/docs/rules/array-callback-return"
},
diff --git a/lib/rules/array-element-newline.js b/lib/rules/array-element-newline.js
index 77f5fc9e9ce..c762755bd83 100644
--- a/lib/rules/array-element-newline.js
+++ b/lib/rules/array-element-newline.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce line breaks after each array element",
+ description: "Enforce line breaks after each array element",
recommended: false,
url: "https://eslint.org/docs/rules/array-element-newline"
},
diff --git a/lib/rules/arrow-body-style.js b/lib/rules/arrow-body-style.js
index 7a141b0d788..8bb9e8c4ffa 100644
--- a/lib/rules/arrow-body-style.js
+++ b/lib/rules/arrow-body-style.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require braces around arrow function bodies",
+ description: "Require braces around arrow function bodies",
recommended: false,
url: "https://eslint.org/docs/rules/arrow-body-style"
},
diff --git a/lib/rules/arrow-parens.js b/lib/rules/arrow-parens.js
index 779ab6fe9c9..05012fc37b7 100644
--- a/lib/rules/arrow-parens.js
+++ b/lib/rules/arrow-parens.js
@@ -33,7 +33,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require parentheses around arrow function arguments",
+ description: "Require parentheses around arrow function arguments",
recommended: false,
url: "https://eslint.org/docs/rules/arrow-parens"
},
diff --git a/lib/rules/arrow-spacing.js b/lib/rules/arrow-spacing.js
index 9fdcdd58ba7..2dcc175da06 100644
--- a/lib/rules/arrow-spacing.js
+++ b/lib/rules/arrow-spacing.js
@@ -20,7 +20,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing before and after the arrow in arrow functions",
+ description: "Enforce consistent spacing before and after the arrow in arrow functions",
recommended: false,
url: "https://eslint.org/docs/rules/arrow-spacing"
},
diff --git a/lib/rules/block-scoped-var.js b/lib/rules/block-scoped-var.js
index 3a277863ef2..731d06d0f3b 100644
--- a/lib/rules/block-scoped-var.js
+++ b/lib/rules/block-scoped-var.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce the use of variables within the scope they are defined",
+ description: "Enforce the use of variables within the scope they are defined",
recommended: false,
url: "https://eslint.org/docs/rules/block-scoped-var"
},
diff --git a/lib/rules/block-spacing.js b/lib/rules/block-spacing.js
index 53303a9b004..9fbf1594c47 100644
--- a/lib/rules/block-spacing.js
+++ b/lib/rules/block-spacing.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow or enforce spaces inside of blocks after opening block and before closing block",
+ description: "Disallow or enforce spaces inside of blocks after opening block and before closing block",
recommended: false,
url: "https://eslint.org/docs/rules/block-spacing"
},
diff --git a/lib/rules/brace-style.js b/lib/rules/brace-style.js
index f4adb9490eb..52d89201b9e 100644
--- a/lib/rules/brace-style.js
+++ b/lib/rules/brace-style.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent brace style for blocks",
+ description: "Enforce consistent brace style for blocks",
recommended: false,
url: "https://eslint.org/docs/rules/brace-style"
},
diff --git a/lib/rules/callback-return.js b/lib/rules/callback-return.js
index 34b74631f0c..fe5b649b582 100644
--- a/lib/rules/callback-return.js
+++ b/lib/rules/callback-return.js
@@ -19,7 +19,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `return` statements after callbacks",
+ description: "Require `return` statements after callbacks",
recommended: false,
url: "https://eslint.org/docs/rules/callback-return"
},
diff --git a/lib/rules/camelcase.js b/lib/rules/camelcase.js
index e4761466902..ee1b6bf598d 100644
--- a/lib/rules/camelcase.js
+++ b/lib/rules/camelcase.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce camelcase naming convention",
+ description: "Enforce camelcase naming convention",
recommended: false,
url: "https://eslint.org/docs/rules/camelcase"
},
diff --git a/lib/rules/capitalized-comments.js b/lib/rules/capitalized-comments.js
index dffe9565003..ba798d42858 100644
--- a/lib/rules/capitalized-comments.js
+++ b/lib/rules/capitalized-comments.js
@@ -105,7 +105,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce or disallow capitalization of the first letter of a comment",
+ description: "Enforce or disallow capitalization of the first letter of a comment",
recommended: false,
url: "https://eslint.org/docs/rules/capitalized-comments"
},
diff --git a/lib/rules/class-methods-use-this.js b/lib/rules/class-methods-use-this.js
index 1af6084ed8b..05a915867c3 100644
--- a/lib/rules/class-methods-use-this.js
+++ b/lib/rules/class-methods-use-this.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce that class methods utilize `this`",
+ description: "Enforce that class methods utilize `this`",
recommended: false,
url: "https://eslint.org/docs/rules/class-methods-use-this"
},
diff --git a/lib/rules/comma-dangle.js b/lib/rules/comma-dangle.js
index 063e1cb697f..9518da90e9e 100644
--- a/lib/rules/comma-dangle.js
+++ b/lib/rules/comma-dangle.js
@@ -76,7 +76,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow trailing commas",
+ description: "Require or disallow trailing commas",
recommended: false,
url: "https://eslint.org/docs/rules/comma-dangle"
},
diff --git a/lib/rules/comma-spacing.js b/lib/rules/comma-spacing.js
index 23a51752814..76d5dc46b9c 100644
--- a/lib/rules/comma-spacing.js
+++ b/lib/rules/comma-spacing.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing before and after commas",
+ description: "Enforce consistent spacing before and after commas",
recommended: false,
url: "https://eslint.org/docs/rules/comma-spacing"
},
@@ -103,38 +103,6 @@ module.exports = {
});
}
- /**
- * Validates the spacing around a comma token.
- * @param {Object} tokens The tokens to be validated.
- * @param {Token} tokens.comma The token representing the comma.
- * @param {Token} [tokens.left] The last token before the comma.
- * @param {Token} [tokens.right] The first token after the comma.
- * @param {Token|ASTNode} reportItem The item to use when reporting an error.
- * @returns {void}
- * @private
- */
- function validateCommaItemSpacing(tokens, reportItem) {
- if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) &&
- (options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma))
- ) {
- report(reportItem, "before", tokens.left);
- }
-
- if (tokens.right && astUtils.isClosingParenToken(tokens.right)) {
- return;
- }
-
- if (tokens.right && !options.after && tokens.right.type === "Line") {
- return;
- }
-
- if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) &&
- (options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right))
- ) {
- report(reportItem, "after", tokens.right);
- }
- }
-
/**
* Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list.
* @param {ASTNode} node An ArrayExpression or ArrayPattern node.
@@ -172,18 +140,44 @@ module.exports = {
return;
}
- if (token && token.type === "JSXText") {
- return;
- }
-
const previousToken = tokensAndComments[i - 1];
const nextToken = tokensAndComments[i + 1];
- validateCommaItemSpacing({
- comma: token,
- left: astUtils.isCommaToken(previousToken) || commaTokensToIgnore.includes(token) ? null : previousToken,
- right: astUtils.isCommaToken(nextToken) ? null : nextToken
- }, token);
+ if (
+ previousToken &&
+ !astUtils.isCommaToken(previousToken) && // ignore spacing between two commas
+
+ /*
+ * `commaTokensToIgnore` are ending commas of `null` elements (array holes/elisions).
+ * In addition to spacing between two commas, this can also ignore:
+ *
+ * - Spacing after `[` (controlled by array-bracket-spacing)
+ * Example: [ , ]
+ * ^
+ * - Spacing after a comment (for backwards compatibility, this was possibly unintentional)
+ * Example: [a, /* * / ,]
+ * ^
+ */
+ !commaTokensToIgnore.includes(token) &&
+
+ astUtils.isTokenOnSameLine(previousToken, token) &&
+ options.before !== sourceCode.isSpaceBetweenTokens(previousToken, token)
+ ) {
+ report(token, "before", previousToken);
+ }
+
+ if (
+ nextToken &&
+ !astUtils.isCommaToken(nextToken) && // ignore spacing between two commas
+ !astUtils.isClosingParenToken(nextToken) && // controlled by space-in-parens
+ !astUtils.isClosingBracketToken(nextToken) && // controlled by array-bracket-spacing
+ !astUtils.isClosingBraceToken(nextToken) && // controlled by object-curly-spacing
+ !(!options.after && nextToken.type === "Line") && // special case, allow space before line comment
+ astUtils.isTokenOnSameLine(token, nextToken) &&
+ options.after !== sourceCode.isSpaceBetweenTokens(token, nextToken)
+ ) {
+ report(token, "after", nextToken);
+ }
});
},
ArrayExpression: addNullElementsToIgnoreList,
diff --git a/lib/rules/comma-style.js b/lib/rules/comma-style.js
index cbcbe3ae15b..4969f59d7ef 100644
--- a/lib/rules/comma-style.js
+++ b/lib/rules/comma-style.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent comma style",
+ description: "Enforce consistent comma style",
recommended: false,
url: "https://eslint.org/docs/rules/comma-style"
},
diff --git a/lib/rules/complexity.js b/lib/rules/complexity.js
index b2355556af9..541d3a9bb9a 100644
--- a/lib/rules/complexity.js
+++ b/lib/rules/complexity.js
@@ -23,7 +23,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a maximum cyclomatic complexity allowed in a program",
+ description: "Enforce a maximum cyclomatic complexity allowed in a program",
recommended: false,
url: "https://eslint.org/docs/rules/complexity"
},
diff --git a/lib/rules/computed-property-spacing.js b/lib/rules/computed-property-spacing.js
index 4850a8b651f..3d033fc00bd 100644
--- a/lib/rules/computed-property-spacing.js
+++ b/lib/rules/computed-property-spacing.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing inside computed property brackets",
+ description: "Enforce consistent spacing inside computed property brackets",
recommended: false,
url: "https://eslint.org/docs/rules/computed-property-spacing"
},
diff --git a/lib/rules/consistent-return.js b/lib/rules/consistent-return.js
index fffb4357b65..f0072974d11 100644
--- a/lib/rules/consistent-return.js
+++ b/lib/rules/consistent-return.js
@@ -46,7 +46,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `return` statements to either always or never specify values",
+ description: "Require `return` statements to either always or never specify values",
recommended: false,
url: "https://eslint.org/docs/rules/consistent-return"
},
diff --git a/lib/rules/consistent-this.js b/lib/rules/consistent-this.js
index 2aa07914638..947873b8e4a 100644
--- a/lib/rules/consistent-this.js
+++ b/lib/rules/consistent-this.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce consistent naming when capturing the current execution context",
+ description: "Enforce consistent naming when capturing the current execution context",
recommended: false,
url: "https://eslint.org/docs/rules/consistent-this"
},
diff --git a/lib/rules/constructor-super.js b/lib/rules/constructor-super.js
index defdb91d69d..fff658471b0 100644
--- a/lib/rules/constructor-super.js
+++ b/lib/rules/constructor-super.js
@@ -122,7 +122,7 @@ module.exports = {
type: "problem",
docs: {
- description: "require `super()` calls in constructors",
+ description: "Require `super()` calls in constructors",
recommended: true,
url: "https://eslint.org/docs/rules/constructor-super"
},
diff --git a/lib/rules/curly.js b/lib/rules/curly.js
index 29e73953da6..7b5d140fe66 100644
--- a/lib/rules/curly.js
+++ b/lib/rules/curly.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce consistent brace style for all control statements",
+ description: "Enforce consistent brace style for all control statements",
recommended: false,
url: "https://eslint.org/docs/rules/curly"
},
diff --git a/lib/rules/default-case-last.js b/lib/rules/default-case-last.js
index 34be2894e41..313a0d8c904 100644
--- a/lib/rules/default-case-last.js
+++ b/lib/rules/default-case-last.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce default clauses in switch statements to be last",
+ description: "Enforce default clauses in switch statements to be last",
recommended: false,
url: "https://eslint.org/docs/rules/default-case-last"
},
diff --git a/lib/rules/default-case.js b/lib/rules/default-case.js
index 6ce238529d0..f28de1af906 100644
--- a/lib/rules/default-case.js
+++ b/lib/rules/default-case.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `default` cases in `switch` statements",
+ description: "Require `default` cases in `switch` statements",
recommended: false,
url: "https://eslint.org/docs/rules/default-case"
},
diff --git a/lib/rules/default-param-last.js b/lib/rules/default-param-last.js
index ea12a2a558a..61df5f6d2eb 100644
--- a/lib/rules/default-param-last.js
+++ b/lib/rules/default-param-last.js
@@ -11,7 +11,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce default parameters to be last",
+ description: "Enforce default parameters to be last",
recommended: false,
url: "https://eslint.org/docs/rules/default-param-last"
},
diff --git a/lib/rules/dot-location.js b/lib/rules/dot-location.js
index 9dea4f25cf7..36b50b284cf 100644
--- a/lib/rules/dot-location.js
+++ b/lib/rules/dot-location.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent newlines before and after dots",
+ description: "Enforce consistent newlines before and after dots",
recommended: false,
url: "https://eslint.org/docs/rules/dot-location"
},
diff --git a/lib/rules/dot-notation.js b/lib/rules/dot-notation.js
index 90ba6d83b76..5f6e818cb49 100644
--- a/lib/rules/dot-notation.js
+++ b/lib/rules/dot-notation.js
@@ -26,7 +26,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce dot notation whenever possible",
+ description: "Enforce dot notation whenever possible",
recommended: false,
url: "https://eslint.org/docs/rules/dot-notation"
},
diff --git a/lib/rules/eol-last.js b/lib/rules/eol-last.js
index 393b934125e..fb87971fc73 100644
--- a/lib/rules/eol-last.js
+++ b/lib/rules/eol-last.js
@@ -14,7 +14,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow newline at the end of files",
+ description: "Require or disallow newline at the end of files",
recommended: false,
url: "https://eslint.org/docs/rules/eol-last"
},
diff --git a/lib/rules/eqeqeq.js b/lib/rules/eqeqeq.js
index b5d784dad6e..b3990e214d0 100644
--- a/lib/rules/eqeqeq.js
+++ b/lib/rules/eqeqeq.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require the use of `===` and `!==`",
+ description: "Require the use of `===` and `!==`",
recommended: false,
url: "https://eslint.org/docs/rules/eqeqeq"
},
diff --git a/lib/rules/for-direction.js b/lib/rules/for-direction.js
index d3d825a5766..7df3d7e4802 100644
--- a/lib/rules/for-direction.js
+++ b/lib/rules/for-direction.js
@@ -15,7 +15,7 @@ module.exports = {
type: "problem",
docs: {
- description: "enforce \"for\" loop update clause moving the counter in the right direction.",
+ description: "Enforce \"for\" loop update clause moving the counter in the right direction.",
recommended: true,
url: "https://eslint.org/docs/rules/for-direction"
},
diff --git a/lib/rules/func-call-spacing.js b/lib/rules/func-call-spacing.js
index 0391d99c763..fec6763a2cd 100644
--- a/lib/rules/func-call-spacing.js
+++ b/lib/rules/func-call-spacing.js
@@ -21,7 +21,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow spacing between function identifiers and their invocations",
+ description: "Require or disallow spacing between function identifiers and their invocations",
recommended: false,
url: "https://eslint.org/docs/rules/func-call-spacing"
},
diff --git a/lib/rules/func-name-matching.js b/lib/rules/func-name-matching.js
index 9cee5fe019a..391b2a27836 100644
--- a/lib/rules/func-name-matching.js
+++ b/lib/rules/func-name-matching.js
@@ -74,7 +74,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require function names to match the name of the variable or property to which they are assigned",
+ description: "Require function names to match the name of the variable or property to which they are assigned",
recommended: false,
url: "https://eslint.org/docs/rules/func-name-matching"
},
diff --git a/lib/rules/func-names.js b/lib/rules/func-names.js
index c7b2072e177..ee4664592f2 100644
--- a/lib/rules/func-names.js
+++ b/lib/rules/func-names.js
@@ -30,7 +30,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require or disallow named `function` expressions",
+ description: "Require or disallow named `function` expressions",
recommended: false,
url: "https://eslint.org/docs/rules/func-names"
},
diff --git a/lib/rules/func-style.js b/lib/rules/func-style.js
index f71574890c8..0e1ba9fab0e 100644
--- a/lib/rules/func-style.js
+++ b/lib/rules/func-style.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce the consistent use of either `function` declarations or expressions",
+ description: "Enforce the consistent use of either `function` declarations or expressions",
recommended: false,
url: "https://eslint.org/docs/rules/func-style"
},
diff --git a/lib/rules/function-call-argument-newline.js b/lib/rules/function-call-argument-newline.js
index f3cfeee703a..46610914622 100644
--- a/lib/rules/function-call-argument-newline.js
+++ b/lib/rules/function-call-argument-newline.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce line breaks between arguments of a function call",
+ description: "Enforce line breaks between arguments of a function call",
recommended: false,
url: "https://eslint.org/docs/rules/function-call-argument-newline"
},
diff --git a/lib/rules/function-paren-newline.js b/lib/rules/function-paren-newline.js
index a5b8f0d70c6..e61d17be603 100644
--- a/lib/rules/function-paren-newline.js
+++ b/lib/rules/function-paren-newline.js
@@ -20,7 +20,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent line breaks inside function parentheses",
+ description: "Enforce consistent line breaks inside function parentheses",
recommended: false,
url: "https://eslint.org/docs/rules/function-paren-newline"
},
@@ -183,7 +183,7 @@ module.exports = {
/**
* Gets the left paren and right paren tokens of a node.
* @param {ASTNode} node The node with parens
- * @throws {TypeError} Unexecpted node type.
+ * @throws {TypeError} Unexpected node type.
* @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token.
* Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression
* with a single parameter)
diff --git a/lib/rules/generator-star-spacing.js b/lib/rules/generator-star-spacing.js
index 28e81013fcb..d32b21fff5c 100644
--- a/lib/rules/generator-star-spacing.js
+++ b/lib/rules/generator-star-spacing.js
@@ -31,7 +31,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing around `*` operators in generator functions",
+ description: "Enforce consistent spacing around `*` operators in generator functions",
recommended: false,
url: "https://eslint.org/docs/rules/generator-star-spacing"
},
diff --git a/lib/rules/getter-return.js b/lib/rules/getter-return.js
index 03cfce2cf1a..5209ab1504b 100644
--- a/lib/rules/getter-return.js
+++ b/lib/rules/getter-return.js
@@ -35,7 +35,7 @@ module.exports = {
type: "problem",
docs: {
- description: "enforce `return` statements in getters",
+ description: "Enforce `return` statements in getters",
recommended: true,
url: "https://eslint.org/docs/rules/getter-return"
},
diff --git a/lib/rules/global-require.js b/lib/rules/global-require.js
index 71a2bf1ac49..77ce5d10827 100644
--- a/lib/rules/global-require.js
+++ b/lib/rules/global-require.js
@@ -58,7 +58,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `require()` calls to be placed at top-level module scope",
+ description: "Require `require()` calls to be placed at top-level module scope",
recommended: false,
url: "https://eslint.org/docs/rules/global-require"
},
diff --git a/lib/rules/grouped-accessor-pairs.js b/lib/rules/grouped-accessor-pairs.js
index 0fe6f91e4db..21374be2101 100644
--- a/lib/rules/grouped-accessor-pairs.js
+++ b/lib/rules/grouped-accessor-pairs.js
@@ -96,7 +96,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require grouped accessor pairs in object literals and classes",
+ description: "Require grouped accessor pairs in object literals and classes",
recommended: false,
url: "https://eslint.org/docs/rules/grouped-accessor-pairs"
},
diff --git a/lib/rules/guard-for-in.js b/lib/rules/guard-for-in.js
index 1c52af7d4cd..3b99143fe21 100644
--- a/lib/rules/guard-for-in.js
+++ b/lib/rules/guard-for-in.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `for-in` loops to include an `if` statement",
+ description: "Require `for-in` loops to include an `if` statement",
recommended: false,
url: "https://eslint.org/docs/rules/guard-for-in"
},
diff --git a/lib/rules/handle-callback-err.js b/lib/rules/handle-callback-err.js
index f370407743a..5189564b668 100644
--- a/lib/rules/handle-callback-err.js
+++ b/lib/rules/handle-callback-err.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require error handling in callbacks",
+ description: "Require error handling in callbacks",
recommended: false,
url: "https://eslint.org/docs/rules/handle-callback-err"
},
diff --git a/lib/rules/id-blacklist.js b/lib/rules/id-blacklist.js
index f7e04ae7376..5ea61e94f69 100644
--- a/lib/rules/id-blacklist.js
+++ b/lib/rules/id-blacklist.js
@@ -119,7 +119,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow specified identifiers",
+ description: "Disallow specified identifiers",
recommended: false,
url: "https://eslint.org/docs/rules/id-blacklist"
},
diff --git a/lib/rules/id-denylist.js b/lib/rules/id-denylist.js
index a0b1f416f46..fe0a0b50bd2 100644
--- a/lib/rules/id-denylist.js
+++ b/lib/rules/id-denylist.js
@@ -99,7 +99,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow specified identifiers",
+ description: "Disallow specified identifiers",
recommended: false,
url: "https://eslint.org/docs/rules/id-denylist"
},
diff --git a/lib/rules/id-length.js b/lib/rules/id-length.js
index 3701c66e347..99f833fc73b 100644
--- a/lib/rules/id-length.js
+++ b/lib/rules/id-length.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce minimum and maximum identifier lengths",
+ description: "Enforce minimum and maximum identifier lengths",
recommended: false,
url: "https://eslint.org/docs/rules/id-length"
},
diff --git a/lib/rules/id-match.js b/lib/rules/id-match.js
index 8713a5f9f8b..ec87af18d5b 100644
--- a/lib/rules/id-match.js
+++ b/lib/rules/id-match.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require identifiers to match a specified regular expression",
+ description: "Require identifiers to match a specified regular expression",
recommended: false,
url: "https://eslint.org/docs/rules/id-match"
},
diff --git a/lib/rules/implicit-arrow-linebreak.js b/lib/rules/implicit-arrow-linebreak.js
index 71b2437eef8..c765960267f 100644
--- a/lib/rules/implicit-arrow-linebreak.js
+++ b/lib/rules/implicit-arrow-linebreak.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce the location of arrow function bodies",
+ description: "Enforce the location of arrow function bodies",
recommended: false,
url: "https://eslint.org/docs/rules/implicit-arrow-linebreak"
},
diff --git a/lib/rules/indent-legacy.js b/lib/rules/indent-legacy.js
index c5be4a5d134..06de8c9a754 100644
--- a/lib/rules/indent-legacy.js
+++ b/lib/rules/indent-legacy.js
@@ -26,7 +26,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent indentation",
+ description: "Enforce consistent indentation",
recommended: false,
url: "https://eslint.org/docs/rules/indent-legacy"
},
diff --git a/lib/rules/indent.js b/lib/rules/indent.js
index 9c534cd58f0..b974a6ab150 100644
--- a/lib/rules/indent.js
+++ b/lib/rules/indent.js
@@ -500,7 +500,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent indentation",
+ description: "Enforce consistent indentation",
recommended: false,
url: "https://eslint.org/docs/rules/indent"
},
@@ -916,18 +916,6 @@ module.exports = {
}
offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
-
- /*
- * For blockless nodes with semicolon-first style, don't indent the semicolon.
- * e.g.
- * if (foo) bar()
- * ; [1, 2, 3].map(foo)
- */
- const lastToken = sourceCode.getLastToken(node);
-
- if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
- offsets.setDesiredOffset(lastToken, lastParentToken, 0);
- }
}
}
@@ -1223,7 +1211,7 @@ module.exports = {
}
},
- "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement": node => addBlocklessNodeIndent(node.body),
+ "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement": node => addBlocklessNodeIndent(node.body),
ExportNamedDeclaration(node) {
if (node.declaration === null) {
@@ -1271,6 +1259,50 @@ module.exports = {
}
},
+ /*
+ * For blockless nodes with semicolon-first style, don't indent the semicolon.
+ * e.g.
+ * if (foo)
+ * bar()
+ * ; [1, 2, 3].map(foo)
+ *
+ * Traversal into the node sets indentation of the semicolon, so we need to override it on exit.
+ */
+ ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"(node) {
+ let nodesToCheck;
+
+ if (node.type === "IfStatement") {
+ nodesToCheck = [node.consequent];
+ if (node.alternate) {
+ nodesToCheck.push(node.alternate);
+ }
+ } else {
+ nodesToCheck = [node.body];
+ }
+
+ for (const nodeToCheck of nodesToCheck) {
+ const lastToken = sourceCode.getLastToken(nodeToCheck);
+
+ if (astUtils.isSemicolonToken(lastToken)) {
+ const tokenBeforeLast = sourceCode.getTokenBefore(lastToken);
+ const tokenAfterLast = sourceCode.getTokenAfter(lastToken);
+
+ // override indentation of `;` only if its line looks like a semicolon-first style line
+ if (
+ !astUtils.isTokenOnSameLine(tokenBeforeLast, lastToken) &&
+ tokenAfterLast &&
+ astUtils.isTokenOnSameLine(lastToken, tokenAfterLast)
+ ) {
+ offsets.setDesiredOffset(
+ lastToken,
+ sourceCode.getFirstToken(node),
+ 0
+ );
+ }
+ }
+ }
+ },
+
ImportDeclaration(node) {
if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
diff --git a/lib/rules/init-declarations.js b/lib/rules/init-declarations.js
index d952b8925ed..b2ddf64fb4b 100644
--- a/lib/rules/init-declarations.js
+++ b/lib/rules/init-declarations.js
@@ -48,7 +48,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require or disallow initialization in variable declarations",
+ description: "Require or disallow initialization in variable declarations",
recommended: false,
url: "https://eslint.org/docs/rules/init-declarations"
},
diff --git a/lib/rules/jsx-quotes.js b/lib/rules/jsx-quotes.js
index f63dfd608bc..6745bb64b36 100644
--- a/lib/rules/jsx-quotes.js
+++ b/lib/rules/jsx-quotes.js
@@ -42,7 +42,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce the consistent use of either double or single quotes in JSX attributes",
+ description: "Enforce the consistent use of either double or single quotes in JSX attributes",
recommended: false,
url: "https://eslint.org/docs/rules/jsx-quotes"
},
diff --git a/lib/rules/key-spacing.js b/lib/rules/key-spacing.js
index ce8bad5bb35..b764b7282ef 100644
--- a/lib/rules/key-spacing.js
+++ b/lib/rules/key-spacing.js
@@ -9,6 +9,9 @@
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
+const GraphemeSplitter = require("grapheme-splitter");
+
+const splitter = new GraphemeSplitter();
//------------------------------------------------------------------------------
// Helpers
@@ -139,7 +142,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing between keys and values in object literal properties",
+ description: "Enforce consistent spacing between keys and values in object literal properties",
recommended: false,
url: "https://eslint.org/docs/rules/key-spacing"
},
@@ -508,7 +511,7 @@ module.exports = {
const startToken = sourceCode.getFirstToken(property);
const endToken = getLastTokenBeforeColon(property.key);
- return endToken.range[1] - startToken.range[0];
+ return splitter.countGraphemes(sourceCode.getText().slice(startToken.range[0], endToken.range[1]));
}
/**
diff --git a/lib/rules/keyword-spacing.js b/lib/rules/keyword-spacing.js
index 16a65d78696..59a500f5bfc 100644
--- a/lib/rules/keyword-spacing.js
+++ b/lib/rules/keyword-spacing.js
@@ -67,7 +67,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing before and after keywords",
+ description: "Enforce consistent spacing before and after keywords",
recommended: false,
url: "https://eslint.org/docs/rules/keyword-spacing"
},
diff --git a/lib/rules/line-comment-position.js b/lib/rules/line-comment-position.js
index 9ce2831dec6..0631ebe6f32 100644
--- a/lib/rules/line-comment-position.js
+++ b/lib/rules/line-comment-position.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce position of line comments",
+ description: "Enforce position of line comments",
recommended: false,
url: "https://eslint.org/docs/rules/line-comment-position"
},
diff --git a/lib/rules/linebreak-style.js b/lib/rules/linebreak-style.js
index 483788aa6ef..a5dc39d7967 100644
--- a/lib/rules/linebreak-style.js
+++ b/lib/rules/linebreak-style.js
@@ -21,7 +21,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent linebreak style",
+ description: "Enforce consistent linebreak style",
recommended: false,
url: "https://eslint.org/docs/rules/linebreak-style"
},
diff --git a/lib/rules/lines-around-comment.js b/lib/rules/lines-around-comment.js
index 6b1cd5f848b..bd7d1cd2662 100644
--- a/lib/rules/lines-around-comment.js
+++ b/lib/rules/lines-around-comment.js
@@ -55,7 +55,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require empty lines around comments",
+ description: "Require empty lines around comments",
recommended: false,
url: "https://eslint.org/docs/rules/lines-around-comment"
},
@@ -231,9 +231,15 @@ module.exports = {
const parent = getParentNodeOfToken(token);
if (parent && isParentNodeType(parent, nodeType)) {
- const parentStartNodeOrToken = parent.type === "StaticBlock"
- ? sourceCode.getFirstToken(parent, { skip: 1 }) // opening brace of the static block
- : parent;
+ let parentStartNodeOrToken = parent;
+
+ if (parent.type === "StaticBlock") {
+ parentStartNodeOrToken = sourceCode.getFirstToken(parent, { skip: 1 }); // opening brace of the static block
+ } else if (parent.type === "SwitchStatement") {
+ parentStartNodeOrToken = sourceCode.getTokenAfter(parent.discriminant, {
+ filter: astUtils.isOpeningBraceToken
+ }); // opening brace of the switch statement
+ }
return token.loc.start.line - parentStartNodeOrToken.loc.start.line === 1;
}
@@ -264,7 +270,8 @@ module.exports = {
isCommentAtParentStart(token, "ClassBody") ||
isCommentAtParentStart(token, "BlockStatement") ||
isCommentAtParentStart(token, "StaticBlock") ||
- isCommentAtParentStart(token, "SwitchCase")
+ isCommentAtParentStart(token, "SwitchCase") ||
+ isCommentAtParentStart(token, "SwitchStatement")
);
}
diff --git a/lib/rules/lines-around-directive.js b/lib/rules/lines-around-directive.js
index 21884f162e8..816efc979b7 100644
--- a/lib/rules/lines-around-directive.js
+++ b/lib/rules/lines-around-directive.js
@@ -18,7 +18,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow newlines around directives",
+ description: "Require or disallow newlines around directives",
recommended: false,
url: "https://eslint.org/docs/rules/lines-around-directive"
},
diff --git a/lib/rules/lines-between-class-members.js b/lib/rules/lines-between-class-members.js
index 1d6b7e7693e..26357aa3dde 100644
--- a/lib/rules/lines-between-class-members.js
+++ b/lib/rules/lines-between-class-members.js
@@ -20,7 +20,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow an empty line between class members",
+ description: "Require or disallow an empty line between class members",
recommended: false,
url: "https://eslint.org/docs/rules/lines-between-class-members"
},
diff --git a/lib/rules/max-classes-per-file.js b/lib/rules/max-classes-per-file.js
index 2157bebe4a9..0bd626fe6e8 100644
--- a/lib/rules/max-classes-per-file.js
+++ b/lib/rules/max-classes-per-file.js
@@ -19,7 +19,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a maximum number of classes per file",
+ description: "Enforce a maximum number of classes per file",
recommended: false,
url: "https://eslint.org/docs/rules/max-classes-per-file"
},
diff --git a/lib/rules/max-depth.js b/lib/rules/max-depth.js
index 8006ffdef75..6b428ced763 100644
--- a/lib/rules/max-depth.js
+++ b/lib/rules/max-depth.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a maximum depth that blocks can be nested",
+ description: "Enforce a maximum depth that blocks can be nested",
recommended: false,
url: "https://eslint.org/docs/rules/max-depth"
},
diff --git a/lib/rules/max-len.js b/lib/rules/max-len.js
index d05559e5baf..0d3b2af7026 100644
--- a/lib/rules/max-len.js
+++ b/lib/rules/max-len.js
@@ -69,7 +69,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce a maximum line length",
+ description: "Enforce a maximum line length",
recommended: false,
url: "https://eslint.org/docs/rules/max-len"
},
diff --git a/lib/rules/max-lines-per-function.js b/lib/rules/max-lines-per-function.js
index 5985a739e4b..fad646cc0c3 100644
--- a/lib/rules/max-lines-per-function.js
+++ b/lib/rules/max-lines-per-function.js
@@ -71,7 +71,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a maximum number of lines of code in a function",
+ description: "Enforce a maximum number of lines of code in a function",
recommended: false,
url: "https://eslint.org/docs/rules/max-lines-per-function"
},
diff --git a/lib/rules/max-lines.js b/lib/rules/max-lines.js
index 772f02aff08..d0e5bad3b2b 100644
--- a/lib/rules/max-lines.js
+++ b/lib/rules/max-lines.js
@@ -34,7 +34,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a maximum number of lines per file",
+ description: "Enforce a maximum number of lines per file",
recommended: false,
url: "https://eslint.org/docs/rules/max-lines"
},
diff --git a/lib/rules/max-nested-callbacks.js b/lib/rules/max-nested-callbacks.js
index 0d430507790..3764d5dee95 100644
--- a/lib/rules/max-nested-callbacks.js
+++ b/lib/rules/max-nested-callbacks.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a maximum depth that callbacks can be nested",
+ description: "Enforce a maximum depth that callbacks can be nested",
recommended: false,
url: "https://eslint.org/docs/rules/max-nested-callbacks"
},
diff --git a/lib/rules/max-params.js b/lib/rules/max-params.js
index 72379d217d6..8de1ab44b8a 100644
--- a/lib/rules/max-params.js
+++ b/lib/rules/max-params.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a maximum number of parameters in function definitions",
+ description: "Enforce a maximum number of parameters in function definitions",
recommended: false,
url: "https://eslint.org/docs/rules/max-params"
},
diff --git a/lib/rules/max-statements-per-line.js b/lib/rules/max-statements-per-line.js
index 61b508cf6cd..ada9cf0fe5e 100644
--- a/lib/rules/max-statements-per-line.js
+++ b/lib/rules/max-statements-per-line.js
@@ -20,7 +20,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce a maximum number of statements allowed per line",
+ description: "Enforce a maximum number of statements allowed per line",
recommended: false,
url: "https://eslint.org/docs/rules/max-statements-per-line"
},
diff --git a/lib/rules/max-statements.js b/lib/rules/max-statements.js
index ac117e92e72..c598b1059d0 100644
--- a/lib/rules/max-statements.js
+++ b/lib/rules/max-statements.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a maximum number of statements allowed in function blocks",
+ description: "Enforce a maximum number of statements allowed in function blocks",
recommended: false,
url: "https://eslint.org/docs/rules/max-statements"
},
@@ -126,7 +126,7 @@ module.exports = {
/*
* This rule does not apply to class static blocks, but we have to track them so
- * that stataments in them do not count as statements in the enclosing function.
+ * that statements in them do not count as statements in the enclosing function.
*/
if (node.type === "StaticBlock") {
return;
diff --git a/lib/rules/multiline-comment-style.js b/lib/rules/multiline-comment-style.js
index 7985bc86270..68cd666532d 100644
--- a/lib/rules/multiline-comment-style.js
+++ b/lib/rules/multiline-comment-style.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce a particular style for multiline comments",
+ description: "Enforce a particular style for multiline comments",
recommended: false,
url: "https://eslint.org/docs/rules/multiline-comment-style"
},
diff --git a/lib/rules/multiline-ternary.js b/lib/rules/multiline-ternary.js
index 91aa5a10031..62c84bbfed8 100644
--- a/lib/rules/multiline-ternary.js
+++ b/lib/rules/multiline-ternary.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce newlines between operands of ternary expressions",
+ description: "Enforce newlines between operands of ternary expressions",
recommended: false,
url: "https://eslint.org/docs/rules/multiline-ternary"
},
diff --git a/lib/rules/new-cap.js b/lib/rules/new-cap.js
index 466cfd4c585..ad59fd90621 100644
--- a/lib/rules/new-cap.js
+++ b/lib/rules/new-cap.js
@@ -82,7 +82,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require constructor names to begin with a capital letter",
+ description: "Require constructor names to begin with a capital letter",
recommended: false,
url: "https://eslint.org/docs/rules/new-cap"
},
diff --git a/lib/rules/new-parens.js b/lib/rules/new-parens.js
index 8ee4a2e1d19..f5a98a45d4d 100644
--- a/lib/rules/new-parens.js
+++ b/lib/rules/new-parens.js
@@ -25,7 +25,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce or disallow parentheses when invoking a constructor with no arguments",
+ description: "Enforce or disallow parentheses when invoking a constructor with no arguments",
recommended: false,
url: "https://eslint.org/docs/rules/new-parens"
},
diff --git a/lib/rules/newline-after-var.js b/lib/rules/newline-after-var.js
index e519a3afb6b..2b4d8584656 100644
--- a/lib/rules/newline-after-var.js
+++ b/lib/rules/newline-after-var.js
@@ -22,7 +22,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow an empty line after variable declarations",
+ description: "Require or disallow an empty line after variable declarations",
recommended: false,
url: "https://eslint.org/docs/rules/newline-after-var"
},
diff --git a/lib/rules/newline-before-return.js b/lib/rules/newline-before-return.js
index d07c23658ed..007d9427363 100644
--- a/lib/rules/newline-before-return.js
+++ b/lib/rules/newline-before-return.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require an empty line before `return` statements",
+ description: "Require an empty line before `return` statements",
recommended: false,
url: "https://eslint.org/docs/rules/newline-before-return"
},
diff --git a/lib/rules/newline-per-chained-call.js b/lib/rules/newline-per-chained-call.js
index 818bf703d2b..83844a52b35 100644
--- a/lib/rules/newline-per-chained-call.js
+++ b/lib/rules/newline-per-chained-call.js
@@ -18,7 +18,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require a newline after each call in a method chain",
+ description: "Require a newline after each call in a method chain",
recommended: false,
url: "https://eslint.org/docs/rules/newline-per-chained-call"
},
diff --git a/lib/rules/no-alert.js b/lib/rules/no-alert.js
index c6f7ddf38db..ba0125c877b 100644
--- a/lib/rules/no-alert.js
+++ b/lib/rules/no-alert.js
@@ -88,7 +88,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `alert`, `confirm`, and `prompt`",
+ description: "Disallow the use of `alert`, `confirm`, and `prompt`",
recommended: false,
url: "https://eslint.org/docs/rules/no-alert"
},
diff --git a/lib/rules/no-array-constructor.js b/lib/rules/no-array-constructor.js
index 02e6114dadc..93b79abfd89 100644
--- a/lib/rules/no-array-constructor.js
+++ b/lib/rules/no-array-constructor.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `Array` constructors",
+ description: "Disallow `Array` constructors",
recommended: false,
url: "https://eslint.org/docs/rules/no-array-constructor"
},
diff --git a/lib/rules/no-async-promise-executor.js b/lib/rules/no-async-promise-executor.js
index f940f152e3c..52c51862feb 100644
--- a/lib/rules/no-async-promise-executor.js
+++ b/lib/rules/no-async-promise-executor.js
@@ -14,7 +14,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow using an async function as a Promise executor",
+ description: "Disallow using an async function as a Promise executor",
recommended: true,
url: "https://eslint.org/docs/rules/no-async-promise-executor"
},
diff --git a/lib/rules/no-await-in-loop.js b/lib/rules/no-await-in-loop.js
index 3aea39a16b9..905a793c830 100644
--- a/lib/rules/no-await-in-loop.js
+++ b/lib/rules/no-await-in-loop.js
@@ -59,7 +59,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow `await` inside of loops",
+ description: "Disallow `await` inside of loops",
recommended: false,
url: "https://eslint.org/docs/rules/no-await-in-loop"
},
diff --git a/lib/rules/no-bitwise.js b/lib/rules/no-bitwise.js
index 43a1e764edc..172ea046bbe 100644
--- a/lib/rules/no-bitwise.js
+++ b/lib/rules/no-bitwise.js
@@ -26,7 +26,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow bitwise operators",
+ description: "Disallow bitwise operators",
recommended: false,
url: "https://eslint.org/docs/rules/no-bitwise"
},
diff --git a/lib/rules/no-buffer-constructor.js b/lib/rules/no-buffer-constructor.js
index 678d7032ab4..93003928815 100644
--- a/lib/rules/no-buffer-constructor.js
+++ b/lib/rules/no-buffer-constructor.js
@@ -19,7 +19,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow use of the `Buffer()` constructor",
+ description: "Disallow use of the `Buffer()` constructor",
recommended: false,
url: "https://eslint.org/docs/rules/no-buffer-constructor"
},
diff --git a/lib/rules/no-caller.js b/lib/rules/no-caller.js
index a6ad94f2fe6..884a02bdcf6 100644
--- a/lib/rules/no-caller.js
+++ b/lib/rules/no-caller.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `arguments.caller` or `arguments.callee`",
+ description: "Disallow the use of `arguments.caller` or `arguments.callee`",
recommended: false,
url: "https://eslint.org/docs/rules/no-caller"
},
diff --git a/lib/rules/no-case-declarations.js b/lib/rules/no-case-declarations.js
index d722f0cf584..6557ba3a03d 100644
--- a/lib/rules/no-case-declarations.js
+++ b/lib/rules/no-case-declarations.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow lexical declarations in case clauses",
+ description: "Disallow lexical declarations in case clauses",
recommended: true,
url: "https://eslint.org/docs/rules/no-case-declarations"
},
diff --git a/lib/rules/no-catch-shadow.js b/lib/rules/no-catch-shadow.js
index d09c9134968..49f1ba9649b 100644
--- a/lib/rules/no-catch-shadow.js
+++ b/lib/rules/no-catch-shadow.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `catch` clause parameters from shadowing variables in the outer scope",
+ description: "Disallow `catch` clause parameters from shadowing variables in the outer scope",
recommended: false,
url: "https://eslint.org/docs/rules/no-catch-shadow"
},
diff --git a/lib/rules/no-class-assign.js b/lib/rules/no-class-assign.js
index f679d4263e8..32e48e21188 100644
--- a/lib/rules/no-class-assign.js
+++ b/lib/rules/no-class-assign.js
@@ -17,7 +17,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow reassigning class members",
+ description: "Disallow reassigning class members",
recommended: true,
url: "https://eslint.org/docs/rules/no-class-assign"
},
diff --git a/lib/rules/no-compare-neg-zero.js b/lib/rules/no-compare-neg-zero.js
index fb56b99c58b..9715c2f0f37 100644
--- a/lib/rules/no-compare-neg-zero.js
+++ b/lib/rules/no-compare-neg-zero.js
@@ -14,7 +14,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow comparing against -0",
+ description: "Disallow comparing against -0",
recommended: true,
url: "https://eslint.org/docs/rules/no-compare-neg-zero"
},
diff --git a/lib/rules/no-cond-assign.js b/lib/rules/no-cond-assign.js
index 30d5b3bdaee..59efb341f09 100644
--- a/lib/rules/no-cond-assign.js
+++ b/lib/rules/no-cond-assign.js
@@ -34,7 +34,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow assignment operators in conditional expressions",
+ description: "Disallow assignment operators in conditional expressions",
recommended: true,
url: "https://eslint.org/docs/rules/no-cond-assign"
},
diff --git a/lib/rules/no-confusing-arrow.js b/lib/rules/no-confusing-arrow.js
index 9cdd0a85dbb..d2b6641b74f 100644
--- a/lib/rules/no-confusing-arrow.js
+++ b/lib/rules/no-confusing-arrow.js
@@ -31,7 +31,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow arrow functions where they could be confused with comparisons",
+ description: "Disallow arrow functions where they could be confused with comparisons",
recommended: false,
url: "https://eslint.org/docs/rules/no-confusing-arrow"
},
diff --git a/lib/rules/no-console.js b/lib/rules/no-console.js
index 464d5647cc3..bad6b6f4ee8 100644
--- a/lib/rules/no-console.js
+++ b/lib/rules/no-console.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `console`",
+ description: "Disallow the use of `console`",
recommended: false,
url: "https://eslint.org/docs/rules/no-console"
},
diff --git a/lib/rules/no-const-assign.js b/lib/rules/no-const-assign.js
index b5f7c37a98f..55e40c8849f 100644
--- a/lib/rules/no-const-assign.js
+++ b/lib/rules/no-const-assign.js
@@ -17,7 +17,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow reassigning `const` variables",
+ description: "Disallow reassigning `const` variables",
recommended: true,
url: "https://eslint.org/docs/rules/no-const-assign"
},
diff --git a/lib/rules/no-constant-binary-expression.js b/lib/rules/no-constant-binary-expression.js
index d550bcf1d91..dccfa2f5826 100644
--- a/lib/rules/no-constant-binary-expression.js
+++ b/lib/rules/no-constant-binary-expression.js
@@ -120,7 +120,7 @@ function isStaticBoolean(scope, node) {
/**
* Test if an AST node will always give the same result when compared to a
- * bolean value. Note that comparison to boolean values is different than
+ * boolean value. Note that comparison to boolean values is different than
* truthiness.
* https://262.ecma-international.org/5.1/#sec-11.9.3
*
@@ -238,7 +238,7 @@ function hasConstantLooseBooleanComparison(scope, node) {
/**
* Test if an AST node will always give the same result when _strictly_ compared
- * to a bolean value. This can happen if the expression can never be boolean, or
+ * to a boolean value. This can happen if the expression can never be boolean, or
* if it is always the same boolean value.
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
@@ -432,7 +432,7 @@ module.exports = {
meta: {
type: "problem",
docs: {
- description: "disallow expressions where the operation doesn't affect the value",
+ description: "Disallow expressions where the operation doesn't affect the value",
recommended: false,
url: "https://eslint.org/docs/rules/no-constant-binary-expression"
},
@@ -488,7 +488,7 @@ module.exports = {
}
/*
- * In theory we could handle short circuting assignment operators,
+ * In theory we could handle short-circuiting assignment operators,
* for some constant values, but that would require walking the
* scope to find the value of the variable being assigned. This is
* dependant on https://github.com/eslint/eslint/issues/13776
diff --git a/lib/rules/no-constant-condition.js b/lib/rules/no-constant-condition.js
index a0871fe972d..2ef687f6dca 100644
--- a/lib/rules/no-constant-condition.js
+++ b/lib/rules/no-constant-condition.js
@@ -21,7 +21,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow constant expressions in conditions",
+ description: "Disallow constant expressions in conditions",
recommended: true,
url: "https://eslint.org/docs/rules/no-constant-condition"
},
diff --git a/lib/rules/no-constructor-return.js b/lib/rules/no-constructor-return.js
index f8a717c75e5..911a32abcae 100644
--- a/lib/rules/no-constructor-return.js
+++ b/lib/rules/no-constructor-return.js
@@ -15,7 +15,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow returning value from constructor",
+ description: "Disallow returning value from constructor",
recommended: false,
url: "https://eslint.org/docs/rules/no-constructor-return"
},
diff --git a/lib/rules/no-continue.js b/lib/rules/no-continue.js
index 8658a7984bb..80381fc3f84 100644
--- a/lib/rules/no-continue.js
+++ b/lib/rules/no-continue.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `continue` statements",
+ description: "Disallow `continue` statements",
recommended: false,
url: "https://eslint.org/docs/rules/no-continue"
},
diff --git a/lib/rules/no-control-regex.js b/lib/rules/no-control-regex.js
index 04f3449fb19..ba108437257 100644
--- a/lib/rules/no-control-regex.js
+++ b/lib/rules/no-control-regex.js
@@ -30,10 +30,12 @@ const collector = new (class {
}
}
- collectControlChars(regexpStr) {
+ collectControlChars(regexpStr, flags) {
+ const uFlag = typeof flags === "string" && flags.includes("u");
+
try {
this._source = regexpStr;
- this._validator.validatePattern(regexpStr); // Call onCharacter hook
+ this._validator.validatePattern(regexpStr, void 0, void 0, uFlag); // Call onCharacter hook
} catch {
// Ignore syntax errors in RegExp.
@@ -52,7 +54,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow control characters in regular expressions",
+ description: "Disallow control characters in regular expressions",
recommended: true,
url: "https://eslint.org/docs/rules/no-control-regex"
},
@@ -68,13 +70,15 @@ module.exports = {
/**
* Get the regex expression
- * @param {ASTNode} node node to evaluate
- * @returns {RegExp|null} Regex if found else null
+ * @param {ASTNode} node `Literal` node to evaluate
+ * @returns {{ pattern: string, flags: string | null } | null} Regex if found (the given node is either a regex literal
+ * or a string literal that is the pattern argument of a RegExp constructor call). Otherwise `null`. If flags cannot be determined,
+ * the `flags` property will be `null`.
* @private
*/
- function getRegExpPattern(node) {
+ function getRegExp(node) {
if (node.regex) {
- return node.regex.pattern;
+ return node.regex;
}
if (typeof node.value === "string" &&
(node.parent.type === "NewExpression" || node.parent.type === "CallExpression") &&
@@ -82,7 +86,15 @@ module.exports = {
node.parent.callee.name === "RegExp" &&
node.parent.arguments[0] === node
) {
- return node.value;
+ const pattern = node.value;
+ const flags =
+ node.parent.arguments.length > 1 &&
+ node.parent.arguments[1].type === "Literal" &&
+ typeof node.parent.arguments[1].value === "string"
+ ? node.parent.arguments[1].value
+ : null;
+
+ return { pattern, flags };
}
return null;
@@ -90,10 +102,11 @@ module.exports = {
return {
Literal(node) {
- const pattern = getRegExpPattern(node);
+ const regExp = getRegExp(node);
- if (pattern) {
- const controlCharacters = collector.collectControlChars(pattern);
+ if (regExp) {
+ const { pattern, flags } = regExp;
+ const controlCharacters = collector.collectControlChars(pattern, flags);
if (controlCharacters.length > 0) {
context.report({
diff --git a/lib/rules/no-debugger.js b/lib/rules/no-debugger.js
index e62db1b7393..3b88079a0fb 100644
--- a/lib/rules/no-debugger.js
+++ b/lib/rules/no-debugger.js
@@ -15,7 +15,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow the use of `debugger`",
+ description: "Disallow the use of `debugger`",
recommended: true,
url: "https://eslint.org/docs/rules/no-debugger"
},
diff --git a/lib/rules/no-delete-var.js b/lib/rules/no-delete-var.js
index 1d1c710b098..41021bd46a7 100644
--- a/lib/rules/no-delete-var.js
+++ b/lib/rules/no-delete-var.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow deleting variables",
+ description: "Disallow deleting variables",
recommended: true,
url: "https://eslint.org/docs/rules/no-delete-var"
},
diff --git a/lib/rules/no-div-regex.js b/lib/rules/no-div-regex.js
index 175f6c20104..dd1c5782a58 100644
--- a/lib/rules/no-div-regex.js
+++ b/lib/rules/no-div-regex.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow division operators explicitly at the beginning of regular expressions",
+ description: "Disallow division operators explicitly at the beginning of regular expressions",
recommended: false,
url: "https://eslint.org/docs/rules/no-div-regex"
},
diff --git a/lib/rules/no-dupe-args.js b/lib/rules/no-dupe-args.js
index 13090e19a87..faf253793ec 100644
--- a/lib/rules/no-dupe-args.js
+++ b/lib/rules/no-dupe-args.js
@@ -15,7 +15,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow duplicate arguments in `function` definitions",
+ description: "Disallow duplicate arguments in `function` definitions",
recommended: true,
url: "https://eslint.org/docs/rules/no-dupe-args"
},
diff --git a/lib/rules/no-dupe-class-members.js b/lib/rules/no-dupe-class-members.js
index ae61f164ca9..8eca7878a46 100644
--- a/lib/rules/no-dupe-class-members.js
+++ b/lib/rules/no-dupe-class-members.js
@@ -17,7 +17,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow duplicate class members",
+ description: "Disallow duplicate class members",
recommended: true,
url: "https://eslint.org/docs/rules/no-dupe-class-members"
},
diff --git a/lib/rules/no-dupe-else-if.js b/lib/rules/no-dupe-else-if.js
index 1e1d549185d..49db5ec7c6c 100644
--- a/lib/rules/no-dupe-else-if.js
+++ b/lib/rules/no-dupe-else-if.js
@@ -52,7 +52,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow duplicate conditions in if-else-if chains",
+ description: "Disallow duplicate conditions in if-else-if chains",
recommended: true,
url: "https://eslint.org/docs/rules/no-dupe-else-if"
},
diff --git a/lib/rules/no-dupe-keys.js b/lib/rules/no-dupe-keys.js
index dac13cf9e09..65c34bc5fd1 100644
--- a/lib/rules/no-dupe-keys.js
+++ b/lib/rules/no-dupe-keys.js
@@ -88,7 +88,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow duplicate keys in object literals",
+ description: "Disallow duplicate keys in object literals",
recommended: true,
url: "https://eslint.org/docs/rules/no-dupe-keys"
},
diff --git a/lib/rules/no-duplicate-case.js b/lib/rules/no-duplicate-case.js
index a0c0b31308b..d436afdd007 100644
--- a/lib/rules/no-duplicate-case.js
+++ b/lib/rules/no-duplicate-case.js
@@ -22,7 +22,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow duplicate case labels",
+ description: "Disallow duplicate case labels",
recommended: true,
url: "https://eslint.org/docs/rules/no-duplicate-case"
},
diff --git a/lib/rules/no-duplicate-imports.js b/lib/rules/no-duplicate-imports.js
index 947bb30c2e1..619e2588e91 100644
--- a/lib/rules/no-duplicate-imports.js
+++ b/lib/rules/no-duplicate-imports.js
@@ -233,7 +233,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow duplicate module imports",
+ description: "Disallow duplicate module imports",
recommended: false,
url: "https://eslint.org/docs/rules/no-duplicate-imports"
},
diff --git a/lib/rules/no-else-return.js b/lib/rules/no-else-return.js
index 3662fc8c6e7..d1da3aa49cb 100644
--- a/lib/rules/no-else-return.js
+++ b/lib/rules/no-else-return.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `else` blocks after `return` statements in `if` statements",
+ description: "Disallow `else` blocks after `return` statements in `if` statements",
recommended: false,
url: "https://eslint.org/docs/rules/no-else-return"
},
diff --git a/lib/rules/no-empty-character-class.js b/lib/rules/no-empty-character-class.js
index f75f59191aa..2d294f4bded 100644
--- a/lib/rules/no-empty-character-class.js
+++ b/lib/rules/no-empty-character-class.js
@@ -30,7 +30,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow empty character classes in regular expressions",
+ description: "Disallow empty character classes in regular expressions",
recommended: true,
url: "https://eslint.org/docs/rules/no-empty-character-class"
},
diff --git a/lib/rules/no-empty-function.js b/lib/rules/no-empty-function.js
index e23b69e537b..4c9daa931e2 100644
--- a/lib/rules/no-empty-function.js
+++ b/lib/rules/no-empty-function.js
@@ -95,7 +95,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow empty functions",
+ description: "Disallow empty functions",
recommended: false,
url: "https://eslint.org/docs/rules/no-empty-function"
},
diff --git a/lib/rules/no-empty-pattern.js b/lib/rules/no-empty-pattern.js
index 2de575fcf08..5a497f03972 100644
--- a/lib/rules/no-empty-pattern.js
+++ b/lib/rules/no-empty-pattern.js
@@ -14,7 +14,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow empty destructuring patterns",
+ description: "Disallow empty destructuring patterns",
recommended: true,
url: "https://eslint.org/docs/rules/no-empty-pattern"
},
diff --git a/lib/rules/no-empty.js b/lib/rules/no-empty.js
index f04ee2cb320..459140a2e70 100644
--- a/lib/rules/no-empty.js
+++ b/lib/rules/no-empty.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow empty block statements",
+ description: "Disallow empty block statements",
recommended: true,
url: "https://eslint.org/docs/rules/no-empty"
},
diff --git a/lib/rules/no-eq-null.js b/lib/rules/no-eq-null.js
index b693737126d..9a886803dc5 100644
--- a/lib/rules/no-eq-null.js
+++ b/lib/rules/no-eq-null.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `null` comparisons without type-checking operators",
+ description: "Disallow `null` comparisons without type-checking operators",
recommended: false,
url: "https://eslint.org/docs/rules/no-eq-null"
},
diff --git a/lib/rules/no-eval.js b/lib/rules/no-eval.js
index 7af8dfac7fa..03f7b1f691c 100644
--- a/lib/rules/no-eval.js
+++ b/lib/rules/no-eval.js
@@ -43,7 +43,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `eval()`",
+ description: "Disallow the use of `eval()`",
recommended: false,
url: "https://eslint.org/docs/rules/no-eval"
},
diff --git a/lib/rules/no-ex-assign.js b/lib/rules/no-ex-assign.js
index 3db14206b0b..4c77b1128ad 100644
--- a/lib/rules/no-ex-assign.js
+++ b/lib/rules/no-ex-assign.js
@@ -17,7 +17,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow reassigning exceptions in `catch` clauses",
+ description: "Disallow reassigning exceptions in `catch` clauses",
recommended: true,
url: "https://eslint.org/docs/rules/no-ex-assign"
},
diff --git a/lib/rules/no-extend-native.js b/lib/rules/no-extend-native.js
index 771200f26f7..52c6bd31103 100644
--- a/lib/rules/no-extend-native.js
+++ b/lib/rules/no-extend-native.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow extending native types",
+ description: "Disallow extending native types",
recommended: false,
url: "https://eslint.org/docs/rules/no-extend-native"
},
diff --git a/lib/rules/no-extra-bind.js b/lib/rules/no-extra-bind.js
index 561cb1a33f8..caf6d8b1f80 100644
--- a/lib/rules/no-extra-bind.js
+++ b/lib/rules/no-extra-bind.js
@@ -26,7 +26,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary calls to `.bind()`",
+ description: "Disallow unnecessary calls to `.bind()`",
recommended: false,
url: "https://eslint.org/docs/rules/no-extra-bind"
},
diff --git a/lib/rules/no-extra-boolean-cast.js b/lib/rules/no-extra-boolean-cast.js
index ddb1d8330d5..1c2bc4e5032 100644
--- a/lib/rules/no-extra-boolean-cast.js
+++ b/lib/rules/no-extra-boolean-cast.js
@@ -24,7 +24,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary boolean casts",
+ description: "Disallow unnecessary boolean casts",
recommended: true,
url: "https://eslint.org/docs/rules/no-extra-boolean-cast"
},
diff --git a/lib/rules/no-extra-label.js b/lib/rules/no-extra-label.js
index 9186a9faca1..bda3dd0efb0 100644
--- a/lib/rules/no-extra-label.js
+++ b/lib/rules/no-extra-label.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary labels",
+ description: "Disallow unnecessary labels",
recommended: false,
url: "https://eslint.org/docs/rules/no-extra-label"
},
diff --git a/lib/rules/no-extra-parens.js b/lib/rules/no-extra-parens.js
index 5b54ae26fe3..5ae9af8fd54 100644
--- a/lib/rules/no-extra-parens.js
+++ b/lib/rules/no-extra-parens.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow unnecessary parentheses",
+ description: "Disallow unnecessary parentheses",
recommended: false,
url: "https://eslint.org/docs/rules/no-extra-parens"
},
diff --git a/lib/rules/no-extra-semi.js b/lib/rules/no-extra-semi.js
index 625310eea69..c61ad37dce8 100644
--- a/lib/rules/no-extra-semi.js
+++ b/lib/rules/no-extra-semi.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary semicolons",
+ description: "Disallow unnecessary semicolons",
recommended: true,
url: "https://eslint.org/docs/rules/no-extra-semi"
},
diff --git a/lib/rules/no-fallthrough.js b/lib/rules/no-fallthrough.js
index e49def54ba4..862d0c9bb67 100644
--- a/lib/rules/no-fallthrough.js
+++ b/lib/rules/no-fallthrough.js
@@ -77,7 +77,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow fallthrough of `case` statements",
+ description: "Disallow fallthrough of `case` statements",
recommended: true,
url: "https://eslint.org/docs/rules/no-fallthrough"
},
diff --git a/lib/rules/no-floating-decimal.js b/lib/rules/no-floating-decimal.js
index 8831bb824d0..cce50bf9dad 100644
--- a/lib/rules/no-floating-decimal.js
+++ b/lib/rules/no-floating-decimal.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow leading or trailing decimal points in numeric literals",
+ description: "Disallow leading or trailing decimal points in numeric literals",
recommended: false,
url: "https://eslint.org/docs/rules/no-floating-decimal"
},
diff --git a/lib/rules/no-func-assign.js b/lib/rules/no-func-assign.js
index 04a7dd37055..2c8fa6a8e08 100644
--- a/lib/rules/no-func-assign.js
+++ b/lib/rules/no-func-assign.js
@@ -17,7 +17,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow reassigning `function` declarations",
+ description: "Disallow reassigning `function` declarations",
recommended: true,
url: "https://eslint.org/docs/rules/no-func-assign"
},
diff --git a/lib/rules/no-global-assign.js b/lib/rules/no-global-assign.js
index 1225baec5de..9f2f0ee3642 100644
--- a/lib/rules/no-global-assign.js
+++ b/lib/rules/no-global-assign.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow assignments to native objects or read-only global variables",
+ description: "Disallow assignments to native objects or read-only global variables",
recommended: true,
url: "https://eslint.org/docs/rules/no-global-assign"
},
diff --git a/lib/rules/no-implicit-coercion.js b/lib/rules/no-implicit-coercion.js
index 4b21e3d94f4..c2367715d9d 100644
--- a/lib/rules/no-implicit-coercion.js
+++ b/lib/rules/no-implicit-coercion.js
@@ -30,9 +30,9 @@ function parseOptions(options) {
}
/**
- * Checks whether or not a node is a double logical nigating.
+ * Checks whether or not a node is a double logical negating.
* @param {ASTNode} node An UnaryExpression node to check.
- * @returns {boolean} Whether or not the node is a double logical nigating.
+ * @returns {boolean} Whether or not the node is a double logical negating.
*/
function isDoubleLogicalNegating(node) {
return (
@@ -173,7 +173,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow shorthand type conversions",
+ description: "Disallow shorthand type conversions",
recommended: false,
url: "https://eslint.org/docs/rules/no-implicit-coercion"
},
diff --git a/lib/rules/no-implicit-globals.js b/lib/rules/no-implicit-globals.js
index 5dd6aa71acd..934630ea070 100644
--- a/lib/rules/no-implicit-globals.js
+++ b/lib/rules/no-implicit-globals.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow declarations in the global scope",
+ description: "Disallow declarations in the global scope",
recommended: false,
url: "https://eslint.org/docs/rules/no-implicit-globals"
},
diff --git a/lib/rules/no-implied-eval.js b/lib/rules/no-implied-eval.js
index 38de5b31ccc..44f146171aa 100644
--- a/lib/rules/no-implied-eval.js
+++ b/lib/rules/no-implied-eval.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `eval()`-like methods",
+ description: "Disallow the use of `eval()`-like methods",
recommended: false,
url: "https://eslint.org/docs/rules/no-implied-eval"
},
diff --git a/lib/rules/no-import-assign.js b/lib/rules/no-import-assign.js
index 385386e9a43..fc104fe6c46 100644
--- a/lib/rules/no-import-assign.js
+++ b/lib/rules/no-import-assign.js
@@ -180,7 +180,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow assigning to imported bindings",
+ description: "Disallow assigning to imported bindings",
recommended: true,
url: "https://eslint.org/docs/rules/no-import-assign"
},
diff --git a/lib/rules/no-inline-comments.js b/lib/rules/no-inline-comments.js
index 2ed7feb46b8..366f567f670 100644
--- a/lib/rules/no-inline-comments.js
+++ b/lib/rules/no-inline-comments.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow inline comments after code",
+ description: "Disallow inline comments after code",
recommended: false,
url: "https://eslint.org/docs/rules/no-inline-comments"
},
diff --git a/lib/rules/no-inner-declarations.js b/lib/rules/no-inner-declarations.js
index 3b0feb71a3f..932816641e0 100644
--- a/lib/rules/no-inner-declarations.js
+++ b/lib/rules/no-inner-declarations.js
@@ -48,7 +48,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow variable or `function` declarations in nested blocks",
+ description: "Disallow variable or `function` declarations in nested blocks",
recommended: true,
url: "https://eslint.org/docs/rules/no-inner-declarations"
},
diff --git a/lib/rules/no-invalid-regexp.js b/lib/rules/no-invalid-regexp.js
index 92ac5125e60..0f1d9c7bedc 100644
--- a/lib/rules/no-invalid-regexp.js
+++ b/lib/rules/no-invalid-regexp.js
@@ -23,7 +23,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow invalid regular expression strings in `RegExp` constructors",
+ description: "Disallow invalid regular expression strings in `RegExp` constructors",
recommended: true,
url: "https://eslint.org/docs/rules/no-invalid-regexp"
},
diff --git a/lib/rules/no-invalid-this.js b/lib/rules/no-invalid-this.js
index a97696b8562..b9cb43af5d7 100644
--- a/lib/rules/no-invalid-this.js
+++ b/lib/rules/no-invalid-this.js
@@ -36,7 +36,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow use of `this` in contexts where the value of `this` is `undefined`",
+ description: "Disallow use of `this` in contexts where the value of `this` is `undefined`",
recommended: false,
url: "https://eslint.org/docs/rules/no-invalid-this"
},
diff --git a/lib/rules/no-irregular-whitespace.js b/lib/rules/no-irregular-whitespace.js
index 65c4d67285c..d1646c7b8a1 100644
--- a/lib/rules/no-irregular-whitespace.js
+++ b/lib/rules/no-irregular-whitespace.js
@@ -31,7 +31,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow irregular whitespace",
+ description: "Disallow irregular whitespace",
recommended: true,
url: "https://eslint.org/docs/rules/no-irregular-whitespace"
},
diff --git a/lib/rules/no-iterator.js b/lib/rules/no-iterator.js
index d11267286c8..3550c7b111b 100644
--- a/lib/rules/no-iterator.js
+++ b/lib/rules/no-iterator.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of the `__iterator__` property",
+ description: "Disallow the use of the `__iterator__` property",
recommended: false,
url: "https://eslint.org/docs/rules/no-iterator"
},
diff --git a/lib/rules/no-label-var.js b/lib/rules/no-label-var.js
index 50211811ac8..a07d283f522 100644
--- a/lib/rules/no-label-var.js
+++ b/lib/rules/no-label-var.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow labels that share a name with a variable",
+ description: "Disallow labels that share a name with a variable",
recommended: false,
url: "https://eslint.org/docs/rules/no-label-var"
},
diff --git a/lib/rules/no-labels.js b/lib/rules/no-labels.js
index 2e79f378a9b..6112d04affb 100644
--- a/lib/rules/no-labels.js
+++ b/lib/rules/no-labels.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow labeled statements",
+ description: "Disallow labeled statements",
recommended: false,
url: "https://eslint.org/docs/rules/no-labels"
},
diff --git a/lib/rules/no-lone-blocks.js b/lib/rules/no-lone-blocks.js
index f9fe9514dd7..486a76ffdc9 100644
--- a/lib/rules/no-lone-blocks.js
+++ b/lib/rules/no-lone-blocks.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary nested blocks",
+ description: "Disallow unnecessary nested blocks",
recommended: false,
url: "https://eslint.org/docs/rules/no-lone-blocks"
},
diff --git a/lib/rules/no-lonely-if.js b/lib/rules/no-lonely-if.js
index 9abd4650b56..0774b9fa30f 100644
--- a/lib/rules/no-lonely-if.js
+++ b/lib/rules/no-lonely-if.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `if` statements as the only statement in `else` blocks",
+ description: "Disallow `if` statements as the only statement in `else` blocks",
recommended: false,
url: "https://eslint.org/docs/rules/no-lonely-if"
},
diff --git a/lib/rules/no-loop-func.js b/lib/rules/no-loop-func.js
index c5460616dc1..f81a7133680 100644
--- a/lib/rules/no-loop-func.js
+++ b/lib/rules/no-loop-func.js
@@ -125,7 +125,7 @@ function isSafe(loopNode, reference) {
* The reference is every reference of the upper scope's variable we are
* looking now.
*
- * It's safeafe if the reference matches one of the following condition.
+ * It's safe if the reference matches one of the following condition.
* - is readonly.
* - doesn't exist inside a local function and after the border.
* @param {eslint-scope.Reference} upperRef A reference to check.
@@ -154,7 +154,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow function declarations that contain unsafe references inside loop statements",
+ description: "Disallow function declarations that contain unsafe references inside loop statements",
recommended: false,
url: "https://eslint.org/docs/rules/no-loop-func"
},
diff --git a/lib/rules/no-loss-of-precision.js b/lib/rules/no-loss-of-precision.js
index fefc7b768fe..6dc6d864dcd 100644
--- a/lib/rules/no-loss-of-precision.js
+++ b/lib/rules/no-loss-of-precision.js
@@ -15,7 +15,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow literal numbers that lose precision",
+ description: "Disallow literal numbers that lose precision",
recommended: true,
url: "https://eslint.org/docs/rules/no-loss-of-precision"
},
diff --git a/lib/rules/no-magic-numbers.js b/lib/rules/no-magic-numbers.js
index 6b4cf77c326..9b085881556 100644
--- a/lib/rules/no-magic-numbers.js
+++ b/lib/rules/no-magic-numbers.js
@@ -32,7 +32,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow magic numbers",
+ description: "Disallow magic numbers",
recommended: false,
url: "https://eslint.org/docs/rules/no-magic-numbers"
},
diff --git a/lib/rules/no-misleading-character-class.js b/lib/rules/no-misleading-character-class.js
index 94b28784a10..667d066e81c 100644
--- a/lib/rules/no-misleading-character-class.js
+++ b/lib/rules/no-misleading-character-class.js
@@ -4,13 +4,16 @@
"use strict";
const { CALL, CONSTRUCT, ReferenceTracker, getStringIfConstant } = require("eslint-utils");
-const { RegExpParser, visitRegExpAST } = require("regexpp");
+const { RegExpValidator, RegExpParser, visitRegExpAST } = require("regexpp");
const { isCombiningCharacter, isEmojiModifier, isRegionalIndicatorSymbol, isSurrogatePair } = require("./utils/unicode");
+const astUtils = require("./utils/ast-utils.js");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
+const REGEXPP_LATEST_ECMA_VERSION = 2022;
+
/**
* Iterate character sequences of a given nodes.
*
@@ -104,11 +107,13 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow characters which are made with multiple code points in character class syntax",
+ description: "Disallow characters which are made with multiple code points in character class syntax",
recommended: true,
url: "https://eslint.org/docs/rules/no-misleading-character-class"
},
+ hasSuggestions: true,
+
schema: [],
messages: {
@@ -116,10 +121,12 @@ module.exports = {
combiningClass: "Unexpected combined character in character class.",
emojiModifier: "Unexpected modified Emoji in character class.",
regionalIndicatorSymbol: "Unexpected national flag in character class.",
- zwj: "Unexpected joined character sequence in character class."
+ zwj: "Unexpected joined character sequence in character class.",
+ suggestUnicodeFlag: "Add unicode 'u' flag to regex."
}
},
create(context) {
+ const sourceCode = context.getSourceCode();
const parser = new RegExpParser();
/**
@@ -127,17 +134,10 @@ module.exports = {
* @param {Node} node The node to report.
* @param {string} pattern The regular expression pattern to verify.
* @param {string} flags The flags of the regular expression.
+ * @param {Function} unicodeFixer Fixer for missing "u" flag.
* @returns {void}
*/
- function verify(node, pattern, flags) {
- const has = {
- surrogatePairWithoutUFlag: false,
- combiningClass: false,
- variationSelector: false,
- emojiModifier: false,
- regionalIndicatorSymbol: false,
- zwj: false
- };
+ function verify(node, pattern, flags, unicodeFixer) {
let patternNode;
try {
@@ -153,26 +153,75 @@ module.exports = {
return;
}
+ const foundKinds = new Set();
+
visitRegExpAST(patternNode, {
onCharacterClassEnter(ccNode) {
for (const chars of iterateCharacterSequence(ccNode.elements)) {
for (const kind of kinds) {
- has[kind] = has[kind] || hasCharacterSequence[kind](chars);
+ if (hasCharacterSequence[kind](chars)) {
+ foundKinds.add(kind);
+ }
}
}
}
});
- for (const kind of kinds) {
- if (has[kind]) {
- context.report({ node, messageId: kind });
+ for (const kind of foundKinds) {
+ let suggest;
+
+ if (kind === "surrogatePairWithoutUFlag") {
+ suggest = [{
+ messageId: "suggestUnicodeFlag",
+ fix: unicodeFixer
+ }];
}
+
+ context.report({
+ node,
+ messageId: kind,
+ suggest
+ });
}
}
+ /**
+ * Checks if the given regular expression pattern would be valid with the `u` flag.
+ * @param {string} pattern The regular expression pattern to verify.
+ * @returns {boolean} `true` if the pattern would be valid with the `u` flag.
+ * `false` if the pattern would be invalid with the `u` flag or the configured
+ * ecmaVersion doesn't support the `u` flag.
+ */
+ function isValidWithUnicodeFlag(pattern) {
+ const { ecmaVersion } = context.parserOptions;
+
+ // ecmaVersion is unknown or it doesn't support the 'u' flag
+ if (typeof ecmaVersion !== "number" || ecmaVersion <= 5) {
+ return false;
+ }
+
+ const validator = new RegExpValidator({
+ ecmaVersion: Math.min(ecmaVersion + 2009, REGEXPP_LATEST_ECMA_VERSION)
+ });
+
+ try {
+ validator.validatePattern(pattern, void 0, void 0, /* uFlag = */ true);
+ } catch {
+ return false;
+ }
+
+ return true;
+ }
+
return {
"Literal[regex]"(node) {
- verify(node, node.regex.pattern, node.regex.flags);
+ verify(node, node.regex.pattern, node.regex.flags, fixer => {
+ if (!isValidWithUnicodeFlag(node.regex.pattern)) {
+ return null;
+ }
+
+ return fixer.insertTextAfter(node, "u");
+ });
},
"Program"() {
const scope = context.getScope();
@@ -191,7 +240,31 @@ module.exports = {
const flags = getStringIfConstant(flagsNode, scope);
if (typeof pattern === "string") {
- verify(node, pattern, flags || "");
+ verify(node, pattern, flags || "", fixer => {
+
+ if (!isValidWithUnicodeFlag(pattern)) {
+ return null;
+ }
+
+ if (node.arguments.length === 1) {
+ const penultimateToken = sourceCode.getLastToken(node, { skip: 1 }); // skip closing parenthesis
+
+ return fixer.insertTextAfter(
+ penultimateToken,
+ astUtils.isCommaToken(penultimateToken)
+ ? ' "u",'
+ : ', "u"'
+ );
+ }
+
+ if ((flagsNode.type === "Literal" && typeof flagsNode.value === "string") || flagsNode.type === "TemplateLiteral") {
+ const range = [flagsNode.range[0], flagsNode.range[1] - 1];
+
+ return fixer.insertTextAfterRange(range, "u");
+ }
+
+ return null;
+ });
}
}
}
diff --git a/lib/rules/no-mixed-operators.js b/lib/rules/no-mixed-operators.js
index 0cace7ea910..cb6e9363c15 100644
--- a/lib/rules/no-mixed-operators.js
+++ b/lib/rules/no-mixed-operators.js
@@ -88,7 +88,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow mixed binary operators",
+ description: "Disallow mixed binary operators",
recommended: false,
url: "https://eslint.org/docs/rules/no-mixed-operators"
},
diff --git a/lib/rules/no-mixed-requires.js b/lib/rules/no-mixed-requires.js
index 97064243ed3..4e970574416 100644
--- a/lib/rules/no-mixed-requires.js
+++ b/lib/rules/no-mixed-requires.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `require` calls to be mixed with regular variable declarations",
+ description: "Disallow `require` calls to be mixed with regular variable declarations",
recommended: false,
url: "https://eslint.org/docs/rules/no-mixed-requires"
},
diff --git a/lib/rules/no-mixed-spaces-and-tabs.js b/lib/rules/no-mixed-spaces-and-tabs.js
index f82a352caa4..b2d5a040b84 100644
--- a/lib/rules/no-mixed-spaces-and-tabs.js
+++ b/lib/rules/no-mixed-spaces-and-tabs.js
@@ -14,7 +14,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow mixed spaces and tabs for indentation",
+ description: "Disallow mixed spaces and tabs for indentation",
recommended: true,
url: "https://eslint.org/docs/rules/no-mixed-spaces-and-tabs"
},
diff --git a/lib/rules/no-multi-assign.js b/lib/rules/no-multi-assign.js
index be4d41f33d6..392b33ffd2d 100644
--- a/lib/rules/no-multi-assign.js
+++ b/lib/rules/no-multi-assign.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow use of chained assignment expressions",
+ description: "Disallow use of chained assignment expressions",
recommended: false,
url: "https://eslint.org/docs/rules/no-multi-assign"
},
diff --git a/lib/rules/no-multi-spaces.js b/lib/rules/no-multi-spaces.js
index 6fac7e3ca7e..d8d3c6509cc 100644
--- a/lib/rules/no-multi-spaces.js
+++ b/lib/rules/no-multi-spaces.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow multiple spaces",
+ description: "Disallow multiple spaces",
recommended: false,
url: "https://eslint.org/docs/rules/no-multi-spaces"
},
diff --git a/lib/rules/no-multi-str.js b/lib/rules/no-multi-str.js
index 6a17d581b98..c4400f45ee6 100644
--- a/lib/rules/no-multi-str.js
+++ b/lib/rules/no-multi-str.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow multiline strings",
+ description: "Disallow multiline strings",
recommended: false,
url: "https://eslint.org/docs/rules/no-multi-str"
},
diff --git a/lib/rules/no-multiple-empty-lines.js b/lib/rules/no-multiple-empty-lines.js
index d012303cc33..e8b0f9859c0 100644
--- a/lib/rules/no-multiple-empty-lines.js
+++ b/lib/rules/no-multiple-empty-lines.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow multiple empty lines",
+ description: "Disallow multiple empty lines",
recommended: false,
url: "https://eslint.org/docs/rules/no-multiple-empty-lines"
},
diff --git a/lib/rules/no-native-reassign.js b/lib/rules/no-native-reassign.js
index 5f396e404c6..634fea93308 100644
--- a/lib/rules/no-native-reassign.js
+++ b/lib/rules/no-native-reassign.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow assignments to native objects or read-only global variables",
+ description: "Disallow assignments to native objects or read-only global variables",
recommended: false,
url: "https://eslint.org/docs/rules/no-native-reassign"
},
diff --git a/lib/rules/no-negated-condition.js b/lib/rules/no-negated-condition.js
index a2870137f57..387617767fa 100644
--- a/lib/rules/no-negated-condition.js
+++ b/lib/rules/no-negated-condition.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow negated conditions",
+ description: "Disallow negated conditions",
recommended: false,
url: "https://eslint.org/docs/rules/no-negated-condition"
},
diff --git a/lib/rules/no-negated-in-lhs.js b/lib/rules/no-negated-in-lhs.js
index 95ab58a080f..975a8d75cb1 100644
--- a/lib/rules/no-negated-in-lhs.js
+++ b/lib/rules/no-negated-in-lhs.js
@@ -16,7 +16,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow negating the left operand in `in` expressions",
+ description: "Disallow negating the left operand in `in` expressions",
recommended: false,
url: "https://eslint.org/docs/rules/no-negated-in-lhs"
},
diff --git a/lib/rules/no-nested-ternary.js b/lib/rules/no-nested-ternary.js
index c87875e4040..fe97823416b 100644
--- a/lib/rules/no-nested-ternary.js
+++ b/lib/rules/no-nested-ternary.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow nested ternary expressions",
+ description: "Disallow nested ternary expressions",
recommended: false,
url: "https://eslint.org/docs/rules/no-nested-ternary"
},
diff --git a/lib/rules/no-new-func.js b/lib/rules/no-new-func.js
index 3b599433519..4759f380b29 100644
--- a/lib/rules/no-new-func.js
+++ b/lib/rules/no-new-func.js
@@ -27,7 +27,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `new` operators with the `Function` object",
+ description: "Disallow `new` operators with the `Function` object",
recommended: false,
url: "https://eslint.org/docs/rules/no-new-func"
},
diff --git a/lib/rules/no-new-object.js b/lib/rules/no-new-object.js
index 1a5784df24d..4dbe8db7365 100644
--- a/lib/rules/no-new-object.js
+++ b/lib/rules/no-new-object.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `Object` constructors",
+ description: "Disallow `Object` constructors",
recommended: false,
url: "https://eslint.org/docs/rules/no-new-object"
},
@@ -29,7 +29,7 @@ module.exports = {
schema: [],
messages: {
- preferLiteral: "The object literal notation {} is preferrable."
+ preferLiteral: "The object literal notation {} is preferable."
}
},
diff --git a/lib/rules/no-new-require.js b/lib/rules/no-new-require.js
index 5dadf6c2538..63ca057b741 100644
--- a/lib/rules/no-new-require.js
+++ b/lib/rules/no-new-require.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `new` operators with calls to `require`",
+ description: "Disallow `new` operators with calls to `require`",
recommended: false,
url: "https://eslint.org/docs/rules/no-new-require"
},
diff --git a/lib/rules/no-new-symbol.js b/lib/rules/no-new-symbol.js
index 6acfca94358..534201c0ba6 100644
--- a/lib/rules/no-new-symbol.js
+++ b/lib/rules/no-new-symbol.js
@@ -15,7 +15,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow `new` operators with the `Symbol` object",
+ description: "Disallow `new` operators with the `Symbol` object",
recommended: true,
url: "https://eslint.org/docs/rules/no-new-symbol"
},
diff --git a/lib/rules/no-new-wrappers.js b/lib/rules/no-new-wrappers.js
index 1fe06c1943e..ff44efc5930 100644
--- a/lib/rules/no-new-wrappers.js
+++ b/lib/rules/no-new-wrappers.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `new` operators with the `String`, `Number`, and `Boolean` objects",
+ description: "Disallow `new` operators with the `String`, `Number`, and `Boolean` objects",
recommended: false,
url: "https://eslint.org/docs/rules/no-new-wrappers"
},
diff --git a/lib/rules/no-new.js b/lib/rules/no-new.js
index 5b0976534d6..c4345057588 100644
--- a/lib/rules/no-new.js
+++ b/lib/rules/no-new.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `new` operators outside of assignments or comparisons",
+ description: "Disallow `new` operators outside of assignments or comparisons",
recommended: false,
url: "https://eslint.org/docs/rules/no-new"
},
diff --git a/lib/rules/no-nonoctal-decimal-escape.js b/lib/rules/no-nonoctal-decimal-escape.js
index 3edd269faeb..63e2264b33a 100644
--- a/lib/rules/no-nonoctal-decimal-escape.js
+++ b/lib/rules/no-nonoctal-decimal-escape.js
@@ -30,7 +30,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `\\8` and `\\9` escape sequences in string literals",
+ description: "Disallow `\\8` and `\\9` escape sequences in string literals",
recommended: true,
url: "https://eslint.org/docs/rules/no-nonoctal-decimal-escape"
},
diff --git a/lib/rules/no-obj-calls.js b/lib/rules/no-obj-calls.js
index 667ba69d803..86355d85d36 100644
--- a/lib/rules/no-obj-calls.js
+++ b/lib/rules/no-obj-calls.js
@@ -43,7 +43,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow calling global object properties as functions",
+ description: "Disallow calling global object properties as functions",
recommended: true,
url: "https://eslint.org/docs/rules/no-obj-calls"
},
diff --git a/lib/rules/no-octal-escape.js b/lib/rules/no-octal-escape.js
index 9ac56ab7bea..81a8a74cddb 100644
--- a/lib/rules/no-octal-escape.js
+++ b/lib/rules/no-octal-escape.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow octal escape sequences in string literals",
+ description: "Disallow octal escape sequences in string literals",
recommended: false,
url: "https://eslint.org/docs/rules/no-octal-escape"
},
diff --git a/lib/rules/no-octal.js b/lib/rules/no-octal.js
index 44df45fdacd..eec56919f1e 100644
--- a/lib/rules/no-octal.js
+++ b/lib/rules/no-octal.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow octal literals",
+ description: "Disallow octal literals",
recommended: true,
url: "https://eslint.org/docs/rules/no-octal"
},
@@ -23,7 +23,7 @@ module.exports = {
schema: [],
messages: {
- noOcatal: "Octal literals should not be used."
+ noOctal: "Octal literals should not be used."
}
},
@@ -35,7 +35,7 @@ module.exports = {
if (typeof node.value === "number" && /^0[0-9]/u.test(node.raw)) {
context.report({
node,
- messageId: "noOcatal"
+ messageId: "noOctal"
});
}
}
diff --git a/lib/rules/no-param-reassign.js b/lib/rules/no-param-reassign.js
index 87a6b702382..f89435c8675 100644
--- a/lib/rules/no-param-reassign.js
+++ b/lib/rules/no-param-reassign.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow reassigning `function` parameters",
+ description: "Disallow reassigning `function` parameters",
recommended: false,
url: "https://eslint.org/docs/rules/no-param-reassign"
},
diff --git a/lib/rules/no-path-concat.js b/lib/rules/no-path-concat.js
index 8d570a3778f..8502c511ed9 100644
--- a/lib/rules/no-path-concat.js
+++ b/lib/rules/no-path-concat.js
@@ -19,7 +19,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow string concatenation with `__dirname` and `__filename`",
+ description: "Disallow string concatenation with `__dirname` and `__filename`",
recommended: false,
url: "https://eslint.org/docs/rules/no-path-concat"
},
diff --git a/lib/rules/no-plusplus.js b/lib/rules/no-plusplus.js
index 2565da43231..cda6b05bfa8 100644
--- a/lib/rules/no-plusplus.js
+++ b/lib/rules/no-plusplus.js
@@ -51,7 +51,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the unary operators `++` and `--`",
+ description: "Disallow the unary operators `++` and `--`",
recommended: false,
url: "https://eslint.org/docs/rules/no-plusplus"
},
diff --git a/lib/rules/no-process-env.js b/lib/rules/no-process-env.js
index f7c2c718fd0..5db7c94b13b 100644
--- a/lib/rules/no-process-env.js
+++ b/lib/rules/no-process-env.js
@@ -19,7 +19,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `process.env`",
+ description: "Disallow the use of `process.env`",
recommended: false,
url: "https://eslint.org/docs/rules/no-process-env"
},
diff --git a/lib/rules/no-process-exit.js b/lib/rules/no-process-exit.js
index 251044b31c9..ca3ecfe6f5f 100644
--- a/lib/rules/no-process-exit.js
+++ b/lib/rules/no-process-exit.js
@@ -19,7 +19,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `process.exit()`",
+ description: "Disallow the use of `process.exit()`",
recommended: false,
url: "https://eslint.org/docs/rules/no-process-exit"
},
diff --git a/lib/rules/no-promise-executor-return.js b/lib/rules/no-promise-executor-return.js
index e40d4bcb3f5..caa195ffa07 100644
--- a/lib/rules/no-promise-executor-return.js
+++ b/lib/rules/no-promise-executor-return.js
@@ -69,7 +69,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow returning values from Promise executor functions",
+ description: "Disallow returning values from Promise executor functions",
recommended: false,
url: "https://eslint.org/docs/rules/no-promise-executor-return"
},
diff --git a/lib/rules/no-proto.js b/lib/rules/no-proto.js
index e6659e59c6b..771d206a88d 100644
--- a/lib/rules/no-proto.js
+++ b/lib/rules/no-proto.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of the `__proto__` property",
+ description: "Disallow the use of the `__proto__` property",
recommended: false,
url: "https://eslint.org/docs/rules/no-proto"
},
diff --git a/lib/rules/no-prototype-builtins.js b/lib/rules/no-prototype-builtins.js
index dc12669c87d..ea2763396d0 100644
--- a/lib/rules/no-prototype-builtins.js
+++ b/lib/rules/no-prototype-builtins.js
@@ -20,7 +20,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow calling some `Object.prototype` methods directly on objects",
+ description: "Disallow calling some `Object.prototype` methods directly on objects",
recommended: true,
url: "https://eslint.org/docs/rules/no-prototype-builtins"
},
diff --git a/lib/rules/no-redeclare.js b/lib/rules/no-redeclare.js
index cc71a612349..59749cb6643 100644
--- a/lib/rules/no-redeclare.js
+++ b/lib/rules/no-redeclare.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow variable redeclaration",
+ description: "Disallow variable redeclaration",
recommended: true,
url: "https://eslint.org/docs/rules/no-redeclare"
},
diff --git a/lib/rules/no-regex-spaces.js b/lib/rules/no-regex-spaces.js
index 400c72b5027..6d74aabe263 100644
--- a/lib/rules/no-regex-spaces.js
+++ b/lib/rules/no-regex-spaces.js
@@ -39,7 +39,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow multiple spaces in regular expressions",
+ description: "Disallow multiple spaces in regular expressions",
recommended: true,
url: "https://eslint.org/docs/rules/no-regex-spaces"
},
diff --git a/lib/rules/no-restricted-exports.js b/lib/rules/no-restricted-exports.js
index 5166cecaef2..d99e8928209 100644
--- a/lib/rules/no-restricted-exports.js
+++ b/lib/rules/no-restricted-exports.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow specified names in exports",
+ description: "Disallow specified names in exports",
recommended: false,
url: "https://eslint.org/docs/rules/no-restricted-exports"
},
diff --git a/lib/rules/no-restricted-globals.js b/lib/rules/no-restricted-globals.js
index 09d347890ca..b666238382d 100644
--- a/lib/rules/no-restricted-globals.js
+++ b/lib/rules/no-restricted-globals.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow specified global variables",
+ description: "Disallow specified global variables",
recommended: false,
url: "https://eslint.org/docs/rules/no-restricted-globals"
},
diff --git a/lib/rules/no-restricted-imports.js b/lib/rules/no-restricted-imports.js
index 3bb45d715ff..f4838679efc 100644
--- a/lib/rules/no-restricted-imports.js
+++ b/lib/rules/no-restricted-imports.js
@@ -58,6 +58,14 @@ const arrayOfStringsOrObjectPatterns = {
items: {
type: "object",
properties: {
+ importNames: {
+ type: "array",
+ items: {
+ type: "string"
+ },
+ minItems: 1,
+ uniqueItems: true
+ },
group: {
type: "array",
items: {
@@ -88,7 +96,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow specified modules when loaded by `import`",
+ description: "Disallow specified modules when loaded by `import`",
recommended: false,
url: "https://eslint.org/docs/rules/no-restricted-imports"
},
@@ -102,6 +110,14 @@ module.exports = {
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
patternWithCustomMessage: "'{{importSource}}' import is restricted from being used by a pattern. {{customMessage}}",
+ patternAndImportName: "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern.",
+ // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
+ patternAndImportNameWithCustomMessage: "'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}",
+
+ patternAndEverything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted from being used by a pattern.",
+ // eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
+ patternAndEverythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}",
+
everything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.",
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
everythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted. {{customMessage}}",
@@ -159,9 +175,10 @@ module.exports = {
}
// relative paths are supported for this rule
- const restrictedPatternGroups = restrictedPatterns.map(({ group, message, caseSensitive }) => ({
+ const restrictedPatternGroups = restrictedPatterns.map(({ group, message, caseSensitive, importNames }) => ({
matcher: ignore({ allowRelativePaths: true, ignorecase: !caseSensitive }).add(group),
- customMessage: message
+ customMessage: message,
+ importNames
}));
// if no imports are restricted we don't need to check
@@ -234,20 +251,68 @@ module.exports = {
/**
* Report a restricted path specifically for patterns.
* @param {node} node representing the restricted path reference
- * @param {Object} group contains a Ignore instance for paths, and the customMessage to show if it fails
+ * @param {Object} group contains an Ignore instance for paths, the customMessage to show on failure,
+ * and any restricted import names that have been specified in the config
+ * @param {Map} importNames Map of import names that are being imported
* @returns {void}
* @private
*/
- function reportPathForPatterns(node, group) {
+ function reportPathForPatterns(node, group, importNames) {
const importSource = node.source.value.trim();
- context.report({
- node,
- messageId: group.customMessage ? "patternWithCustomMessage" : "patterns",
- data: {
- importSource,
- customMessage: group.customMessage
+ const customMessage = group.customMessage;
+ const restrictedImportNames = group.importNames;
+
+ /*
+ * If we are not restricting to any specific import names and just the pattern itself,
+ * report the error and move on
+ */
+ if (!restrictedImportNames) {
+ context.report({
+ node,
+ messageId: customMessage ? "patternWithCustomMessage" : "patterns",
+ data: {
+ importSource,
+ customMessage
+ }
+ });
+ return;
+ }
+
+ if (importNames.has("*")) {
+ const specifierData = importNames.get("*")[0];
+
+ context.report({
+ node,
+ messageId: customMessage ? "patternAndEverythingWithCustomMessage" : "patternAndEverything",
+ loc: specifierData.loc,
+ data: {
+ importSource,
+ importNames: restrictedImportNames,
+ customMessage
+ }
+ });
+ }
+
+ restrictedImportNames.forEach(importName => {
+ if (!importNames.has(importName)) {
+ return;
}
+
+ const specifiers = importNames.get(importName);
+
+ specifiers.forEach(specifier => {
+ context.report({
+ node,
+ messageId: customMessage ? "patternAndImportNameWithCustomMessage" : "patternAndImportName",
+ loc: specifier.loc,
+ data: {
+ importSource,
+ customMessage,
+ importName
+ }
+ });
+ });
});
}
@@ -304,7 +369,7 @@ module.exports = {
checkRestrictedPathAndReport(importSource, importNames, node);
restrictedPatternGroups.forEach(group => {
if (isRestrictedPattern(importSource, group)) {
- reportPathForPatterns(node, group);
+ reportPathForPatterns(node, group, importNames);
}
});
}
diff --git a/lib/rules/no-restricted-modules.js b/lib/rules/no-restricted-modules.js
index d92aa7a86bc..c37694f9046 100644
--- a/lib/rules/no-restricted-modules.js
+++ b/lib/rules/no-restricted-modules.js
@@ -49,7 +49,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow specified modules when loaded by `require`",
+ description: "Disallow specified modules when loaded by `require`",
recommended: false,
url: "https://eslint.org/docs/rules/no-restricted-modules"
},
diff --git a/lib/rules/no-restricted-properties.js b/lib/rules/no-restricted-properties.js
index 1e8c7a89aed..7c03498563f 100644
--- a/lib/rules/no-restricted-properties.js
+++ b/lib/rules/no-restricted-properties.js
@@ -17,7 +17,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow certain properties on certain objects",
+ description: "Disallow certain properties on certain objects",
recommended: false,
url: "https://eslint.org/docs/rules/no-restricted-properties"
},
diff --git a/lib/rules/no-restricted-syntax.js b/lib/rules/no-restricted-syntax.js
index 713d1157c4d..76369cfd539 100644
--- a/lib/rules/no-restricted-syntax.js
+++ b/lib/rules/no-restricted-syntax.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow specified syntax",
+ description: "Disallow specified syntax",
recommended: false,
url: "https://eslint.org/docs/rules/no-restricted-syntax"
},
diff --git a/lib/rules/no-return-assign.js b/lib/rules/no-return-assign.js
index 4fd7a3ddba5..ccaf2c1c158 100644
--- a/lib/rules/no-return-assign.js
+++ b/lib/rules/no-return-assign.js
@@ -26,7 +26,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow assignment operators in `return` statements",
+ description: "Disallow assignment operators in `return` statements",
recommended: false,
url: "https://eslint.org/docs/rules/no-return-assign"
},
diff --git a/lib/rules/no-return-await.js b/lib/rules/no-return-await.js
index 191bf42dcf9..3007c8c877d 100644
--- a/lib/rules/no-return-await.js
+++ b/lib/rules/no-return-await.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary `return await`",
+ description: "Disallow unnecessary `return await`",
recommended: false,
diff --git a/lib/rules/no-script-url.js b/lib/rules/no-script-url.js
index 0eef2541840..41479006ee9 100644
--- a/lib/rules/no-script-url.js
+++ b/lib/rules/no-script-url.js
@@ -18,7 +18,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `javascript:` urls",
+ description: "Disallow `javascript:` urls",
recommended: false,
url: "https://eslint.org/docs/rules/no-script-url"
},
diff --git a/lib/rules/no-self-assign.js b/lib/rules/no-self-assign.js
index 060cc8e353e..348ee8dfc5f 100644
--- a/lib/rules/no-self-assign.js
+++ b/lib/rules/no-self-assign.js
@@ -130,7 +130,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow assignments where both sides are exactly the same",
+ description: "Disallow assignments where both sides are exactly the same",
recommended: true,
url: "https://eslint.org/docs/rules/no-self-assign"
},
diff --git a/lib/rules/no-self-compare.js b/lib/rules/no-self-compare.js
index c3512895e13..dab0db4b917 100644
--- a/lib/rules/no-self-compare.js
+++ b/lib/rules/no-self-compare.js
@@ -16,7 +16,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow comparisons where both sides are exactly the same",
+ description: "Disallow comparisons where both sides are exactly the same",
recommended: false,
url: "https://eslint.org/docs/rules/no-self-compare"
},
diff --git a/lib/rules/no-sequences.js b/lib/rules/no-sequences.js
index 376aec37988..2c0c27c3fea 100644
--- a/lib/rules/no-sequences.js
+++ b/lib/rules/no-sequences.js
@@ -29,7 +29,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow comma operators",
+ description: "Disallow comma operators",
recommended: false,
url: "https://eslint.org/docs/rules/no-sequences"
},
diff --git a/lib/rules/no-setter-return.js b/lib/rules/no-setter-return.js
index 7204e5c0c4d..25e8f1428b2 100644
--- a/lib/rules/no-setter-return.js
+++ b/lib/rules/no-setter-return.js
@@ -142,7 +142,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow returning values from setters",
+ description: "Disallow returning values from setters",
recommended: true,
url: "https://eslint.org/docs/rules/no-setter-return"
},
diff --git a/lib/rules/no-shadow-restricted-names.js b/lib/rules/no-shadow-restricted-names.js
index 52620e58d1c..a7d6d00f164 100644
--- a/lib/rules/no-shadow-restricted-names.js
+++ b/lib/rules/no-shadow-restricted-names.js
@@ -27,7 +27,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow identifiers from shadowing restricted names",
+ description: "Disallow identifiers from shadowing restricted names",
recommended: true,
url: "https://eslint.org/docs/rules/no-shadow-restricted-names"
},
diff --git a/lib/rules/no-shadow.js b/lib/rules/no-shadow.js
index b4ef334efdd..3af9354ebd7 100644
--- a/lib/rules/no-shadow.js
+++ b/lib/rules/no-shadow.js
@@ -30,7 +30,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow variable declarations from shadowing variables declared in the outer scope",
+ description: "Disallow variable declarations from shadowing variables declared in the outer scope",
recommended: false,
url: "https://eslint.org/docs/rules/no-shadow"
},
diff --git a/lib/rules/no-spaced-func.js b/lib/rules/no-spaced-func.js
index 1d2994333e1..97e2da06b0f 100644
--- a/lib/rules/no-spaced-func.js
+++ b/lib/rules/no-spaced-func.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow spacing between function identifiers and their applications (deprecated)",
+ description: "Disallow spacing between function identifiers and their applications (deprecated)",
recommended: false,
url: "https://eslint.org/docs/rules/no-spaced-func"
},
diff --git a/lib/rules/no-sparse-arrays.js b/lib/rules/no-sparse-arrays.js
index ff5c2cf9978..0e95fe4af7b 100644
--- a/lib/rules/no-sparse-arrays.js
+++ b/lib/rules/no-sparse-arrays.js
@@ -14,7 +14,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow sparse arrays",
+ description: "Disallow sparse arrays",
recommended: true,
url: "https://eslint.org/docs/rules/no-sparse-arrays"
},
diff --git a/lib/rules/no-sync.js b/lib/rules/no-sync.js
index 3536d9f2a39..71360c6bd32 100644
--- a/lib/rules/no-sync.js
+++ b/lib/rules/no-sync.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow synchronous methods",
+ description: "Disallow synchronous methods",
recommended: false,
url: "https://eslint.org/docs/rules/no-sync"
},
diff --git a/lib/rules/no-tabs.js b/lib/rules/no-tabs.js
index 9758b850be1..1b4834e09a7 100644
--- a/lib/rules/no-tabs.js
+++ b/lib/rules/no-tabs.js
@@ -22,7 +22,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow all tabs",
+ description: "Disallow all tabs",
recommended: false,
url: "https://eslint.org/docs/rules/no-tabs"
},
diff --git a/lib/rules/no-template-curly-in-string.js b/lib/rules/no-template-curly-in-string.js
index 1901460f3d2..4f4e9ee17e9 100644
--- a/lib/rules/no-template-curly-in-string.js
+++ b/lib/rules/no-template-curly-in-string.js
@@ -14,7 +14,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow template literal placeholder syntax in regular strings",
+ description: "Disallow template literal placeholder syntax in regular strings",
recommended: false,
url: "https://eslint.org/docs/rules/no-template-curly-in-string"
},
diff --git a/lib/rules/no-ternary.js b/lib/rules/no-ternary.js
index b0dc626832b..a185808a69a 100644
--- a/lib/rules/no-ternary.js
+++ b/lib/rules/no-ternary.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow ternary operators",
+ description: "Disallow ternary operators",
recommended: false,
url: "https://eslint.org/docs/rules/no-ternary"
},
diff --git a/lib/rules/no-this-before-super.js b/lib/rules/no-this-before-super.js
index 929eded2443..b4e48e86264 100644
--- a/lib/rules/no-this-before-super.js
+++ b/lib/rules/no-this-before-super.js
@@ -40,7 +40,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow `this`/`super` before calling `super()` in constructors",
+ description: "Disallow `this`/`super` before calling `super()` in constructors",
recommended: true,
url: "https://eslint.org/docs/rules/no-this-before-super"
},
diff --git a/lib/rules/no-throw-literal.js b/lib/rules/no-throw-literal.js
index c670ed9e5e1..3656c83a3ff 100644
--- a/lib/rules/no-throw-literal.js
+++ b/lib/rules/no-throw-literal.js
@@ -17,7 +17,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow throwing literals as exceptions",
+ description: "Disallow throwing literals as exceptions",
recommended: false,
url: "https://eslint.org/docs/rules/no-throw-literal"
},
diff --git a/lib/rules/no-trailing-spaces.js b/lib/rules/no-trailing-spaces.js
index 9e720ad32e8..a02a880e1d6 100644
--- a/lib/rules/no-trailing-spaces.js
+++ b/lib/rules/no-trailing-spaces.js
@@ -20,7 +20,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow trailing whitespace at the end of lines",
+ description: "Disallow trailing whitespace at the end of lines",
recommended: false,
url: "https://eslint.org/docs/rules/no-trailing-spaces"
},
diff --git a/lib/rules/no-undef-init.js b/lib/rules/no-undef-init.js
index 2c2204cf0fe..2cb1c3f3710 100644
--- a/lib/rules/no-undef-init.js
+++ b/lib/rules/no-undef-init.js
@@ -17,7 +17,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow initializing variables to `undefined`",
+ description: "Disallow initializing variables to `undefined`",
recommended: false,
url: "https://eslint.org/docs/rules/no-undef-init"
},
diff --git a/lib/rules/no-undef.js b/lib/rules/no-undef.js
index f65903245c8..e920ce6c288 100644
--- a/lib/rules/no-undef.js
+++ b/lib/rules/no-undef.js
@@ -29,7 +29,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow the use of undeclared variables unless mentioned in `/*global */` comments",
+ description: "Disallow the use of undeclared variables unless mentioned in `/*global */` comments",
recommended: true,
url: "https://eslint.org/docs/rules/no-undef"
},
diff --git a/lib/rules/no-undefined.js b/lib/rules/no-undefined.js
index de396d889c0..e006320b522 100644
--- a/lib/rules/no-undefined.js
+++ b/lib/rules/no-undefined.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `undefined` as an identifier",
+ description: "Disallow the use of `undefined` as an identifier",
recommended: false,
url: "https://eslint.org/docs/rules/no-undefined"
},
diff --git a/lib/rules/no-underscore-dangle.js b/lib/rules/no-underscore-dangle.js
index a3a9f650032..eb3e404a66d 100644
--- a/lib/rules/no-underscore-dangle.js
+++ b/lib/rules/no-underscore-dangle.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow dangling underscores in identifiers",
+ description: "Disallow dangling underscores in identifiers",
recommended: false,
url: "https://eslint.org/docs/rules/no-underscore-dangle"
},
diff --git a/lib/rules/no-unexpected-multiline.js b/lib/rules/no-unexpected-multiline.js
index 60d8f3164cd..2ca6731bc67 100644
--- a/lib/rules/no-unexpected-multiline.js
+++ b/lib/rules/no-unexpected-multiline.js
@@ -20,7 +20,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow confusing multiline expressions",
+ description: "Disallow confusing multiline expressions",
recommended: true,
url: "https://eslint.org/docs/rules/no-unexpected-multiline"
},
diff --git a/lib/rules/no-unmodified-loop-condition.js b/lib/rules/no-unmodified-loop-condition.js
index 5b8da26f2d2..12f61e98e6a 100644
--- a/lib/rules/no-unmodified-loop-condition.js
+++ b/lib/rules/no-unmodified-loop-condition.js
@@ -162,7 +162,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow unmodified loop conditions",
+ description: "Disallow unmodified loop conditions",
recommended: false,
url: "https://eslint.org/docs/rules/no-unmodified-loop-condition"
},
diff --git a/lib/rules/no-unneeded-ternary.js b/lib/rules/no-unneeded-ternary.js
index e00d5270a2a..c193282fa70 100644
--- a/lib/rules/no-unneeded-ternary.js
+++ b/lib/rules/no-unneeded-ternary.js
@@ -29,7 +29,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow ternary operators when simpler alternatives exist",
+ description: "Disallow ternary operators when simpler alternatives exist",
recommended: false,
url: "https://eslint.org/docs/rules/no-unneeded-ternary"
},
diff --git a/lib/rules/no-unreachable-loop.js b/lib/rules/no-unreachable-loop.js
index f100263308f..c42c922e0c4 100644
--- a/lib/rules/no-unreachable-loop.js
+++ b/lib/rules/no-unreachable-loop.js
@@ -59,7 +59,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow loops with a body that allows only one iteration",
+ description: "Disallow loops with a body that allows only one iteration",
recommended: false,
url: "https://eslint.org/docs/rules/no-unreachable-loop"
},
diff --git a/lib/rules/no-unreachable.js b/lib/rules/no-unreachable.js
index 4dda51f11b9..dea86815aac 100644
--- a/lib/rules/no-unreachable.js
+++ b/lib/rules/no-unreachable.js
@@ -111,7 +111,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow unreachable code after `return`, `throw`, `continue`, and `break` statements",
+ description: "Disallow unreachable code after `return`, `throw`, `continue`, and `break` statements",
recommended: true,
url: "https://eslint.org/docs/rules/no-unreachable"
},
diff --git a/lib/rules/no-unsafe-finally.js b/lib/rules/no-unsafe-finally.js
index 26c05eab8b0..80adb0fea46 100644
--- a/lib/rules/no-unsafe-finally.js
+++ b/lib/rules/no-unsafe-finally.js
@@ -24,7 +24,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow control flow statements in `finally` blocks",
+ description: "Disallow control flow statements in `finally` blocks",
recommended: true,
url: "https://eslint.org/docs/rules/no-unsafe-finally"
},
diff --git a/lib/rules/no-unsafe-negation.js b/lib/rules/no-unsafe-negation.js
index 057b1742acc..5dd150f8788 100644
--- a/lib/rules/no-unsafe-negation.js
+++ b/lib/rules/no-unsafe-negation.js
@@ -52,7 +52,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow negating the left operand of relational operators",
+ description: "Disallow negating the left operand of relational operators",
recommended: true,
url: "https://eslint.org/docs/rules/no-unsafe-negation"
},
diff --git a/lib/rules/no-unsafe-optional-chaining.js b/lib/rules/no-unsafe-optional-chaining.js
index 8556ccbd79d..99139078198 100644
--- a/lib/rules/no-unsafe-optional-chaining.js
+++ b/lib/rules/no-unsafe-optional-chaining.js
@@ -24,7 +24,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow use of optional chaining in contexts where the `undefined` value is not allowed",
+ description: "Disallow use of optional chaining in contexts where the `undefined` value is not allowed",
recommended: true,
url: "https://eslint.org/docs/rules/no-unsafe-optional-chaining"
},
diff --git a/lib/rules/no-unused-expressions.js b/lib/rules/no-unused-expressions.js
index e90099d6201..d34d5844d97 100644
--- a/lib/rules/no-unused-expressions.js
+++ b/lib/rules/no-unused-expressions.js
@@ -30,7 +30,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unused expressions",
+ description: "Disallow unused expressions",
recommended: false,
url: "https://eslint.org/docs/rules/no-unused-expressions"
},
diff --git a/lib/rules/no-unused-labels.js b/lib/rules/no-unused-labels.js
index f309dd12b12..305226a4df2 100644
--- a/lib/rules/no-unused-labels.js
+++ b/lib/rules/no-unused-labels.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unused labels",
+ description: "Disallow unused labels",
recommended: true,
url: "https://eslint.org/docs/rules/no-unused-labels"
},
diff --git a/lib/rules/no-unused-private-class-members.js b/lib/rules/no-unused-private-class-members.js
index 754c36002eb..e62a9ed5968 100644
--- a/lib/rules/no-unused-private-class-members.js
+++ b/lib/rules/no-unused-private-class-members.js
@@ -15,7 +15,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow unused private class members",
+ description: "Disallow unused private class members",
recommended: false,
url: "https://eslint.org/docs/rules/no-unused-private-class-members"
},
diff --git a/lib/rules/no-unused-vars.js b/lib/rules/no-unused-vars.js
index 11b1f3722de..778889a7676 100644
--- a/lib/rules/no-unused-vars.js
+++ b/lib/rules/no-unused-vars.js
@@ -33,7 +33,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow unused variables",
+ description: "Disallow unused variables",
recommended: true,
url: "https://eslint.org/docs/rules/no-unused-vars"
},
@@ -484,12 +484,12 @@ module.exports = {
}
/**
- * Determine if an identifier is used either in for-in loops.
+ * Determine if an identifier is used either in for-in or for-of loops.
* @param {Reference} ref The reference to check.
* @returns {boolean} whether reference is used in the for-in loops
* @private
*/
- function isForInRef(ref) {
+ function isForInOfRef(ref) {
let target = ref.identifier.parent;
@@ -498,7 +498,7 @@ module.exports = {
target = target.parent.parent;
}
- if (target.type !== "ForInStatement") {
+ if (target.type !== "ForInStatement" && target.type !== "ForOfStatement") {
return false;
}
@@ -531,7 +531,7 @@ module.exports = {
let rhsNode = null;
return variable.references.some(ref => {
- if (isForInRef(ref)) {
+ if (isForInOfRef(ref)) {
return true;
}
diff --git a/lib/rules/no-use-before-define.js b/lib/rules/no-use-before-define.js
index 07d035c431f..592c083589c 100644
--- a/lib/rules/no-use-before-define.js
+++ b/lib/rules/no-use-before-define.js
@@ -21,6 +21,7 @@ function parseOptions(options) {
let functions = true;
let classes = true;
let variables = true;
+ let allowNamedExports = false;
if (typeof options === "string") {
functions = (options !== "nofunc");
@@ -28,9 +29,10 @@ function parseOptions(options) {
functions = options.functions !== false;
classes = options.classes !== false;
variables = options.variables !== false;
+ allowNamedExports = !!options.allowNamedExports;
}
- return { functions, classes, variables };
+ return { functions, classes, variables, allowNamedExports };
}
/**
@@ -224,7 +226,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow the use of variables before they are defined",
+ description: "Disallow the use of variables before they are defined",
recommended: false,
url: "https://eslint.org/docs/rules/no-use-before-define"
},
@@ -240,7 +242,8 @@ module.exports = {
properties: {
functions: { type: "boolean" },
classes: { type: "boolean" },
- variables: { type: "boolean" }
+ variables: { type: "boolean" },
+ allowNamedExports: { type: "boolean" }
},
additionalProperties: false
}
@@ -273,6 +276,16 @@ module.exports = {
return false;
}
+ const { identifier } = reference;
+
+ if (
+ options.allowNamedExports &&
+ identifier.parent.type === "ExportSpecifier" &&
+ identifier.parent.local === identifier
+ ) {
+ return false;
+ }
+
const variable = reference.resolved;
if (!variable || variable.defs.length === 0) {
diff --git a/lib/rules/no-useless-backreference.js b/lib/rules/no-useless-backreference.js
index 1a09988b809..f23535bc359 100644
--- a/lib/rules/no-useless-backreference.js
+++ b/lib/rules/no-useless-backreference.js
@@ -64,7 +64,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow useless backreferences in regular expressions",
+ description: "Disallow useless backreferences in regular expressions",
recommended: true,
url: "https://eslint.org/docs/rules/no-useless-backreference"
},
diff --git a/lib/rules/no-useless-call.js b/lib/rules/no-useless-call.js
index 8c57cd5cc9a..2d3ae4e84ae 100644
--- a/lib/rules/no-useless-call.js
+++ b/lib/rules/no-useless-call.js
@@ -55,7 +55,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary calls to `.call()` and `.apply()`",
+ description: "Disallow unnecessary calls to `.call()` and `.apply()`",
recommended: false,
url: "https://eslint.org/docs/rules/no-useless-call"
},
diff --git a/lib/rules/no-useless-catch.js b/lib/rules/no-useless-catch.js
index 325a2e58117..36c356ecb42 100644
--- a/lib/rules/no-useless-catch.js
+++ b/lib/rules/no-useless-catch.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary `catch` clauses",
+ description: "Disallow unnecessary `catch` clauses",
recommended: true,
url: "https://eslint.org/docs/rules/no-useless-catch"
},
diff --git a/lib/rules/no-useless-computed-key.js b/lib/rules/no-useless-computed-key.js
index 7ebbe09de26..e7a3dc1db6d 100644
--- a/lib/rules/no-useless-computed-key.js
+++ b/lib/rules/no-useless-computed-key.js
@@ -91,7 +91,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary computed property keys in objects and classes",
+ description: "Disallow unnecessary computed property keys in objects and classes",
recommended: false,
url: "https://eslint.org/docs/rules/no-useless-computed-key"
},
diff --git a/lib/rules/no-useless-concat.js b/lib/rules/no-useless-concat.js
index 36ca84f90cb..26c5206df36 100644
--- a/lib/rules/no-useless-concat.js
+++ b/lib/rules/no-useless-concat.js
@@ -70,7 +70,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary concatenation of literals or template literals",
+ description: "Disallow unnecessary concatenation of literals or template literals",
recommended: false,
url: "https://eslint.org/docs/rules/no-useless-concat"
},
diff --git a/lib/rules/no-useless-constructor.js b/lib/rules/no-useless-constructor.js
index 6512c8b1fef..38c3bc3a05c 100644
--- a/lib/rules/no-useless-constructor.js
+++ b/lib/rules/no-useless-constructor.js
@@ -138,7 +138,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary constructors",
+ description: "Disallow unnecessary constructors",
recommended: false,
url: "https://eslint.org/docs/rules/no-useless-constructor"
},
diff --git a/lib/rules/no-useless-escape.js b/lib/rules/no-useless-escape.js
index 123bc5b8a01..2046a148a17 100644
--- a/lib/rules/no-useless-escape.js
+++ b/lib/rules/no-useless-escape.js
@@ -84,7 +84,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow unnecessary escape characters",
+ description: "Disallow unnecessary escape characters",
recommended: true,
url: "https://eslint.org/docs/rules/no-useless-escape"
},
diff --git a/lib/rules/no-useless-rename.js b/lib/rules/no-useless-rename.js
index 2489f57bcf5..908605f74cb 100644
--- a/lib/rules/no-useless-rename.js
+++ b/lib/rules/no-useless-rename.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow renaming import, export, and destructured assignments to the same name",
+ description: "Disallow renaming import, export, and destructured assignments to the same name",
recommended: false,
url: "https://eslint.org/docs/rules/no-useless-rename"
},
diff --git a/lib/rules/no-useless-return.js b/lib/rules/no-useless-return.js
index 0baa6b2942d..be8d4dfd3a5 100644
--- a/lib/rules/no-useless-return.js
+++ b/lib/rules/no-useless-return.js
@@ -67,7 +67,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow redundant return statements",
+ description: "Disallow redundant return statements",
recommended: false,
url: "https://eslint.org/docs/rules/no-useless-return"
},
diff --git a/lib/rules/no-var.js b/lib/rules/no-var.js
index 83a1f62eb6f..2185610ea10 100644
--- a/lib/rules/no-var.js
+++ b/lib/rules/no-var.js
@@ -185,7 +185,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `let` or `const` instead of `var`",
+ description: "Require `let` or `const` instead of `var`",
recommended: false,
url: "https://eslint.org/docs/rules/no-var"
},
diff --git a/lib/rules/no-void.js b/lib/rules/no-void.js
index 8631caf70cf..15c4730612d 100644
--- a/lib/rules/no-void.js
+++ b/lib/rules/no-void.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `void` operators",
+ description: "Disallow `void` operators",
recommended: false,
url: "https://eslint.org/docs/rules/no-void"
},
diff --git a/lib/rules/no-warning-comments.js b/lib/rules/no-warning-comments.js
index 5f3ea21d7d0..4f867cbb707 100644
--- a/lib/rules/no-warning-comments.js
+++ b/lib/rules/no-warning-comments.js
@@ -20,7 +20,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow specified warning terms in comments",
+ description: "Disallow specified warning terms in comments",
recommended: false,
url: "https://eslint.org/docs/rules/no-warning-comments"
},
@@ -64,59 +64,45 @@ module.exports = {
*/
function convertToRegExp(term) {
const escaped = escapeRegExp(term);
- const wordBoundary = "\\b";
- const eitherOrWordBoundary = `|${wordBoundary}`;
- let prefix;
/*
- * If the term ends in a word character (a-z0-9_), ensure a word
- * boundary at the end, so that substrings do not get falsely
- * matched. eg "todo" in a string such as "mastodon".
- * If the term ends in a non-word character, then \b won't match on
- * the boundary to the next non-word character, which would likely
- * be a space. For example `/\bFIX!\b/.test('FIX! blah') === false`.
- * In these cases, use no bounding match. Same applies for the
- * prefix, handled below.
+ * When matching at the start, ignore leading whitespace, and
+ * there's no need to worry about word boundaries.
+ *
+ * These expressions for the prefix and suffix are designed as follows:
+ * ^ handles any terms at the beginning of a comment.
+ * e.g. terms ["TODO"] matches `//TODO something`
+ * $ handles any terms at the end of a comment
+ * e.g. terms ["TODO"] matches `// something TODO`
+ * \s* handles optional leading spaces (for "start" location only)
+ * e.g. terms ["TODO"] matches `// TODO something`
+ * \b handles terms preceded/followed by word boundary
+ * e.g. terms: ["!FIX", "FIX!"] matches `// FIX!something` or `// something!FIX`
+ * terms: ["FIX"] matches `// FIX!` or `// !FIX`, but not `// fixed or affix`
*/
- const suffix = /\w$/u.test(term) ? "\\b" : "";
+ const wordBoundary = "\\b";
- if (location === "start") {
+ let prefix = "";
- /*
- * When matching at the start, ignore leading whitespace, and
- * there's no need to worry about word boundaries.
- */
+ if (location === "start") {
prefix = "^\\s*";
} else if (/^\w/u.test(term)) {
prefix = wordBoundary;
- } else {
- prefix = "";
}
- if (location === "start") {
-
- /*
- * For location "start" the regex should be
- * ^\s*TERM\b. This checks the word boundary
- * at the beginning of the comment.
- */
- return new RegExp(prefix + escaped + suffix, "iu");
- }
+ const suffix = /\w$/u.test(term) ? wordBoundary : "";
+ const flags = "iu"; // Case-insensitive with Unicode case folding.
/*
- * For location "anywhere" the regex should be
- * \bTERM\b|\bTERM\b, this checks the entire comment
- * for the term.
+ * For location "start", the typical regex is:
+ * /^\s*ESCAPED_TERM\b/iu.
+ *
+ * For location "anywhere" the typical regex is
+ * /\bESCAPED_TERM\b/iu
+ *
+ * If it starts or ends with non-word character, the prefix and suffix empty, respectively.
*/
- return new RegExp(
- prefix +
- escaped +
- suffix +
- eitherOrWordBoundary +
- term +
- wordBoundary,
- "iu"
- );
+ return new RegExp(`${prefix}${escaped}${suffix}`, flags);
}
const warningRegExps = warningTerms.map(convertToRegExp);
diff --git a/lib/rules/no-whitespace-before-property.js b/lib/rules/no-whitespace-before-property.js
index 95e920f27ea..67323816f85 100644
--- a/lib/rules/no-whitespace-before-property.js
+++ b/lib/rules/no-whitespace-before-property.js
@@ -20,7 +20,7 @@ module.exports = {
type: "layout",
docs: {
- description: "disallow whitespace before properties",
+ description: "Disallow whitespace before properties",
recommended: false,
url: "https://eslint.org/docs/rules/no-whitespace-before-property"
},
diff --git a/lib/rules/no-with.js b/lib/rules/no-with.js
index fc93f199f87..33de68d9c05 100644
--- a/lib/rules/no-with.js
+++ b/lib/rules/no-with.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `with` statements",
+ description: "Disallow `with` statements",
recommended: true,
url: "https://eslint.org/docs/rules/no-with"
},
diff --git a/lib/rules/nonblock-statement-body-position.js b/lib/rules/nonblock-statement-body-position.js
index c177cf34cee..cefecf302a6 100644
--- a/lib/rules/nonblock-statement-body-position.js
+++ b/lib/rules/nonblock-statement-body-position.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce the location of single-line statements",
+ description: "Enforce the location of single-line statements",
recommended: false,
url: "https://eslint.org/docs/rules/nonblock-statement-body-position"
},
diff --git a/lib/rules/object-curly-newline.js b/lib/rules/object-curly-newline.js
index e052cd86493..2f8004918a9 100644
--- a/lib/rules/object-curly-newline.js
+++ b/lib/rules/object-curly-newline.js
@@ -150,7 +150,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent line breaks after opening and before closing braces",
+ description: "Enforce consistent line breaks after opening and before closing braces",
recommended: false,
url: "https://eslint.org/docs/rules/object-curly-newline"
},
diff --git a/lib/rules/object-curly-spacing.js b/lib/rules/object-curly-spacing.js
index 9122da3ef3d..d6a8e5956ae 100644
--- a/lib/rules/object-curly-spacing.js
+++ b/lib/rules/object-curly-spacing.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing inside braces",
+ description: "Enforce consistent spacing inside braces",
recommended: false,
url: "https://eslint.org/docs/rules/object-curly-spacing"
},
diff --git a/lib/rules/object-property-newline.js b/lib/rules/object-property-newline.js
index dac084c3f65..bc079a16f45 100644
--- a/lib/rules/object-property-newline.js
+++ b/lib/rules/object-property-newline.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce placing object properties on separate lines",
+ description: "Enforce placing object properties on separate lines",
recommended: false,
url: "https://eslint.org/docs/rules/object-property-newline"
},
diff --git a/lib/rules/object-shorthand.js b/lib/rules/object-shorthand.js
index aa03450d071..8cd3978ca35 100644
--- a/lib/rules/object-shorthand.js
+++ b/lib/rules/object-shorthand.js
@@ -28,7 +28,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require or disallow method and property shorthand syntax for object literals",
+ description: "Require or disallow method and property shorthand syntax for object literals",
recommended: false,
url: "https://eslint.org/docs/rules/object-shorthand"
},
diff --git a/lib/rules/one-var-declaration-per-line.js b/lib/rules/one-var-declaration-per-line.js
index 440146b92c1..65be0929e71 100644
--- a/lib/rules/one-var-declaration-per-line.js
+++ b/lib/rules/one-var-declaration-per-line.js
@@ -14,7 +14,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require or disallow newlines around variable declarations",
+ description: "Require or disallow newlines around variable declarations",
recommended: false,
url: "https://eslint.org/docs/rules/one-var-declaration-per-line"
},
diff --git a/lib/rules/one-var.js b/lib/rules/one-var.js
index 1818c02e6e1..a8e2a1de05a 100644
--- a/lib/rules/one-var.js
+++ b/lib/rules/one-var.js
@@ -34,7 +34,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce variables to be declared either together or separately in functions",
+ description: "Enforce variables to be declared either together or separately in functions",
recommended: false,
url: "https://eslint.org/docs/rules/one-var"
},
diff --git a/lib/rules/operator-assignment.js b/lib/rules/operator-assignment.js
index 8b9fb5bd73b..ed9cb963bf2 100644
--- a/lib/rules/operator-assignment.js
+++ b/lib/rules/operator-assignment.js
@@ -63,7 +63,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require or disallow assignment operator shorthand where possible",
+ description: "Require or disallow assignment operator shorthand where possible",
recommended: false,
url: "https://eslint.org/docs/rules/operator-assignment"
},
diff --git a/lib/rules/operator-linebreak.js b/lib/rules/operator-linebreak.js
index a04f85bdea9..03b603e7584 100644
--- a/lib/rules/operator-linebreak.js
+++ b/lib/rules/operator-linebreak.js
@@ -21,7 +21,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent linebreak style for operators",
+ description: "Enforce consistent linebreak style for operators",
recommended: false,
url: "https://eslint.org/docs/rules/operator-linebreak"
},
diff --git a/lib/rules/padded-blocks.js b/lib/rules/padded-blocks.js
index 336adac9a02..5faf4343874 100644
--- a/lib/rules/padded-blocks.js
+++ b/lib/rules/padded-blocks.js
@@ -21,7 +21,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow padding within blocks",
+ description: "Require or disallow padding within blocks",
recommended: false,
url: "https://eslint.org/docs/rules/padded-blocks"
},
diff --git a/lib/rules/padding-line-between-statements.js b/lib/rules/padding-line-between-statements.js
index 7b442bff64a..9d730bffcd9 100644
--- a/lib/rules/padding-line-between-statements.js
+++ b/lib/rules/padding-line-between-statements.js
@@ -431,7 +431,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow padding lines between statements",
+ description: "Require or disallow padding lines between statements",
recommended: false,
url: "https://eslint.org/docs/rules/padding-line-between-statements"
},
diff --git a/lib/rules/prefer-arrow-callback.js b/lib/rules/prefer-arrow-callback.js
index 55a098a6097..9667139a88d 100644
--- a/lib/rules/prefer-arrow-callback.js
+++ b/lib/rules/prefer-arrow-callback.js
@@ -151,7 +151,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require using arrow functions for callbacks",
+ description: "Require using arrow functions for callbacks",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-arrow-callback"
},
diff --git a/lib/rules/prefer-const.js b/lib/rules/prefer-const.js
index cf07d6ce714..08f4492aaea 100644
--- a/lib/rules/prefer-const.js
+++ b/lib/rules/prefer-const.js
@@ -332,7 +332,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `const` declarations for variables that are never reassigned after declared",
+ description: "Require `const` declarations for variables that are never reassigned after declared",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-const"
},
diff --git a/lib/rules/prefer-destructuring.js b/lib/rules/prefer-destructuring.js
index 1f68313d6b1..fdf46f65f59 100644
--- a/lib/rules/prefer-destructuring.js
+++ b/lib/rules/prefer-destructuring.js
@@ -26,7 +26,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require destructuring from arrays and/or objects",
+ description: "Require destructuring from arrays and/or objects",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-destructuring"
},
diff --git a/lib/rules/prefer-exponentiation-operator.js b/lib/rules/prefer-exponentiation-operator.js
index a291e8dec15..fec5319723e 100644
--- a/lib/rules/prefer-exponentiation-operator.js
+++ b/lib/rules/prefer-exponentiation-operator.js
@@ -90,7 +90,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow the use of `Math.pow` in favor of the `**` operator",
+ description: "Disallow the use of `Math.pow` in favor of the `**` operator",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-exponentiation-operator"
},
diff --git a/lib/rules/prefer-named-capture-group.js b/lib/rules/prefer-named-capture-group.js
index cff2d8f45d2..1a13ffa8582 100644
--- a/lib/rules/prefer-named-capture-group.js
+++ b/lib/rules/prefer-named-capture-group.js
@@ -33,7 +33,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce using named capture group in regular expression",
+ description: "Enforce using named capture group in regular expression",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-named-capture-group"
},
diff --git a/lib/rules/prefer-numeric-literals.js b/lib/rules/prefer-numeric-literals.js
index 53a51536896..5f70158126c 100644
--- a/lib/rules/prefer-numeric-literals.js
+++ b/lib/rules/prefer-numeric-literals.js
@@ -45,7 +45,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals",
+ description: "Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-numeric-literals"
},
diff --git a/lib/rules/prefer-object-has-own.js b/lib/rules/prefer-object-has-own.js
index 19abdb31565..023d0a64f4c 100644
--- a/lib/rules/prefer-object-has-own.js
+++ b/lib/rules/prefer-object-has-own.js
@@ -50,7 +50,7 @@ module.exports = {
type: "suggestion",
docs: {
description:
- "disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`",
+ "Disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-object-has-own"
},
diff --git a/lib/rules/prefer-object-spread.js b/lib/rules/prefer-object-spread.js
index b63474ef2bd..08192001a2b 100644
--- a/lib/rules/prefer-object-spread.js
+++ b/lib/rules/prefer-object-spread.js
@@ -247,7 +247,7 @@ module.exports = {
docs: {
description:
- "disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead.",
+ "Disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead.",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-object-spread"
},
diff --git a/lib/rules/prefer-promise-reject-errors.js b/lib/rules/prefer-promise-reject-errors.js
index 60e72f45101..bd7bdcbf5b7 100644
--- a/lib/rules/prefer-promise-reject-errors.js
+++ b/lib/rules/prefer-promise-reject-errors.js
@@ -16,7 +16,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require using Error objects as Promise rejection reasons",
+ description: "Require using Error objects as Promise rejection reasons",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-promise-reject-errors"
},
diff --git a/lib/rules/prefer-reflect.js b/lib/rules/prefer-reflect.js
index 377268900b4..68ffa88b352 100644
--- a/lib/rules/prefer-reflect.js
+++ b/lib/rules/prefer-reflect.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `Reflect` methods where applicable",
+ description: "Require `Reflect` methods where applicable",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-reflect"
},
diff --git a/lib/rules/prefer-regex-literals.js b/lib/rules/prefer-regex-literals.js
index aa7258997c5..f30eddbf8c5 100644
--- a/lib/rules/prefer-regex-literals.js
+++ b/lib/rules/prefer-regex-literals.js
@@ -123,7 +123,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow use of the `RegExp` constructor in favor of regular expression literals",
+ description: "Disallow use of the `RegExp` constructor in favor of regular expression literals",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-regex-literals"
},
diff --git a/lib/rules/prefer-rest-params.js b/lib/rules/prefer-rest-params.js
index 371a28964f2..df1be55879a 100644
--- a/lib/rules/prefer-rest-params.js
+++ b/lib/rules/prefer-rest-params.js
@@ -65,7 +65,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require rest parameters instead of `arguments`",
+ description: "Require rest parameters instead of `arguments`",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-rest-params"
},
diff --git a/lib/rules/prefer-spread.js b/lib/rules/prefer-spread.js
index c5f9e1e6cbf..c8909fc0612 100644
--- a/lib/rules/prefer-spread.js
+++ b/lib/rules/prefer-spread.js
@@ -49,7 +49,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require spread operators instead of `.apply()`",
+ description: "Require spread operators instead of `.apply()`",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-spread"
},
diff --git a/lib/rules/prefer-template.js b/lib/rules/prefer-template.js
index e61eac1d65d..167c187db6f 100644
--- a/lib/rules/prefer-template.js
+++ b/lib/rules/prefer-template.js
@@ -128,7 +128,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require template literals instead of string concatenation",
+ description: "Require template literals instead of string concatenation",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-template"
},
diff --git a/lib/rules/quote-props.js b/lib/rules/quote-props.js
index 0b66d761c47..db9423978bb 100644
--- a/lib/rules/quote-props.js
+++ b/lib/rules/quote-props.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require quotes around object literal property names",
+ description: "Require quotes around object literal property names",
recommended: false,
url: "https://eslint.org/docs/rules/quote-props"
},
diff --git a/lib/rules/quotes.js b/lib/rules/quotes.js
index f1d30a044bc..ab7b38b90bf 100644
--- a/lib/rules/quotes.js
+++ b/lib/rules/quotes.js
@@ -80,7 +80,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce the consistent use of either backticks, double, or single quotes",
+ description: "Enforce the consistent use of either backticks, double, or single quotes",
recommended: false,
url: "https://eslint.org/docs/rules/quotes"
},
diff --git a/lib/rules/radix.js b/lib/rules/radix.js
index f83c762c11d..0618d9844ad 100644
--- a/lib/rules/radix.js
+++ b/lib/rules/radix.js
@@ -80,7 +80,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce the consistent use of the radix argument when using `parseInt()`",
+ description: "Enforce the consistent use of the radix argument when using `parseInt()`",
recommended: false,
url: "https://eslint.org/docs/rules/radix"
},
diff --git a/lib/rules/require-atomic-updates.js b/lib/rules/require-atomic-updates.js
index 4dbd48dfc58..7a5f822ab28 100644
--- a/lib/rules/require-atomic-updates.js
+++ b/lib/rules/require-atomic-updates.js
@@ -171,7 +171,7 @@ module.exports = {
type: "problem",
docs: {
- description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
+ description: "Disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
recommended: false,
url: "https://eslint.org/docs/rules/require-atomic-updates"
},
diff --git a/lib/rules/require-await.js b/lib/rules/require-await.js
index 1b17de0e197..1add2552e58 100644
--- a/lib/rules/require-await.js
+++ b/lib/rules/require-await.js
@@ -34,7 +34,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "disallow async functions which have no `await` expression",
+ description: "Disallow async functions which have no `await` expression",
recommended: false,
url: "https://eslint.org/docs/rules/require-await"
},
diff --git a/lib/rules/require-jsdoc.js b/lib/rules/require-jsdoc.js
index 169b6f52413..755f6df5fee 100644
--- a/lib/rules/require-jsdoc.js
+++ b/lib/rules/require-jsdoc.js
@@ -11,7 +11,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require JSDoc comments",
+ description: "Require JSDoc comments",
recommended: false,
url: "https://eslint.org/docs/rules/require-jsdoc"
},
diff --git a/lib/rules/require-unicode-regexp.js b/lib/rules/require-unicode-regexp.js
index 577ae6cf827..4236af6db47 100644
--- a/lib/rules/require-unicode-regexp.js
+++ b/lib/rules/require-unicode-regexp.js
@@ -26,7 +26,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce the use of `u` flag on RegExp",
+ description: "Enforce the use of `u` flag on RegExp",
recommended: false,
url: "https://eslint.org/docs/rules/require-unicode-regexp"
},
diff --git a/lib/rules/require-yield.js b/lib/rules/require-yield.js
index aba06140672..ffb2229790d 100644
--- a/lib/rules/require-yield.js
+++ b/lib/rules/require-yield.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require generator functions to contain `yield`",
+ description: "Require generator functions to contain `yield`",
recommended: true,
url: "https://eslint.org/docs/rules/require-yield"
},
diff --git a/lib/rules/rest-spread-spacing.js b/lib/rules/rest-spread-spacing.js
index ace1ec52141..17f9aa0c3c5 100644
--- a/lib/rules/rest-spread-spacing.js
+++ b/lib/rules/rest-spread-spacing.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce spacing between rest and spread operators and their expressions",
+ description: "Enforce spacing between rest and spread operators and their expressions",
recommended: false,
url: "https://eslint.org/docs/rules/rest-spread-spacing"
},
diff --git a/lib/rules/semi-spacing.js b/lib/rules/semi-spacing.js
index 4f0afbb11a3..875cb62443d 100644
--- a/lib/rules/semi-spacing.js
+++ b/lib/rules/semi-spacing.js
@@ -17,7 +17,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing before and after semicolons",
+ description: "Enforce consistent spacing before and after semicolons",
recommended: false,
url: "https://eslint.org/docs/rules/semi-spacing"
},
diff --git a/lib/rules/semi-style.js b/lib/rules/semi-style.js
index 7952a9adff1..424858b4ba1 100644
--- a/lib/rules/semi-style.js
+++ b/lib/rules/semi-style.js
@@ -73,7 +73,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce location of semicolons",
+ description: "Enforce location of semicolons",
recommended: false,
url: "https://eslint.org/docs/rules/semi-style"
},
diff --git a/lib/rules/semi.js b/lib/rules/semi.js
index 86ff8d74ee1..1e49273c2e9 100644
--- a/lib/rules/semi.js
+++ b/lib/rules/semi.js
@@ -21,7 +21,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow semicolons instead of ASI",
+ description: "Require or disallow semicolons instead of ASI",
recommended: false,
url: "https://eslint.org/docs/rules/semi"
},
diff --git a/lib/rules/sort-imports.js b/lib/rules/sort-imports.js
index 13cb63681cb..bfb0765baa5 100644
--- a/lib/rules/sort-imports.js
+++ b/lib/rules/sort-imports.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce sorted import declarations within modules",
+ description: "Enforce sorted import declarations within modules",
recommended: false,
url: "https://eslint.org/docs/rules/sort-imports"
},
diff --git a/lib/rules/sort-keys.js b/lib/rules/sort-keys.js
index 2fc19635271..1523ab751a0 100644
--- a/lib/rules/sort-keys.js
+++ b/lib/rules/sort-keys.js
@@ -81,7 +81,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require object keys to be sorted",
+ description: "Require object keys to be sorted",
recommended: false,
url: "https://eslint.org/docs/rules/sort-keys"
},
@@ -105,6 +105,10 @@ module.exports = {
type: "integer",
minimum: 2,
default: 2
+ },
+ allowLineSeparatedGroups: {
+ type: "boolean",
+ default: false
}
},
additionalProperties: false
@@ -124,17 +128,21 @@ module.exports = {
const insensitive = options && options.caseSensitive === false;
const natural = options && options.natural;
const minKeys = options && options.minKeys;
+ const allowLineSeparatedGroups = options && options.allowLineSeparatedGroups || false;
const isValidOrder = isValidOrders[
order + (insensitive ? "I" : "") + (natural ? "N" : "")
];
// The stack to save the previous property's name for each object literals.
let stack = null;
+ const sourceCode = context.getSourceCode();
return {
ObjectExpression(node) {
stack = {
upper: stack,
+ prevNode: null,
+ prevBlankLine: false,
prevName: null,
numKeys: node.properties.length
};
@@ -159,10 +167,45 @@ module.exports = {
const numKeys = stack.numKeys;
const thisName = getPropertyName(node);
+ // Get tokens between current node and previous node
+ const tokens = stack.prevNode && sourceCode
+ .getTokensBetween(stack.prevNode, node, { includeComments: true });
+
+ let isBlankLineBetweenNodes = stack.prevBlankLine;
+
+ if (tokens) {
+
+ // check blank line between tokens
+ tokens.forEach((token, index) => {
+ const previousToken = tokens[index - 1];
+
+ if (previousToken && (token.loc.start.line - previousToken.loc.end.line > 1)) {
+ isBlankLineBetweenNodes = true;
+ }
+ });
+
+ // check blank line between the current node and the last token
+ if (!isBlankLineBetweenNodes && (node.loc.start.line - tokens[tokens.length - 1].loc.end.line > 1)) {
+ isBlankLineBetweenNodes = true;
+ }
+
+ // check blank line between the first token and the previous node
+ if (!isBlankLineBetweenNodes && (tokens[0].loc.start.line - stack.prevNode.loc.end.line > 1)) {
+ isBlankLineBetweenNodes = true;
+ }
+ }
+
+ stack.prevNode = node;
+
if (thisName !== null) {
stack.prevName = thisName;
}
+ if (allowLineSeparatedGroups && isBlankLineBetweenNodes) {
+ stack.prevBlankLine = thisName === null;
+ return;
+ }
+
if (prevName === null || thisName === null || numKeys < minKeys) {
return;
}
diff --git a/lib/rules/sort-vars.js b/lib/rules/sort-vars.js
index 8246558c547..ec0718ee578 100644
--- a/lib/rules/sort-vars.js
+++ b/lib/rules/sort-vars.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require variables within the same declaration block to be sorted",
+ description: "Require variables within the same declaration block to be sorted",
recommended: false,
url: "https://eslint.org/docs/rules/sort-vars"
},
diff --git a/lib/rules/space-before-blocks.js b/lib/rules/space-before-blocks.js
index 5cc7266654f..ffd33ddcaea 100644
--- a/lib/rules/space-before-blocks.js
+++ b/lib/rules/space-before-blocks.js
@@ -40,7 +40,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing before blocks",
+ description: "Enforce consistent spacing before blocks",
recommended: false,
url: "https://eslint.org/docs/rules/space-before-blocks"
},
diff --git a/lib/rules/space-before-function-paren.js b/lib/rules/space-before-function-paren.js
index fdd45be241d..b56ac3c52c7 100644
--- a/lib/rules/space-before-function-paren.js
+++ b/lib/rules/space-before-function-paren.js
@@ -20,7 +20,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing before `function` definition opening parenthesis",
+ description: "Enforce consistent spacing before `function` definition opening parenthesis",
recommended: false,
url: "https://eslint.org/docs/rules/space-before-function-paren"
},
diff --git a/lib/rules/space-in-parens.js b/lib/rules/space-in-parens.js
index 1509d600f1d..42d9bb58e7e 100644
--- a/lib/rules/space-in-parens.js
+++ b/lib/rules/space-in-parens.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing inside parentheses",
+ description: "Enforce consistent spacing inside parentheses",
recommended: false,
url: "https://eslint.org/docs/rules/space-in-parens"
},
diff --git a/lib/rules/space-infix-ops.js b/lib/rules/space-infix-ops.js
index c526b7e2b0a..141c269df6b 100644
--- a/lib/rules/space-infix-ops.js
+++ b/lib/rules/space-infix-ops.js
@@ -16,7 +16,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require spacing around infix operators",
+ description: "Require spacing around infix operators",
recommended: false,
url: "https://eslint.org/docs/rules/space-infix-ops"
},
diff --git a/lib/rules/space-unary-ops.js b/lib/rules/space-unary-ops.js
index 04487c49e0d..1d9141d2b97 100644
--- a/lib/rules/space-unary-ops.js
+++ b/lib/rules/space-unary-ops.js
@@ -20,7 +20,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce consistent spacing before or after unary operators",
+ description: "Enforce consistent spacing before or after unary operators",
recommended: false,
url: "https://eslint.org/docs/rules/space-unary-ops"
},
diff --git a/lib/rules/spaced-comment.js b/lib/rules/spaced-comment.js
index d858fc47cf8..6aedeae871d 100644
--- a/lib/rules/spaced-comment.js
+++ b/lib/rules/spaced-comment.js
@@ -152,7 +152,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce consistent spacing after the `//` or `/*` in a comment",
+ description: "Enforce consistent spacing after the `//` or `/*` in a comment",
recommended: false,
url: "https://eslint.org/docs/rules/spaced-comment"
},
diff --git a/lib/rules/strict.js b/lib/rules/strict.js
index 0ea1da5677e..e677c95e717 100644
--- a/lib/rules/strict.js
+++ b/lib/rules/strict.js
@@ -69,7 +69,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require or disallow strict mode directives",
+ description: "Require or disallow strict mode directives",
recommended: false,
url: "https://eslint.org/docs/rules/strict"
},
diff --git a/lib/rules/switch-colon-spacing.js b/lib/rules/switch-colon-spacing.js
index cd2ca7018d2..c1df496fd94 100644
--- a/lib/rules/switch-colon-spacing.js
+++ b/lib/rules/switch-colon-spacing.js
@@ -21,7 +21,7 @@ module.exports = {
type: "layout",
docs: {
- description: "enforce spacing around colons of switch statements",
+ description: "Enforce spacing around colons of switch statements",
recommended: false,
url: "https://eslint.org/docs/rules/switch-colon-spacing"
},
diff --git a/lib/rules/symbol-description.js b/lib/rules/symbol-description.js
index 07bb8cd2735..1c8a364986c 100644
--- a/lib/rules/symbol-description.js
+++ b/lib/rules/symbol-description.js
@@ -22,7 +22,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require symbol descriptions",
+ description: "Require symbol descriptions",
recommended: false,
url: "https://eslint.org/docs/rules/symbol-description"
},
diff --git a/lib/rules/template-curly-spacing.js b/lib/rules/template-curly-spacing.js
index c842b76a41f..35d4bbab4d7 100644
--- a/lib/rules/template-curly-spacing.js
+++ b/lib/rules/template-curly-spacing.js
@@ -21,7 +21,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow spacing around embedded expressions of template strings",
+ description: "Require or disallow spacing around embedded expressions of template strings",
recommended: false,
url: "https://eslint.org/docs/rules/template-curly-spacing"
},
diff --git a/lib/rules/template-tag-spacing.js b/lib/rules/template-tag-spacing.js
index fa1a613b894..3140fa0eed7 100644
--- a/lib/rules/template-tag-spacing.js
+++ b/lib/rules/template-tag-spacing.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow spacing between template tags and their literals",
+ description: "Require or disallow spacing between template tags and their literals",
recommended: false,
url: "https://eslint.org/docs/rules/template-tag-spacing"
},
diff --git a/lib/rules/unicode-bom.js b/lib/rules/unicode-bom.js
index d480f1bcdc8..482d3bbf50b 100644
--- a/lib/rules/unicode-bom.js
+++ b/lib/rules/unicode-bom.js
@@ -14,7 +14,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow Unicode byte order mark (BOM)",
+ description: "Require or disallow Unicode byte order mark (BOM)",
recommended: false,
url: "https://eslint.org/docs/rules/unicode-bom"
},
diff --git a/lib/rules/use-isnan.js b/lib/rules/use-isnan.js
index 92903500c18..219d695374e 100644
--- a/lib/rules/use-isnan.js
+++ b/lib/rules/use-isnan.js
@@ -37,7 +37,7 @@ module.exports = {
type: "problem",
docs: {
- description: "require calls to `isNaN()` when checking for `NaN`",
+ description: "Require calls to `isNaN()` when checking for `NaN`",
recommended: true,
url: "https://eslint.org/docs/rules/use-isnan"
},
diff --git a/lib/rules/valid-jsdoc.js b/lib/rules/valid-jsdoc.js
index 8662bf0eae7..25be39fdd51 100644
--- a/lib/rules/valid-jsdoc.js
+++ b/lib/rules/valid-jsdoc.js
@@ -21,7 +21,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "enforce valid JSDoc comments",
+ description: "Enforce valid JSDoc comments",
recommended: false,
url: "https://eslint.org/docs/rules/valid-jsdoc"
},
diff --git a/lib/rules/valid-typeof.js b/lib/rules/valid-typeof.js
index 2286d8926cc..908d5725e22 100644
--- a/lib/rules/valid-typeof.js
+++ b/lib/rules/valid-typeof.js
@@ -14,7 +14,7 @@ module.exports = {
type: "problem",
docs: {
- description: "enforce comparing `typeof` expressions against valid strings",
+ description: "Enforce comparing `typeof` expressions against valid strings",
recommended: true,
url: "https://eslint.org/docs/rules/valid-typeof"
},
diff --git a/lib/rules/vars-on-top.js b/lib/rules/vars-on-top.js
index 09e9932b4ca..99e2b4ac0dd 100644
--- a/lib/rules/vars-on-top.js
+++ b/lib/rules/vars-on-top.js
@@ -15,7 +15,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: "require `var` declarations be placed at the top of their containing scope",
+ description: "Require `var` declarations be placed at the top of their containing scope",
recommended: false,
url: "https://eslint.org/docs/rules/vars-on-top"
},
diff --git a/lib/rules/wrap-iife.js b/lib/rules/wrap-iife.js
index 8523796722a..4c2c9275d87 100644
--- a/lib/rules/wrap-iife.js
+++ b/lib/rules/wrap-iife.js
@@ -43,7 +43,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require parentheses around immediate `function` invocations",
+ description: "Require parentheses around immediate `function` invocations",
recommended: false,
url: "https://eslint.org/docs/rules/wrap-iife"
},
diff --git a/lib/rules/wrap-regex.js b/lib/rules/wrap-regex.js
index b10f2ec53bd..b24d36025ed 100644
--- a/lib/rules/wrap-regex.js
+++ b/lib/rules/wrap-regex.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require parenthesis around regex literals",
+ description: "Require parenthesis around regex literals",
recommended: false,
url: "https://eslint.org/docs/rules/wrap-regex"
},
diff --git a/lib/rules/yield-star-spacing.js b/lib/rules/yield-star-spacing.js
index 884a3a4ed01..c2e07aaaa22 100644
--- a/lib/rules/yield-star-spacing.js
+++ b/lib/rules/yield-star-spacing.js
@@ -15,7 +15,7 @@ module.exports = {
type: "layout",
docs: {
- description: "require or disallow spacing around the `*` in `yield*` expressions",
+ description: "Require or disallow spacing around the `*` in `yield*` expressions",
recommended: false,
url: "https://eslint.org/docs/rules/yield-star-spacing"
},
diff --git a/lib/rules/yoda.js b/lib/rules/yoda.js
index 5b64287a151..eb9a32ad5c3 100644
--- a/lib/rules/yoda.js
+++ b/lib/rules/yoda.js
@@ -121,7 +121,7 @@ module.exports = {
type: "suggestion",
docs: {
- description: 'require or disallow "Yoda" conditions',
+ description: 'Require or disallow "Yoda" conditions',
recommended: false,
url: "https://eslint.org/docs/rules/yoda"
},
diff --git a/lib/shared/deprecation-warnings.js b/lib/shared/deprecation-warnings.js
index 1a0501ab057..d09cafb07fe 100644
--- a/lib/shared/deprecation-warnings.js
+++ b/lib/shared/deprecation-warnings.js
@@ -17,14 +17,7 @@ const path = require("path");
// Definitions for deprecation warnings.
const deprecationWarningMessages = {
ESLINT_LEGACY_ECMAFEATURES:
- "The 'ecmaFeatures' config file property is deprecated and has no effect.",
- ESLINT_PERSONAL_CONFIG_LOAD:
- "'~/.eslintrc.*' config files have been deprecated. " +
- "Please use a config file per project or the '--config' option.",
- ESLINT_PERSONAL_CONFIG_SUPPRESS:
- "'~/.eslintrc.*' config files have been deprecated. " +
- "Please remove it or add 'root:true' to the config files in your " +
- "projects in order to avoid loading '~/.eslintrc.*' accidentally."
+ "The 'ecmaFeatures' config file property is deprecated and has no effect."
};
const sourceFileErrorCache = new Set();
diff --git a/lib/shared/types.js b/lib/shared/types.js
index 0335423f284..5d9a4e6cf26 100644
--- a/lib/shared/types.js
+++ b/lib/shared/types.js
@@ -136,7 +136,6 @@ module.exports = {};
/**
* @typedef {Object} RuleMetaDocs
- * @property {string} category The category of the rule.
* @property {string} description The description of the rule.
* @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset.
* @property {string} url The URL of the rule documentation.
@@ -147,6 +146,7 @@ module.exports = {};
* @property {boolean} [deprecated] If `true` then the rule has been deprecated.
* @property {RuleMetaDocs} docs The document information of the rule.
* @property {"code"|"whitespace"} [fixable] The autofix type.
+ * @property {boolean} [hasSuggestions] If `true` then the rule provides suggestions.
* @property {Record} [messages] The messages the rule reports.
* @property {string[]} [replacedBy] The IDs of the alternative rules.
* @property {Array|Object} schema The option schema of the rule.
diff --git a/lib/unsupported-api.js b/lib/unsupported-api.js
index 110b35a47a4..c1daf54d6ae 100644
--- a/lib/unsupported-api.js
+++ b/lib/unsupported-api.js
@@ -12,6 +12,8 @@
//-----------------------------------------------------------------------------
const { FileEnumerator } = require("./cli-engine/file-enumerator");
+const { FlatESLint } = require("./eslint/flat-eslint");
+const FlatRuleTester = require("./rule-tester/flat-rule-tester");
//-----------------------------------------------------------------------------
// Exports
@@ -19,5 +21,7 @@ const { FileEnumerator } = require("./cli-engine/file-enumerator");
module.exports = {
builtinRules: require("./rules"),
+ FlatESLint,
+ FlatRuleTester,
FileEnumerator
};
diff --git a/package.json b/package.json
index 380ebf6597d..0957c718d88 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "eslint",
- "version": "8.15.0",
+ "version": "8.21.0",
"author": "Nicholas C. Zakas ",
"description": "An AST-based pattern checker for JavaScript.",
"bin": {
@@ -16,7 +16,9 @@
"test": "node Makefile.js test",
"test:cli": "mocha",
"lint": "node Makefile.js lint",
+ "lint:docsjs": "node Makefile.js lintDocsJS",
"fix": "node Makefile.js lint -- fix",
+ "fix:docsjs": "node Makefile.js lintDocsJS -- fix",
"fuzz": "node Makefile.js fuzz",
"generate-release": "node Makefile.js generateRelease",
"generate-alpharelease": "node Makefile.js generatePrerelease -- alpha",
@@ -25,14 +27,20 @@
"publish-release": "node Makefile.js publishRelease",
"gensite": "node Makefile.js gensite",
"webpack": "node Makefile.js webpack",
- "perf": "node Makefile.js perf"
+ "perf": "node Makefile.js perf",
+ "docs:update-links": "node tools/fetch-docs-links.js"
},
"gitHooks": {
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.js": "eslint --fix",
- "*.md": "markdownlint --fix"
+ "*.md": "markdownlint --fix",
+ "docs/src/rules/*.md": [
+ "node tools/fetch-docs-links.js",
+ "git add docs/src/_data/further_reading_links.json"
+ ],
+ "docs/**/*.svg": "npx svgo -r --multipass"
},
"files": [
"LICENSE",
@@ -47,8 +55,9 @@
"homepage": "https://eslint.org",
"bugs": "https://github.com/eslint/eslint/issues/",
"dependencies": {
- "@eslint/eslintrc": "^1.2.3",
- "@humanwhocodes/config-array": "^0.9.2",
+ "@eslint/eslintrc": "^1.3.0",
+ "@humanwhocodes/config-array": "^0.10.4",
+ "@humanwhocodes/gitignore-to-minimatch": "^1.0.2",
"ajv": "^6.10.0",
"chalk": "^4.0.0",
"cross-spawn": "^7.0.2",
@@ -58,14 +67,17 @@
"eslint-scope": "^7.1.1",
"eslint-utils": "^3.0.0",
"eslint-visitor-keys": "^3.3.0",
- "espree": "^9.3.2",
+ "espree": "^9.3.3",
"esquery": "^1.4.0",
"esutils": "^2.0.2",
"fast-deep-equal": "^3.1.3",
"file-entry-cache": "^6.0.1",
+ "find-up": "^5.0.0",
"functional-red-black-tree": "^1.0.1",
"glob-parent": "^6.0.1",
"globals": "^13.15.0",
+ "globby": "^11.1.0",
+ "grapheme-splitter": "^1.0.4",
"ignore": "^5.2.0",
"import-fresh": "^3.0.0",
"imurmurhash": "^0.1.4",
@@ -91,21 +103,23 @@
"cheerio": "^0.22.0",
"common-tags": "^1.8.0",
"core-js": "^3.1.3",
- "dateformat": "^4.5.1",
"ejs": "^3.0.2",
"eslint": "file:.",
"eslint-config-eslint": "file:packages/eslint-config-eslint",
"eslint-plugin-eslint-comments": "^3.2.0",
- "eslint-plugin-eslint-plugin": "^4.2.0",
+ "eslint-plugin-eslint-plugin": "^4.4.0",
"eslint-plugin-internal-rules": "file:tools/internal-rules",
- "eslint-plugin-jsdoc": "^37.0.0",
- "eslint-plugin-node": "^11.1.0",
+ "eslint-plugin-jsdoc": "^38.1.6",
+ "eslint-plugin-n": "^15.2.4",
"eslint-plugin-unicorn": "^42.0.0",
"eslint-release": "^3.2.0",
"eslump": "^3.0.0",
"esprima": "^4.0.1",
+ "fast-glob": "^3.2.11",
"fs-teardown": "^0.1.3",
"glob": "^7.1.6",
+ "got": "^11.8.3",
+ "gray-matter": "^4.0.3",
"jsdoc": "^3.5.5",
"karma": "^6.1.1",
"karma-chrome-launcher": "^3.1.0",
@@ -114,10 +128,16 @@
"karma-webpack": "^5.0.0",
"lint-staged": "^11.0.0",
"load-perf": "^0.2.0",
- "markdownlint": "^0.24.0",
- "markdownlint-cli": "^0.30.0",
+ "markdownlint": "^0.25.1",
+ "markdownlint-cli": "^0.31.1",
"marked": "^4.0.8",
"memfs": "^3.0.1",
+ "metascraper": "^5.25.7",
+ "metascraper-description": "^5.25.7",
+ "metascraper-image": "^5.29.3",
+ "metascraper-logo": "^5.25.7",
+ "metascraper-logo-favicon": "^5.25.7",
+ "metascraper-title": "^5.25.7",
"mocha": "^8.3.2",
"mocha-junit-reporter": "^2.0.0",
"node-polyfill-webpack-plugin": "^1.0.3",
@@ -126,7 +146,7 @@
"pirates": "^4.0.5",
"progress": "^2.0.3",
"proxyquire": "^2.0.1",
- "puppeteer": "^9.1.1",
+ "puppeteer": "^13.7.0",
"recast": "^0.20.4",
"regenerator-runtime": "^0.13.2",
"semver": "^7.3.5",
diff --git a/packages/eslint-config-eslint/README.md b/packages/eslint-config-eslint/README.md
index e79bb5eccf8..ea144120fc4 100644
--- a/packages/eslint-config-eslint/README.md
+++ b/packages/eslint-config-eslint/README.md
@@ -10,11 +10,15 @@ Contains the ESLint configuration used for projects maintained by the ESLint tea
You can install ESLint using npm:
- npm install eslint --save-dev
+```shell
+npm install eslint --save-dev
+```
Then install this configuration:
- npm install eslint-config-eslint --save-dev
+```shell
+npm install eslint-config-eslint --save-dev
+```
## Usage
diff --git a/packages/eslint-config-eslint/default.yml b/packages/eslint-config-eslint/default.yml
index 3985ae2988c..e233e8b01cc 100644
--- a/packages/eslint-config-eslint/default.yml
+++ b/packages/eslint-config-eslint/default.yml
@@ -1,7 +1,7 @@
reportUnusedDisableDirectives: true
extends:
- "eslint:recommended"
- - "plugin:node/recommended"
+ - "plugin:n/recommended"
- "plugin:jsdoc/recommended"
- "plugin:eslint-comments/recommended"
plugins:
@@ -14,11 +14,11 @@ settings:
class: "constructor"
preferredTypes:
"*":
- message: "Use a more precise type or if necessary use `any` or `ArbitraryCallbackResult`"
- replacement: "any"
+ message: "Use a more precise type or if necessary use `any` or `ArbitraryCallbackResult`"
+ replacement: "any"
Any:
- message: "Use a more precise type or if necessary use `any` or `ArbitraryCallbackResult`"
- replacement: "any"
+ message: "Use a more precise type or if necessary use `any` or `ArbitraryCallbackResult`"
+ replacement: "any"
# Function:
# message: "Point to a `@callback` namepath or `GenericCallback` if truly arbitrary in form"
# replacement: "GenericCallback"
@@ -26,13 +26,13 @@ settings:
# message: "Point to a `@callback` namepath or `GenericCallback` if truly arbitrary in form"
# replacement: "GenericCallback"
function:
- message: "Point to a `@callback` namepath or `Function` if truly arbitrary in form"
- replacement: "Function"
+ message: "Point to a `@callback` namepath or `Function` if truly arbitrary in form"
+ replacement: "Function"
Promise:
- message: "Specify the specific Promise type, including, if necessary, the type `any`"
+ message: "Specify the specific Promise type, including, if necessary, the type `any`"
".<>":
- message: "Prefer type form without dot"
- replacement: "<>"
+ message: "Prefer type form without dot"
+ replacement: "<>"
# Object:
# message: "Use the specific object type or `PlainObject` if truly arbitrary"
# replacement: "PlainObject"
@@ -40,8 +40,8 @@ settings:
# message: "Use the specific object type or `PlainObject` if truly arbitrary"
# replacement: "PlainObject"
object:
- message: "Use the specific object type or `Object` if truly arbitrary"
- replacement: "Object"
+ message: "Use the specific object type or `Object` if truly arbitrary"
+ replacement: "Object"
# Array:
# message: "Use the specific array type or `GenericArray` if it is truly arbitrary."
# replacement: "GenericArray"
@@ -56,7 +56,7 @@ rules:
arrow-body-style: ["error", "as-needed"]
arrow-parens: ["error", "as-needed"]
arrow-spacing: "error"
- indent: ["error", 4, {SwitchCase: 1}]
+ indent: ["error", 4, { SwitchCase: 1 }]
block-spacing: "error"
brace-style: ["error", "1tbs"]
camelcase: "error"
@@ -101,9 +101,21 @@ rules:
jsdoc/require-description: ["error", { checkConstructors: false }]
# jsdoc/require-file-overview: "error"
jsdoc/require-hyphen-before-param-description: ["error", "never"]
- jsdoc/require-returns: ["error", { forceRequireReturn: true, forceReturnsWithAsync: true }]
+ jsdoc/require-returns:
+ ["error", { forceRequireReturn: true, forceReturnsWithAsync: true }]
jsdoc/require-throws: "error"
- jsdoc/tag-lines: ["error", "never", { tags: { example: { lines: "always" }, fileoverview: { lines: "any" } } }]
+ jsdoc/tag-lines:
+ [
+ "error",
+ "never",
+ {
+ tags:
+ {
+ example: { lines: "always" },
+ fileoverview: { lines: "any" },
+ },
+ },
+ ]
# jsdoc: disable recommended rules
jsdoc/no-undefined-types: "off"
@@ -120,7 +132,7 @@ rules:
jsdoc/implements-on-classes: "error"
jsdoc/multiline-blocks: "error"
jsdoc/no-multi-asterisks: "error"
- jsdoc/require-jsdoc: ["error", { require: {ClassDeclaration: true} }]
+ jsdoc/require-jsdoc: ["error", { require: { ClassDeclaration: true } }]
jsdoc/require-param: "error"
jsdoc/require-param-description: "error"
jsdoc/require-param-name: "error"
@@ -137,19 +149,28 @@ rules:
key-spacing: ["error", { beforeColon: false, afterColon: true }]
keyword-spacing: "error"
- lines-around-comment: ["error", {
- beforeBlockComment: true,
- afterBlockComment: false,
- beforeLineComment: true,
- afterLineComment: false
- }]
- max-len: ["error", 160, {
- "ignoreComments": true,
- "ignoreUrls": true,
- "ignoreStrings": true,
- "ignoreTemplateLiterals": true,
- "ignoreRegExpLiterals": true
- }]
+ lines-around-comment:
+ [
+ "error",
+ {
+ beforeBlockComment: true,
+ afterBlockComment: false,
+ beforeLineComment: true,
+ afterLineComment: false,
+ },
+ ]
+ max-len:
+ [
+ "error",
+ 160,
+ {
+ "ignoreComments": true,
+ "ignoreUrls": true,
+ "ignoreStrings": true,
+ "ignoreTemplateLiterals": true,
+ "ignoreRegExpLiterals": true,
+ },
+ ]
max-statements-per-line: "error"
new-cap: "error"
new-parens: "error"
@@ -175,7 +196,7 @@ rules:
no-mixed-spaces-and-tabs: ["error", false] # Modified from recommended
no-multi-spaces: "error"
no-multi-str: "error"
- no-multiple-empty-lines: ["error", {max: 2, maxBOF: 0, maxEOF: 0}]
+ no-multiple-empty-lines: ["error", { max: 2, maxBOF: 0, maxEOF: 0 }]
no-nested-ternary: "error"
no-new: "error"
no-new-func: "error"
@@ -185,15 +206,35 @@ rules:
no-param-reassign: "error"
no-proto: "error"
no-process-exit: "off"
- no-restricted-properties: [
- "error",
- { property: "substring", message: "Use .slice instead of .substring." },
- { property: "substr", message: "Use .slice instead of .substr." },
- { object: "assert", property: "equal", message: "Use assert.strictEqual instead of assert.equal." },
- { object: "assert", property: "notEqual", message: "Use assert.notStrictEqual instead of assert.notEqual." },
- { object: "assert", property: "deepEqual", message: "Use assert.deepStrictEqual instead of assert.deepEqual." },
- { object: "assert", property: "notDeepEqual", message: "Use assert.notDeepStrictEqual instead of assert.notDeepEqual." }
- ]
+ no-restricted-properties:
+ [
+ "error",
+ {
+ property: "substring",
+ message: "Use .slice instead of .substring.",
+ },
+ { property: "substr", message: "Use .slice instead of .substr." },
+ {
+ object: "assert",
+ property: "equal",
+ message: "Use assert.strictEqual instead of assert.equal.",
+ },
+ {
+ object: "assert",
+ property: "notEqual",
+ message: "Use assert.notStrictEqual instead of assert.notEqual.",
+ },
+ {
+ object: "assert",
+ property: "deepEqual",
+ message: "Use assert.deepStrictEqual instead of assert.deepEqual.",
+ },
+ {
+ object: "assert",
+ property: "notDeepEqual",
+ message: "Use assert.notDeepStrictEqual instead of assert.notDeepEqual.",
+ },
+ ]
no-return-assign: "error"
no-script-url: "error"
no-self-compare: "error"
@@ -202,15 +243,18 @@ rules:
no-tabs: "error"
no-throw-literal: "error"
no-trailing-spaces: "error"
- no-undef: ["error", {typeof: true}] # Modified from recommended
+ no-undef: ["error", { typeof: true }] # Modified from recommended
no-undef-init: "error"
no-undefined: "error"
- no-underscore-dangle: ["error", {allowAfterThis: true}]
+ no-underscore-dangle: ["error", { allowAfterThis: true }]
no-unmodified-loop-condition: "error"
no-unneeded-ternary: "error"
no-unreachable-loop: "error"
no-unused-expressions: "error"
- no-unused-vars: ["error", {vars: "all", args: "after-used", caughtErrors: "all"}] # Modified from recommended
+ no-unused-vars: [
+ "error",
+ { vars: "all", args: "after-used", caughtErrors: "all" },
+ ] # Modified from recommended
no-use-before-define: "error"
no-useless-call: "error"
no-useless-computed-key: "error"
@@ -221,12 +265,12 @@ rules:
no-whitespace-before-property: "error"
no-var: "error"
- node/callback-return: ["error", ["cb", "callback", "next"]]
- node/handle-callback-err: ["error", "err"]
- node/no-deprecated-api: "error"
- node/no-mixed-requires: "error"
- node/no-new-require: "error"
- node/no-path-concat: "error"
+ n/callback-return: ["error", ["cb", "callback", "next"]]
+ n/handle-callback-err: ["error", "err"]
+ n/no-deprecated-api: "error"
+ n/no-mixed-requires: "error"
+ n/no-new-require: "error"
+ n/no-path-concat: "error"
object-curly-newline: ["error", { "consistent": true, "multiline": true }]
object-curly-spacing: ["error", "always"]
@@ -235,19 +279,16 @@ rules:
one-var-declaration-per-line: "error"
operator-assignment: "error"
operator-linebreak: "error"
- padding-line-between-statements: [
- "error",
- {
- blankLine: "always",
- prev: ["const", "let", "var"],
- next: "*"
- },
- {
- blankLine: "any",
- prev: ["const", "let", "var"],
- next: ["const", "let", "var"]
- }
- ]
+ padding-line-between-statements:
+ [
+ "error",
+ { blankLine: "always", prev: ["const", "let", "var"], next: "*" },
+ {
+ blankLine: "any",
+ prev: ["const", "let", "var"],
+ next: ["const", "let", "var"],
+ },
+ ]
prefer-arrow-callback: "error"
prefer-const: "error"
prefer-exponentiation-operator: "error"
@@ -257,24 +298,24 @@ rules:
prefer-rest-params: "error"
prefer-spread: "error"
prefer-template: "error"
- quotes: ["error", "double", {avoidEscape: true}]
+ quotes: ["error", "double", { avoidEscape: true }]
quote-props: ["error", "as-needed"]
radix: "error"
require-unicode-regexp: "error"
rest-spread-spacing: "error"
semi: "error"
- semi-spacing: ["error", {before: false, after: true}]
+ semi-spacing: ["error", { before: false, after: true }]
semi-style: "error"
space-before-blocks: "error"
- space-before-function-paren: ["error", {
- "anonymous": "never",
- "named": "never",
- "asyncArrow": "always"
- }]
+ space-before-function-paren:
+ [
+ "error",
+ { "anonymous": "never", "named": "never", "asyncArrow": "always" },
+ ]
space-in-parens: "error"
space-infix-ops: "error"
- space-unary-ops: ["error", {words: true, nonwords: false}]
- spaced-comment: ["error", "always", { exceptions: ["-"]}]
+ space-unary-ops: ["error", { words: true, nonwords: false }]
+ spaced-comment: ["error", "always", { exceptions: ["-"] }]
strict: ["error", "global"]
switch-colon-spacing: "error"
symbol-description: "error"
diff --git a/packages/eslint-config-eslint/package.json b/packages/eslint-config-eslint/package.json
index e64f65a7a9b..00c10811fb8 100644
--- a/packages/eslint-config-eslint/package.json
+++ b/packages/eslint-config-eslint/package.json
@@ -21,8 +21,8 @@
"bugs": "https://github.com/eslint/eslint/issues/",
"peerDependencies": {
"eslint-plugin-eslint-comments": ">=3.2.0",
- "eslint-plugin-jsdoc": ">=36.0.6",
- "eslint-plugin-node": ">=11.1.0",
+ "eslint-plugin-jsdoc": ">=38.1.6",
+ "eslint-plugin-n": ">=15.2.4",
"eslint-plugin-unicorn": ">=42.0.0"
},
"keywords": [
diff --git a/templates/blogpost.md.ejs b/templates/blogpost.md.ejs
index 9d01937e80a..2d73ee127fe 100644
--- a/templates/blogpost.md.ejs
+++ b/templates/blogpost.md.ejs
@@ -3,6 +3,9 @@ layout: post
title: ESLint v<%- version %> released
teaser: "We just pushed ESLint v<%- version %>, which is a <%- type %> release upgrade of ESLint. This release <% if (type !== "patch") { %>adds some new features and <% } %>fixes several bugs found in the previous release.<% if (type === "major") { %> This release also has some breaking changes, so please read the following closely.<% } %>"
image: release-notes-<%- type %>.png
+draft: true
+authors:
+ - eslintbot
categories:
- Release Notes
tags:
diff --git a/templates/formatter-examples.md.ejs b/templates/formatter-examples.md.ejs
index 7c41544da2f..6dae9d79002 100644
--- a/templates/formatter-examples.md.ejs
+++ b/templates/formatter-examples.md.ejs
@@ -1,6 +1,12 @@
---
-title: ESLint Formatters
+title: Formatters
layout: doc
+eleventyNavigation:
+ key: formatters
+ parent: user guide
+ title: Formatters
+ order: 5
+edit_link: https://github.com/eslint/eslint/edit/main/templates/formatter-examples.md.ejs
---
ESLint comes with several built-in formatters to control the appearance of the linting results, and supports third-party formatters as well.
@@ -49,10 +55,12 @@ function addOne(i) {
### <%= formatterName %>
<% if (formatterName !== "html") { -%>
-```
-<%- formatterResults[formatterName].result %>
+
+```text
+<%= formatterResults[formatterName].result %>
```
<% } else {-%>
+
<% } -%>
<% }) -%>
diff --git a/tests/_utils/test-lazy-loading-rules.js b/tests/_utils/test-lazy-loading-rules.js
index bac4383242a..34e19869ac7 100644
--- a/tests/_utils/test-lazy-loading-rules.js
+++ b/tests/_utils/test-lazy-loading-rules.js
@@ -62,5 +62,5 @@ addHook(
await eslint.lintFiles([pattern]);
})().catch(({ message, stack }) => {
process.send({ message, stack });
- process.exit(1);
+ process.exit(1); // eslint-disable-line n/no-process-exit -- this is a child process
});
diff --git a/tests/fixtures/cli-engine/deprecated-rule-config/eslint.config.js b/tests/fixtures/cli-engine/deprecated-rule-config/eslint.config.js
new file mode 100644
index 00000000000..eb9b7f0ee06
--- /dev/null
+++ b/tests/fixtures/cli-engine/deprecated-rule-config/eslint.config.js
@@ -0,0 +1,5 @@
+module.exports = {
+ rules: {
+ "indent-legacy": "error"
+ }
+};
diff --git a/tests/fixtures/config-hierarchy/broken/add-conf.js b/tests/fixtures/config-hierarchy/broken/add-conf.js
new file mode 100644
index 00000000000..75c32923a32
--- /dev/null
+++ b/tests/fixtures/config-hierarchy/broken/add-conf.js
@@ -0,0 +1,5 @@
+module.exports = {
+ rules: {
+ semi: [1, "never"]
+ }
+};
diff --git a/tests/fixtures/config-hierarchy/broken/override-conf.js b/tests/fixtures/config-hierarchy/broken/override-conf.js
new file mode 100644
index 00000000000..6287d08ff28
--- /dev/null
+++ b/tests/fixtures/config-hierarchy/broken/override-conf.js
@@ -0,0 +1,5 @@
+module.exports = {
+ rules: {
+ quotes: 0;
+ }
+};
diff --git a/tests/fixtures/configurations/env-browser.js b/tests/fixtures/configurations/env-browser.js
new file mode 100644
index 00000000000..a99c5707d8a
--- /dev/null
+++ b/tests/fixtures/configurations/env-browser.js
@@ -0,0 +1,11 @@
+module.exports = {
+ languageOptions: {
+ globals: {
+ window: false
+ }
+ },
+ rules: {
+ "no-alert": 0,
+ "no-undef": 2
+ }
+};
diff --git a/tests/fixtures/configurations/env-node.js b/tests/fixtures/configurations/env-node.js
new file mode 100644
index 00000000000..27d5fe77de2
--- /dev/null
+++ b/tests/fixtures/configurations/env-node.js
@@ -0,0 +1,13 @@
+module.exports = {
+ languageOptions: {
+ globals: {
+ __dirname: false,
+ console: false
+ },
+ sourceType: "commonjs"
+ },
+ rules: {
+ "no-console": 0,
+ "no-undef": 2
+ }
+};
diff --git a/tests/fixtures/configurations/plugins-with-prefix.js b/tests/fixtures/configurations/plugins-with-prefix.js
new file mode 100644
index 00000000000..42411144b4f
--- /dev/null
+++ b/tests/fixtures/configurations/plugins-with-prefix.js
@@ -0,0 +1,5 @@
+module.exports = {
+ "rules": {
+ "example/example-rule": 1
+ }
+};
diff --git a/tests/fixtures/configurations/processors.js b/tests/fixtures/configurations/processors.js
new file mode 100644
index 00000000000..e8bcce32060
--- /dev/null
+++ b/tests/fixtures/configurations/processors.js
@@ -0,0 +1,12 @@
+module.exports = {
+ "plugins": [
+ "processor",
+ "example"
+ ],
+
+ "rules": {
+ "no-console": 2,
+ "no-unused-vars": 2,
+ "example/example-rule": 1
+ }
+}
diff --git a/tests/fixtures/configurations/quotes-error.js b/tests/fixtures/configurations/quotes-error.js
new file mode 100644
index 00000000000..bbf45f0e817
--- /dev/null
+++ b/tests/fixtures/configurations/quotes-error.js
@@ -0,0 +1,5 @@
+module.exports = {
+ rules: {
+ quotes: [2, "double"]
+ }
+};
diff --git a/tests/fixtures/configurations/semi-error.js b/tests/fixtures/configurations/semi-error.js
new file mode 100644
index 00000000000..2dcc0b196b7
--- /dev/null
+++ b/tests/fixtures/configurations/semi-error.js
@@ -0,0 +1,6 @@
+module.exports = {
+ rules: {
+ semi: 1,
+ strict: 0
+ }
+};
diff --git a/tests/fixtures/eslint.config.js b/tests/fixtures/eslint.config.js
new file mode 100644
index 00000000000..2d9e0848d41
--- /dev/null
+++ b/tests/fixtures/eslint.config.js
@@ -0,0 +1,6 @@
+
+module.exports = {
+ rules: {
+ strict: 0
+ }
+};
diff --git a/tests/fixtures/ignored-paths/.eslintignoreForNegationTest b/tests/fixtures/ignored-paths/.eslintignoreForNegationTest
new file mode 100644
index 00000000000..d1cc10c7d73
--- /dev/null
+++ b/tests/fixtures/ignored-paths/.eslintignoreForNegationTest
@@ -0,0 +1 @@
+undef.js
diff --git a/tests/fixtures/parsers/arrow-parens/identifer-type.js b/tests/fixtures/parsers/arrow-parens/identifier-type.js
similarity index 100%
rename from tests/fixtures/parsers/arrow-parens/identifer-type.js
rename to tests/fixtures/parsers/arrow-parens/identifier-type.js
diff --git a/tests/fixtures/rules/eslint.js b/tests/fixtures/rules/eslint.js
new file mode 100644
index 00000000000..aff3e58062c
--- /dev/null
+++ b/tests/fixtures/rules/eslint.js
@@ -0,0 +1,10 @@
+module.exports = {
+ languageOptions: {
+ "globals": {
+ "test": true
+ }
+ },
+ "rules": {
+ "custom-rule": 1
+ }
+};
diff --git a/tests/fixtures/rules/missing-rule.js b/tests/fixtures/rules/missing-rule.js
new file mode 100644
index 00000000000..39a8c00f17e
--- /dev/null
+++ b/tests/fixtures/rules/missing-rule.js
@@ -0,0 +1,5 @@
+module.exports = {
+ rules: {
+ "missing-rule": 1
+ }
+};
diff --git a/tests/fixtures/testers/rule-tester/modify-ast-at-first.js b/tests/fixtures/testers/rule-tester/modify-ast-at-first.js
index 831d4a06ca7..a7a80f1f16f 100644
--- a/tests/fixtures/testers/rule-tester/modify-ast-at-first.js
+++ b/tests/fixtures/testers/rule-tester/modify-ast-at-first.js
@@ -9,30 +9,36 @@
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- return {
- "Program": function(node) {
- node.body.push({
- "type": "Identifier",
- "name": "modified",
- "range": [0, 8],
- "loc": {
- "start": {
- "line": 1,
- "column": 0
- },
- "end": {
- "line": 1,
- "column": 8
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: []
+ },
+ create(context) {
+ return {
+ "Program": function(node) {
+ node.body.push({
+ "type": "Identifier",
+ "name": "modified",
+ "range": [0, 8],
+ "loc": {
+ "start": {
+ "line": 1,
+ "column": 0
+ },
+ "end": {
+ "line": 1,
+ "column": 8
+ }
}
- }
- });
- },
+ });
+ },
- "Identifier": function(node) {
- if (node.name === "bar") {
- context.report({message: "error", node: node});
+ "Identifier": function(node) {
+ if (node.name === "bar") {
+ context.report({message: "error", node: node});
+ }
}
- }
- };
+ };
+ },
};
diff --git a/tests/fixtures/testers/rule-tester/modify-ast-at-last.js b/tests/fixtures/testers/rule-tester/modify-ast-at-last.js
index f093b191c3c..7c7c0c87939 100644
--- a/tests/fixtures/testers/rule-tester/modify-ast-at-last.js
+++ b/tests/fixtures/testers/rule-tester/modify-ast-at-last.js
@@ -9,30 +9,36 @@
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- return {
- "Program:exit": function(node) {
- node.body.push({
- "type": "Identifier",
- "name": "modified",
- "range": [0, 8],
- "loc": {
- "start": {
- "line": 1,
- "column": 0
- },
- "end": {
- "line": 1,
- "column": 8
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: []
+ },
+ create(context) {
+ return {
+ "Program:exit": function(node) {
+ node.body.push({
+ "type": "Identifier",
+ "name": "modified",
+ "range": [0, 8],
+ "loc": {
+ "start": {
+ "line": 1,
+ "column": 0
+ },
+ "end": {
+ "line": 1,
+ "column": 8
+ }
}
- }
- });
- },
+ });
+ },
- "Identifier": function(node) {
- if (node.name === "bar") {
- context.report({message: "error", node: node});
+ "Identifier": function(node) {
+ if (node.name === "bar") {
+ context.report({message: "error", node: node});
+ }
}
- }
- };
+ };
+ },
};
diff --git a/tests/fixtures/testers/rule-tester/modify-ast.js b/tests/fixtures/testers/rule-tester/modify-ast.js
index 82a7c48ffc5..45f46a662e4 100644
--- a/tests/fixtures/testers/rule-tester/modify-ast.js
+++ b/tests/fixtures/testers/rule-tester/modify-ast.js
@@ -9,14 +9,20 @@
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- return {
- "Identifier": function(node) {
- node.name += "!";
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: []
+ },
+ create(context) {
+ return {
+ "Identifier": function(node) {
+ node.name += "!";
- if (node.name === "bar!") {
- context.report({message: "error", node: node});
+ if (node.name === "bar!") {
+ context.report({message: "error", node: node});
+ }
}
- }
- };
+ };
+ },
};
diff --git a/tests/fixtures/testers/rule-tester/no-eval.js b/tests/fixtures/testers/rule-tester/no-eval.js
index 0d57cb6cd7b..dc6e869888e 100644
--- a/tests/fixtures/testers/rule-tester/no-eval.js
+++ b/tests/fixtures/testers/rule-tester/no-eval.js
@@ -3,20 +3,24 @@
* @author Nicholas C. Zakas
*/
+"use strict";
+
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
-
- "use strict";
-
- return {
- "CallExpression": function(node) {
- if (node.callee.name === "eval") {
- context.report(node, "eval sucks.");
- }
- }
- };
-
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: [],
+ },
+ create(context) {
+ return {
+ CallExpression: function (node) {
+ if (node.callee.name === "eval") {
+ context.report(node, "eval sucks.");
+ }
+ },
+ };
+ },
};
diff --git a/tests/fixtures/testers/rule-tester/no-invalid-args.js b/tests/fixtures/testers/rule-tester/no-invalid-args.js
index 4c2e7015cbb..d1eb2ad7199 100644
--- a/tests/fixtures/testers/rule-tester/no-invalid-args.js
+++ b/tests/fixtures/testers/rule-tester/no-invalid-args.js
@@ -3,20 +3,28 @@
* @author Mathias Schreck
*/
+"use strict";
+
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- "use strict";
-
- var config = context.options[0];
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: [{
+ type: "boolean"
+ }]
+ },
+ create(context) {
+ var config = context.options[0];
- return {
- "Program": function(node) {
- if (config === true) {
- context.report(node, "Invalid args");
+ return {
+ "Program": function(node) {
+ if (config === true) {
+ context.report(node, "Invalid args");
+ }
}
- }
- };
+ };
+ }
};
diff --git a/tests/fixtures/testers/rule-tester/no-invalid-schema.js b/tests/fixtures/testers/rule-tester/no-invalid-schema.js
index fdf290dc62e..affe38053ab 100644
--- a/tests/fixtures/testers/rule-tester/no-invalid-schema.js
+++ b/tests/fixtures/testers/rule-tester/no-invalid-schema.js
@@ -3,26 +3,26 @@
* @author Brandon Mills
*/
+"use strict";
+
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- "use strict";
-
- var config = context.options[0];
-
- return {
- "Program": function(node) {
- if (config) {
- context.report(node, "Expected nothing.");
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: [{
+ "enum": []
+ }]
+ },
+ create(context) {
+ return {
+ "Program": function(node) {
+ if (config) {
+ context.report(node, "Expected nothing.");
+ }
}
- }
- };
+ };
+ },
};
-
-module.exports.schema = [
- {
- "enum": []
- }
-];
diff --git a/tests/fixtures/testers/rule-tester/no-schema-violation.js b/tests/fixtures/testers/rule-tester/no-schema-violation.js
index 2a9f65e2161..7876f25305b 100644
--- a/tests/fixtures/testers/rule-tester/no-schema-violation.js
+++ b/tests/fixtures/testers/rule-tester/no-schema-violation.js
@@ -3,26 +3,27 @@
* @author Brandon Mills
*/
+"use strict";
+
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- "use strict";
-
- var config = context.options[0];
-
- return {
- "Program": function(node) {
- if (config && config !== "foo") {
- context.report(node, "Expected foo.");
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: [{
+ "enum": ["foo"]
+ }]
+ },
+ create(context) {
+ const config = context.options[0];
+ return {
+ "Program": function(node) {
+ if (config && config !== "foo") {
+ context.report(node, "Expected foo.");
+ }
}
- }
- };
+ };
+ },
};
-
-module.exports.schema = [
- {
- "enum": ["foo"]
- }
-];
diff --git a/tests/fixtures/testers/rule-tester/no-test-filename b/tests/fixtures/testers/rule-tester/no-test-filename
index 752c41f0dbf..b3cde257352 100644
--- a/tests/fixtures/testers/rule-tester/no-test-filename
+++ b/tests/fixtures/testers/rule-tester/no-test-filename
@@ -3,18 +3,24 @@
* @author Stefan Lau
*/
+"use strict";
+
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- "use strict";
-
- return {
- "Program": function(node) {
- if (context.getFilename() === '') {
- context.report(node, "Filename test was not defined.");
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: []
+ },
+ create(context) {
+ return {
+ "Program": function(node) {
+ if (context.getFilename() === '') {
+ context.report(node, "Filename test was not defined.");
+ }
}
- }
- };
+ };
+ }
};
diff --git a/tests/fixtures/testers/rule-tester/no-test-global.js b/tests/fixtures/testers/rule-tester/no-test-global.js
index b5fa4c3bf92..6703cc62100 100644
--- a/tests/fixtures/testers/rule-tester/no-test-global.js
+++ b/tests/fixtures/testers/rule-tester/no-test-global.js
@@ -7,21 +7,27 @@
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- "use strict";
+"use strict";
- return {
- "Program": function(node) {
- var globals = context.getScope().variables.map(function (variable) {
- return variable.name;
- });
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: [],
+ },
+ create(context) {
+ return {
+ "Program": function(node) {
+ var globals = context.getScope().variables.map(function (variable) {
+ return variable.name;
+ });
- if (globals.indexOf("test") === -1) {
- context.report(node, "Global variable test was not defined.");
+ if (globals.indexOf("test") === -1) {
+ context.report(node, "Global variable test was not defined.");
+ }
+ if (globals.indexOf("foo") !== -1) {
+ context.report(node, "Global variable foo should not be used.");
+ }
}
- if (globals.indexOf("foo") !== -1) {
- context.report(node, "Global variable foo should not be used.");
- }
- }
- };
+ };
+ },
};
diff --git a/tests/fixtures/testers/rule-tester/no-test-settings.js b/tests/fixtures/testers/rule-tester/no-test-settings.js
index 07ecfa7bca6..a67ebc23ff5 100644
--- a/tests/fixtures/testers/rule-tester/no-test-settings.js
+++ b/tests/fixtures/testers/rule-tester/no-test-settings.js
@@ -3,18 +3,27 @@
* @author Ilya Volodin
*/
+"use strict";
+
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
-module.exports = function(context) {
- "use strict";
-
- return {
- "Program": function(node) {
- if (!context.settings || !context.settings.test) {
- context.report(node, "Global settings test was not defined.");
- }
- }
- };
+module.exports = {
+ meta: {
+ type: "problem",
+ schema: [],
+ },
+ create(context) {
+ return {
+ Program: function (node) {
+ if (!context.settings || !context.settings.test) {
+ context.report(
+ node,
+ "Global settings test was not defined."
+ );
+ }
+ },
+ };
+ },
};
diff --git a/tests/fixtures/testers/rule-tester/no-var.js b/tests/fixtures/testers/rule-tester/no-var.js
index 5841f15bfa1..96a410fe78a 100644
--- a/tests/fixtures/testers/rule-tester/no-var.js
+++ b/tests/fixtures/testers/rule-tester/no-var.js
@@ -10,13 +10,11 @@
"use strict";
module.exports = {
-
meta: {
- fixable: "code"
+ fixable: "code",
+ schema: []
},
-
create(context) {
-
var sourceCode = context.getSourceCode();
return {
diff --git a/tests/lib/cli-engine/cli-engine.js b/tests/lib/cli-engine/cli-engine.js
index b979bd89201..9cd5593c8b3 100644
--- a/tests/lib/cli-engine/cli-engine.js
+++ b/tests/lib/cli-engine/cli-engine.js
@@ -5089,9 +5089,9 @@ describe("CLIEngine", () => {
});
it("should expose the list of plugin rules", () => {
- const engine = new CLIEngine({ plugins: ["node"] });
+ const engine = new CLIEngine({ plugins: ["n"] });
- assert(engine.getRules().has("node/no-deprecated-api"), "node/no-deprecated-api is present");
+ assert(engine.getRules().has("n/no-deprecated-api"), "n/no-deprecated-api is present");
});
it("should expose the list of rules from a preloaded plugin", () => {
@@ -5099,7 +5099,7 @@ describe("CLIEngine", () => {
plugins: ["foo"]
}, {
preloadedPlugins: {
- foo: require("eslint-plugin-node")
+ foo: require("eslint-plugin-n")
}
});
@@ -5336,7 +5336,7 @@ describe("CLIEngine", () => {
});
});
- describe("when retreiving version number", () => {
+ describe("when retrieving version number", () => {
it("should return current version number", () => {
const eslintCLI = require("../../../lib/cli-engine").CLIEngine;
const version = eslintCLI.version;
diff --git a/tests/lib/config/flat-config-array.js b/tests/lib/config/flat-config-array.js
index 8dc45b6e236..bf154ccffe7 100644
--- a/tests/lib/config/flat-config-array.js
+++ b/tests/lib/config/flat-config-array.js
@@ -19,6 +19,7 @@ const recommendedConfig = require("../../../conf/eslint-recommended");
//-----------------------------------------------------------------------------
const baseConfig = {
+ files: ["**/*.js"],
plugins: {
"@": {
rules: {
@@ -77,7 +78,6 @@ const baseConfig = {
*/
function createFlatConfigArray(configs) {
return new FlatConfigArray(configs, {
- basePath: __dirname,
baseConfig: [baseConfig]
});
}
@@ -153,7 +153,6 @@ describe("FlatConfigArray", () => {
};
const configs = new FlatConfigArray([], {
- basePath: __dirname,
baseConfig: base
});
@@ -163,6 +162,7 @@ describe("FlatConfigArray", () => {
it("should not reuse languageOptions.parserOptions across configs", () => {
const base = [{
+ files: ["**/*.js"],
languageOptions: {
parserOptions: {
foo: true
@@ -171,7 +171,6 @@ describe("FlatConfigArray", () => {
}];
const configs = new FlatConfigArray([], {
- basePath: __dirname,
baseConfig: base
});
@@ -185,7 +184,7 @@ describe("FlatConfigArray", () => {
describe("Special configs", () => {
it("eslint:recommended is replaced with an actual config", async () => {
- const configs = new FlatConfigArray(["eslint:recommended"], { basePath: __dirname });
+ const configs = new FlatConfigArray(["eslint:recommended"]);
await configs.normalize();
const config = configs.getConfig("foo.js");
@@ -194,7 +193,7 @@ describe("FlatConfigArray", () => {
});
it("eslint:all is replaced with an actual config", async () => {
- const configs = new FlatConfigArray(["eslint:all"], { basePath: __dirname });
+ const configs = new FlatConfigArray(["eslint:all"]);
await configs.normalize();
const config = configs.getConfig("foo.js");
@@ -1459,7 +1458,7 @@ describe("FlatConfigArray", () => {
},
{
plugins: {
- "foo/baz/boom": {
+ "@foo/baz/boom": {
rules: {
bang: {}
}
@@ -1468,13 +1467,13 @@ describe("FlatConfigArray", () => {
rules: {
foo: ["error"],
bar: 0,
- "foo/baz/boom/bang": "error"
+ "@foo/baz/boom/bang": "error"
}
}
], {
plugins: {
...baseConfig.plugins,
- "foo/baz/boom": {
+ "@foo/baz/boom": {
rules: {
bang: {}
}
@@ -1483,7 +1482,7 @@ describe("FlatConfigArray", () => {
rules: {
foo: [2, "always"],
bar: [0],
- "foo/baz/boom/bang": [2]
+ "@foo/baz/boom/bang": [2]
}
}));
diff --git a/tests/lib/config/flat-config-helpers.js b/tests/lib/config/flat-config-helpers.js
new file mode 100644
index 00000000000..004fb82b13c
--- /dev/null
+++ b/tests/lib/config/flat-config-helpers.js
@@ -0,0 +1,102 @@
+/**
+ * @fileoverview Tests for FlatConfigArray
+ * @author Nicholas C. Zakas
+ */
+
+"use strict";
+
+//-----------------------------------------------------------------------------
+// Requirements
+//-----------------------------------------------------------------------------
+
+const {
+ parseRuleId,
+ getRuleFromConfig
+} = require("../../../lib/config/flat-config-helpers");
+const assert = require("chai").assert;
+
+//-----------------------------------------------------------------------------
+// Tests
+//-----------------------------------------------------------------------------
+
+describe("Config Helpers", () => {
+
+
+ describe("parseRuleId()", () => {
+
+ it("should return plugin name and rule name for core rule", () => {
+ const result = parseRuleId("foo");
+
+ assert.deepStrictEqual(result, {
+ pluginName: "@",
+ ruleName: "foo"
+ });
+ });
+
+ it("should return plugin name and rule name with a/b format", () => {
+ const result = parseRuleId("test/foo");
+
+ assert.deepStrictEqual(result, {
+ pluginName: "test",
+ ruleName: "foo"
+ });
+ });
+
+ it("should return plugin name and rule name with a/b/c format", () => {
+ const result = parseRuleId("node/no-unsupported-features/es-builtins");
+
+ assert.deepStrictEqual(result, {
+ pluginName: "node",
+ ruleName: "no-unsupported-features/es-builtins"
+ });
+ });
+
+ it("should return plugin name and rule name with @a/b/c format", () => {
+ const result = parseRuleId("@test/foo/bar");
+
+ assert.deepStrictEqual(result, {
+ pluginName: "@test/foo",
+ ruleName: "bar"
+ });
+ });
+ });
+
+ describe("getRuleFromConfig", () => {
+ it("should retrieve rule from plugin in config", () => {
+ const rule = {};
+ const config = {
+ plugins: {
+ test: {
+ rules: {
+ one: rule
+ }
+ }
+ }
+ };
+
+ const result = getRuleFromConfig("test/one", config);
+
+ assert.strictEqual(result, rule);
+
+ });
+
+ it("should retrieve rule from core in config", () => {
+ const rule = {};
+ const config = {
+ plugins: {
+ "@": {
+ rules: {
+ semi: rule
+ }
+ }
+ }
+ };
+
+ const result = getRuleFromConfig("semi", config);
+
+ assert.strictEqual(result, rule);
+
+ });
+ });
+
+});
diff --git a/tests/lib/eslint/eslint.config.js b/tests/lib/eslint/eslint.config.js
new file mode 100644
index 00000000000..6b389dc670e
--- /dev/null
+++ b/tests/lib/eslint/eslint.config.js
@@ -0,0 +1,11 @@
+"use strict";
+
+module.exports = {
+ rules: {
+ quotes: 2,
+ "no-var": 2,
+ "eol-last": 2,
+ strict: 2,
+ "no-unused-vars": 2
+ }
+};
diff --git a/tests/lib/eslint/eslint.js b/tests/lib/eslint/eslint.js
index 2cec67fde6b..74f26cfa896 100644
--- a/tests/lib/eslint/eslint.js
+++ b/tests/lib/eslint/eslint.js
@@ -5025,16 +5025,16 @@ describe("ESLint", () => {
});
it("should return multiple rule meta when there are multiple linting errors from a plugin", async () => {
- const nodePlugin = require("eslint-plugin-node");
+ const nodePlugin = require("eslint-plugin-n");
const engine = new ESLint({
useEslintrc: false,
plugins: {
node: nodePlugin
},
overrideConfig: {
- plugins: ["node"],
+ plugins: ["n"],
rules: {
- "node/no-new-require": 2,
+ "n/no-new-require": 2,
semi: 2,
quotes: [2, "double"]
}
@@ -5047,7 +5047,7 @@ describe("ESLint", () => {
assert.strictEqual(rulesMeta.semi, coreRules.get("semi").meta);
assert.strictEqual(rulesMeta.quotes, coreRules.get("quotes").meta);
assert.strictEqual(
- rulesMeta["node/no-new-require"],
+ rulesMeta["n/no-new-require"],
nodePlugin.rules["no-new-require"].meta
);
});
@@ -5212,7 +5212,7 @@ describe("ESLint", () => {
});
});
- describe("when retreiving version number", () => {
+ describe("when retrieving version number", () => {
it("should return current version number", () => {
const eslintCLI = require("../../../lib/eslint").ESLint;
const version = eslintCLI.version;
diff --git a/tests/lib/eslint/flat-eslint.js b/tests/lib/eslint/flat-eslint.js
new file mode 100644
index 00000000000..62f1afd6b8d
--- /dev/null
+++ b/tests/lib/eslint/flat-eslint.js
@@ -0,0 +1,4647 @@
+/**
+ * @fileoverview Tests for the ESLint class.
+ * @author Kai Cataldo
+ * @author Toru Nagashima
+ */
+
+"use strict";
+
+//------------------------------------------------------------------------------
+// Requirements
+//------------------------------------------------------------------------------
+
+const assert = require("assert");
+const fs = require("fs");
+const fsp = fs.promises;
+const os = require("os");
+const path = require("path");
+const escapeStringRegExp = require("escape-string-regexp");
+const fCache = require("file-entry-cache");
+const sinon = require("sinon");
+const proxyquire = require("proxyquire").noCallThru().noPreserveCache();
+const shell = require("shelljs");
+const hash = require("../../../lib/cli-engine/hash");
+const { unIndent, createCustomTeardown } = require("../../_utils");
+const coreRules = require("../../../lib/rules");
+
+//------------------------------------------------------------------------------
+// Tests
+//------------------------------------------------------------------------------
+
+describe("FlatESLint", () => {
+ const examplePluginName = "eslint-plugin-example";
+ const examplePluginNameWithNamespace = "@eslint/eslint-plugin-example";
+ const examplePlugin = {
+ rules: {
+ "example-rule": require("../../fixtures/rules/custom-rule"),
+ "make-syntax-error": require("../../fixtures/rules/make-syntax-error-rule")
+ }
+ };
+ const examplePreprocessorName = "eslint-plugin-processor";
+ const originalDir = process.cwd();
+ const fixtureDir = path.resolve(fs.realpathSync(os.tmpdir()), "eslint/fixtures");
+
+ /** @type {import("../../../lib/flat-eslint").FlatESLint} */
+ let FlatESLint;
+
+ /**
+ * Returns the path inside of the fixture directory.
+ * @param {...string} args file path segments.
+ * @returns {string} The path inside the fixture directory.
+ * @private
+ */
+ function getFixturePath(...args) {
+ const filepath = path.join(fixtureDir, ...args);
+
+ try {
+ return fs.realpathSync(filepath);
+ } catch {
+ return filepath;
+ }
+ }
+
+ /**
+ * Create the ESLint object by mocking some of the plugins
+ * @param {Object} options options for ESLint
+ * @returns {ESLint} engine object
+ * @private
+ */
+ function eslintWithPlugins(options) {
+ return new FlatESLint({
+ ...options,
+ plugins: {
+ [examplePluginName]: examplePlugin,
+ [examplePluginNameWithNamespace]: examplePlugin,
+ [examplePreprocessorName]: require("../../fixtures/processors/custom-processor")
+ }
+ });
+ }
+
+ // copy into clean area so as not to get "infected" by this project's .eslintrc files
+ before(function() {
+
+ /*
+ * GitHub Actions Windows and macOS runners occasionally exhibit
+ * extremely slow filesystem operations, during which copying fixtures
+ * exceeds the default test timeout, so raise it just for this hook.
+ * Mocha uses `this` to set timeouts on an individual hook level.
+ */
+ this.timeout(60 * 1000); // eslint-disable-line no-invalid-this -- Mocha API
+ shell.mkdir("-p", fixtureDir);
+ shell.cp("-r", "./tests/fixtures/.", fixtureDir);
+ });
+
+ beforeEach(() => {
+ ({ FlatESLint } = require("../../../lib/eslint/flat-eslint"));
+ });
+
+ after(() => {
+ shell.rm("-r", fixtureDir);
+ });
+
+ describe("ESLint constructor function", () => {
+ it("the default value of 'options.cwd' should be the current working directory.", async () => {
+ process.chdir(__dirname);
+ try {
+ const engine = new FlatESLint();
+ const results = await engine.lintFiles("eslint.js");
+
+ assert.strictEqual(path.dirname(results[0].filePath), __dirname);
+ } finally {
+ process.chdir(originalDir);
+ }
+ });
+
+ // https://github.com/eslint/eslint/issues/2380
+ it("should not modify baseConfig when format is specified", () => {
+ const customBaseConfig = { root: true };
+
+ new FlatESLint({ baseConfig: customBaseConfig }); // eslint-disable-line no-new -- Check for argument side effects
+
+ assert.deepStrictEqual(customBaseConfig, { root: true });
+ });
+
+ it("should throw readable messages if removed options are present", () => {
+ assert.throws(
+ () => new FlatESLint({
+ cacheFile: "",
+ configFile: "",
+ envs: [],
+ globals: [],
+ ignorePattern: [],
+ parser: "",
+ parserOptions: {},
+ rules: {},
+ plugins: []
+ }),
+ new RegExp(escapeStringRegExp([
+ "Invalid Options:",
+ "- Unknown options: cacheFile, configFile, envs, globals, ignorePattern, parser, parserOptions, rules"
+ ].join("\n")), "u")
+ );
+ });
+
+ it("should throw readable messages if wrong type values are given to options", () => {
+ assert.throws(
+ () => new FlatESLint({
+ allowInlineConfig: "",
+ baseConfig: "",
+ cache: "",
+ cacheLocation: "",
+ cwd: "foo",
+ errorOnUnmatchedPattern: "",
+ extensions: "",
+ fix: "",
+ fixTypes: ["xyz"],
+ globInputPaths: "",
+ ignore: "",
+ ignorePath: "",
+ overrideConfig: "",
+ overrideConfigFile: "",
+ plugins: "",
+ reportUnusedDisableDirectives: ""
+ }),
+ new RegExp(escapeStringRegExp([
+ "Invalid Options:",
+ "- 'allowInlineConfig' must be a boolean.",
+ "- 'baseConfig' must be an object or null.",
+ "- 'cache' must be a boolean.",
+ "- 'cacheLocation' must be a non-empty string.",
+ "- 'cwd' must be an absolute path.",
+ "- 'errorOnUnmatchedPattern' must be a boolean.",
+ "- 'extensions' must be an array of non-empty strings or null.",
+ "- 'fix' must be a boolean or a function.",
+ "- 'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".",
+ "- 'globInputPaths' must be a boolean.",
+ "- 'ignore' must be a boolean.",
+ "- 'ignorePath' must be a non-empty string or null.",
+ "- 'overrideConfig' must be an object or null.",
+ "- 'overrideConfigFile' must be a non-empty string, null, or true.",
+ "- 'plugins' must be an object or null.",
+ "- 'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null."
+ ].join("\n")), "u")
+ );
+ });
+
+ it("should throw readable messages if 'plugins' option contains empty key", () => {
+ assert.throws(
+ () => new FlatESLint({
+ plugins: {
+ "eslint-plugin-foo": {},
+ "eslint-plugin-bar": {},
+ "": {}
+ }
+ }),
+ new RegExp(escapeStringRegExp([
+ "Invalid Options:",
+ "- 'plugins' must not include an empty string."
+ ].join("\n")), "u")
+ );
+ });
+ });
+
+ describe("lintText()", () => {
+ let eslint;
+
+ it("should report the total and per file errors when using local cwd eslint.config.js", async () => {
+ eslint = new FlatESLint({
+ cwd: __dirname
+ });
+
+ const results = await eslint.lintText("var foo = 'bar';");
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 4);
+ assert.strictEqual(results[0].messages[0].ruleId, "no-var");
+ assert.strictEqual(results[0].messages[1].ruleId, "no-unused-vars");
+ assert.strictEqual(results[0].messages[2].ruleId, "quotes");
+ assert.strictEqual(results[0].messages[3].ruleId, "eol-last");
+ assert.strictEqual(results[0].fixableErrorCount, 3);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ assert.strictEqual(results[0].usedDeprecatedRules.length, 0);
+ });
+
+ it("should report the total and per file warnings when using local cwd .eslintrc", async () => {
+ eslint = new FlatESLint({
+ overrideConfig: {
+ rules: {
+ quotes: 1,
+ "no-var": 1,
+ "eol-last": 1,
+ "no-unused-vars": 1
+ }
+ },
+ overrideConfigFile: true
+ });
+ const results = await eslint.lintText("var foo = 'bar';");
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 4);
+ assert.strictEqual(results[0].messages[0].ruleId, "no-var");
+ assert.strictEqual(results[0].messages[1].ruleId, "no-unused-vars");
+ assert.strictEqual(results[0].messages[2].ruleId, "quotes");
+ assert.strictEqual(results[0].messages[3].ruleId, "eol-last");
+ assert.strictEqual(results[0].fixableErrorCount, 0);
+ assert.strictEqual(results[0].fixableWarningCount, 3);
+ assert.strictEqual(results[0].usedDeprecatedRules.length, 0);
+ });
+
+ it("should report one message when using specific config file", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: "fixtures/configurations/quotes-error.js",
+ cwd: getFixturePath("..")
+ });
+ const results = await eslint.lintText("var foo = 'bar';");
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 1);
+ assert.strictEqual(results[0].messages[0].ruleId, "quotes");
+ assert.strictEqual(results[0].messages[0].output, void 0);
+ assert.strictEqual(results[0].errorCount, 1);
+ assert.strictEqual(results[0].fixableErrorCount, 1);
+ assert.strictEqual(results[0].warningCount, 0);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].usedDeprecatedRules.length, 0);
+ });
+
+ it("should report the filename when passed in", async () => {
+ eslint = new FlatESLint({
+ ignore: false,
+ cwd: getFixturePath()
+ });
+ const options = { filePath: "test.js" };
+ const results = await eslint.lintText("var foo = 'bar';", options);
+
+ assert.strictEqual(results[0].filePath, getFixturePath("test.js"));
+ });
+
+ it("should return a warning when given a filename by --stdin-filename in excluded files list if warnIgnored is true", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath(".eslintignore"),
+ cwd: getFixturePath(".."),
+ overrideConfigFile: "fixtures/eslint.config.js"
+ });
+
+ const options = { filePath: "fixtures/passing.js", warnIgnored: true };
+ const results = await eslint.lintText("var bar = foo;", options);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].filePath, getFixturePath("passing.js"));
+ assert.strictEqual(results[0].messages[0].severity, 1);
+ assert.strictEqual(results[0].messages[0].message, "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.");
+ assert.strictEqual(results[0].messages[0].output, void 0);
+ assert.strictEqual(results[0].errorCount, 0);
+ assert.strictEqual(results[0].warningCount, 1);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].fixableErrorCount, 0);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ assert.strictEqual(results[0].usedDeprecatedRules.length, 0);
+ });
+
+ it("should not return a warning when given a filename by --stdin-filename in excluded files list if warnIgnored is false", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath(".eslintignore"),
+ cwd: getFixturePath(".."),
+ overrideConfigFile: "fixtures/eslint.config.js"
+ });
+ const options = {
+ filePath: "fixtures/passing.js",
+ warnIgnored: false
+ };
+
+ // intentional parsing error
+ const results = await eslint.lintText("va r bar = foo;", options);
+
+ // should not report anything because the file is ignored
+ assert.strictEqual(results.length, 0);
+ });
+
+ it("should suppress excluded file warnings by default", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath(".eslintignore"),
+ cwd: getFixturePath(".."),
+ overrideConfigFile: "fixtures/eslint.config.js"
+ });
+ const options = { filePath: "fixtures/passing.js" };
+ const results = await eslint.lintText("var bar = foo;", options);
+
+ // should not report anything because there are no errors
+ assert.strictEqual(results.length, 0);
+ });
+
+ it("should return a message when given a filename by --stdin-filename in excluded files list and ignore is off", async () => {
+ eslint = new FlatESLint({
+ ignorePath: "fixtures/.eslintignore",
+ cwd: getFixturePath(".."),
+ ignore: false,
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ "no-undef": 2
+ }
+ }
+ });
+ const options = { filePath: "fixtures/passing.js" };
+ const results = await eslint.lintText("var bar = foo;", options);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].filePath, getFixturePath("passing.js"));
+ assert.strictEqual(results[0].messages[0].ruleId, "no-undef");
+ assert.strictEqual(results[0].messages[0].severity, 2);
+ assert.strictEqual(results[0].messages[0].output, void 0);
+ });
+
+ it("should return a message and fixed text when in fix mode", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ fix: true,
+ overrideConfig: {
+ rules: {
+ semi: 2
+ }
+ },
+ ignore: false,
+ cwd: getFixturePath()
+ });
+ const options = { filePath: "passing.js" };
+ const results = await eslint.lintText("var bar = foo", options);
+
+ assert.deepStrictEqual(results, [
+ {
+ filePath: getFixturePath("passing.js"),
+ messages: [],
+ errorCount: 0,
+ warningCount: 0,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ output: "var bar = foo;",
+ usedDeprecatedRules: []
+ }
+ ]);
+ });
+
+ it("should return a message and omit fixed text when in fix mode and fixes aren't done", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ fix: true,
+ overrideConfig: {
+ rules: {
+ "no-undef": 2
+ }
+ },
+ ignore: false,
+ cwd: getFixturePath()
+ });
+ const options = { filePath: "passing.js" };
+ const results = await eslint.lintText("var bar = foo", options);
+
+ assert.deepStrictEqual(results, [
+ {
+ filePath: getFixturePath("passing.js"),
+ messages: [
+ {
+ ruleId: "no-undef",
+ severity: 2,
+ messageId: "undef",
+ message: "'foo' is not defined.",
+ line: 1,
+ column: 11,
+ endLine: 1,
+ endColumn: 14,
+ nodeType: "Identifier"
+ }
+ ],
+ errorCount: 1,
+ warningCount: 0,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ source: "var bar = foo",
+ usedDeprecatedRules: []
+ }
+ ]);
+ });
+
+ it("should not delete code if there is a syntax error after trying to autofix.", async () => {
+ eslint = eslintWithPlugins({
+ overrideConfigFile: true,
+ fix: true,
+ overrideConfig: {
+ rules: {
+ "example/make-syntax-error": "error"
+ }
+ },
+ ignore: false,
+ cwd: getFixturePath(".")
+ });
+ const options = { filePath: "test.js" };
+ const results = await eslint.lintText("var bar = foo", options);
+
+ assert.deepStrictEqual(results, [
+ {
+ filePath: getFixturePath("test.js"),
+ messages: [
+ {
+ ruleId: null,
+ fatal: true,
+ severity: 2,
+ message: "Parsing error: Unexpected token is",
+ line: 1,
+ column: 19
+ }
+ ],
+ errorCount: 1,
+ warningCount: 0,
+ fatalErrorCount: 1,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ output: "var bar = foothis is a syntax error.",
+ usedDeprecatedRules: []
+ }
+ ]);
+ });
+
+ it("should not crash even if there are any syntax error since the first time.", async () => {
+ eslint = eslintWithPlugins({
+ overrideConfigFile: true,
+ fix: true,
+ overrideConfig: {
+ rules: {
+ "example/make-syntax-error": "error"
+ }
+ },
+ ignore: false,
+ cwd: getFixturePath()
+ });
+ const options = { filePath: "test.js" };
+ const results = await eslint.lintText("var bar =", options);
+
+ assert.deepStrictEqual(results, [
+ {
+ filePath: getFixturePath("test.js"),
+ messages: [
+ {
+ ruleId: null,
+ fatal: true,
+ severity: 2,
+ message: "Parsing error: Unexpected token",
+ line: 1,
+ column: 10
+ }
+ ],
+ errorCount: 1,
+ warningCount: 0,
+ fatalErrorCount: 1,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ source: "var bar =",
+ usedDeprecatedRules: []
+ }
+ ]);
+ });
+
+ it("should return source code of file in `source` property when errors are present", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: { semi: 2 }
+ }
+ });
+ const results = await eslint.lintText("var foo = 'bar'");
+
+ assert.strictEqual(results[0].source, "var foo = 'bar'");
+ });
+
+ it("should return source code of file in `source` property when warnings are present", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: { semi: 1 }
+ }
+ });
+ const results = await eslint.lintText("var foo = 'bar'");
+
+ assert.strictEqual(results[0].source, "var foo = 'bar'");
+ });
+
+
+ it("should not return a `source` property when no errors or warnings are present", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: { semi: 2 }
+ }
+ });
+ const results = await eslint.lintText("var foo = 'bar';");
+
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[0].source, void 0);
+ });
+
+ it("should not return a `source` property when fixes are applied", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ fix: true,
+ overrideConfig: {
+ rules: {
+ semi: 2,
+ "no-unused-vars": 2
+ }
+ }
+ });
+ const results = await eslint.lintText("var msg = 'hi' + foo\n");
+
+ assert.strictEqual(results[0].source, void 0);
+ assert.strictEqual(results[0].output, "var msg = 'hi' + foo;\n");
+ });
+
+ it("should return a `source` property when a parsing error has occurred", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: { semi: 2 }
+ }
+ });
+ const results = await eslint.lintText("var bar = foothis is a syntax error.\n return bar;");
+
+ assert.deepStrictEqual(results, [
+ {
+ filePath: "",
+ messages: [
+ {
+ ruleId: null,
+ fatal: true,
+ severity: 2,
+ message: "Parsing error: Unexpected token is",
+ line: 1,
+ column: 19
+ }
+ ],
+ errorCount: 1,
+ warningCount: 0,
+ fatalErrorCount: 1,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ source: "var bar = foothis is a syntax error.\n return bar;",
+ usedDeprecatedRules: []
+ }
+ ]);
+ });
+
+ // https://github.com/eslint/eslint/issues/5547
+ it("should respect default ignore rules (ignoring node_modules), even with --no-ignore", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath(),
+ ignore: false
+ });
+ const results = await eslint.lintText("var bar = foo;", { filePath: "node_modules/passing.js", warnIgnored: true });
+ const expectedMsg = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].filePath, getFixturePath("node_modules/passing.js"));
+ assert.strictEqual(results[0].messages[0].message, expectedMsg);
+ });
+
+ it("should warn when deprecated rules are found in a config", async () => {
+ eslint = new FlatESLint({
+ cwd: originalDir,
+ overrideConfigFile: "tests/fixtures/cli-engine/deprecated-rule-config/eslint.config.js"
+ });
+ const [result] = await eslint.lintText("foo");
+
+ assert.deepStrictEqual(
+ result.usedDeprecatedRules,
+ [{ ruleId: "indent-legacy", replacedBy: ["indent"] }]
+ );
+ });
+
+ it("should throw if non-string value is given to 'code' parameter", async () => {
+ eslint = new FlatESLint();
+ await assert.rejects(() => eslint.lintText(100), /'code' must be a string/u);
+ });
+
+ it("should throw if non-object value is given to 'options' parameter", async () => {
+ eslint = new FlatESLint();
+ await assert.rejects(() => eslint.lintText("var a = 0", "foo.js"), /'options' must be an object, null, or undefined/u);
+ });
+
+ it("should throw if 'options' argument contains unknown key", async () => {
+ eslint = new FlatESLint();
+ await assert.rejects(() => eslint.lintText("var a = 0", { filename: "foo.js" }), /'options' must not include the unknown option\(s\): filename/u);
+ });
+
+ it("should throw if non-string value is given to 'options.filePath' option", async () => {
+ eslint = new FlatESLint();
+ await assert.rejects(() => eslint.lintText("var a = 0", { filePath: "" }), /'options.filePath' must be a non-empty string or undefined/u);
+ });
+
+ it("should throw if non-boolean value is given to 'options.warnIgnored' option", async () => {
+ eslint = new FlatESLint();
+ await assert.rejects(() => eslint.lintText("var a = 0", { warnIgnored: "" }), /'options.warnIgnored' must be a boolean or undefined/u);
+ });
+ });
+
+ describe("lintFiles()", () => {
+
+ /** @type {InstanceType} */
+ let eslint;
+
+ it("should use correct parser when custom parser is specified", async () => {
+ const filePath = path.resolve(__dirname, "../../fixtures/configurations/parser/custom.js");
+
+ eslint = new FlatESLint({
+ cwd: originalDir,
+ ignore: false,
+ overrideConfigFile: true,
+ overrideConfig: {
+ languageOptions: {
+ parser: require(filePath)
+ }
+ }
+ });
+
+ const results = await eslint.lintFiles([filePath]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 1);
+ assert.strictEqual(results[0].messages[0].message, "Parsing error: Boom!");
+ });
+
+ it("should report zero messages when given a config file and a valid file", async () => {
+ eslint = new FlatESLint({
+ cwd: originalDir,
+ overrideConfigFile: "eslint.config.js"
+ });
+ const results = await eslint.lintFiles(["lib/**/cli*.js"]);
+
+ assert.strictEqual(results.length, 2);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[1].messages.length, 0);
+ });
+
+ it("should handle multiple patterns with overlapping files", async () => {
+ eslint = new FlatESLint({
+ cwd: originalDir,
+ overrideConfigFile: "eslint.config.js"
+ });
+ const results = await eslint.lintFiles(["lib/**/cli*.js", "lib/cli.?s", "lib/{cli,cli-engine/cli-engine}.js"]);
+
+ assert.strictEqual(results.length, 2);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[1].messages.length, 0);
+ });
+
+ it("should report zero messages when given a config file and a valid file and espree as parser", async () => {
+ eslint = new FlatESLint({
+ overrideConfig: {
+ languageOptions: {
+ parser: require("espree"),
+ parserOptions: {
+ ecmaVersion: 2021
+ }
+ }
+ },
+ overrideConfigFile: true
+ });
+ const results = await eslint.lintFiles(["lib/cli.js"]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0);
+ });
+
+ it("should report zero messages when given a config file and a valid file and esprima as parser", async () => {
+ eslint = new FlatESLint({
+ overrideConfig: {
+ languageOptions: {
+ parser: require("esprima")
+ }
+ },
+ overrideConfigFile: true,
+ ignore: false
+ });
+ const results = await eslint.lintFiles(["tests/fixtures/passing.js"]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0);
+ });
+
+ it("should throw an error when given a config file and a valid file and invalid parser", async () => {
+ eslint = new FlatESLint({
+ overrideConfig: {
+ languageOptions: {
+ parser: "test11"
+ }
+ },
+ overrideConfigFile: true
+ });
+
+ await assert.rejects(async () => await eslint.lintFiles(["lib/cli.js"]), /Expected string in the form "pluginName\/objectName" but found "test11"/u);
+ });
+
+ it("should report zero messages when given a directory with a .js2 file", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ extensions: [".js2"],
+ overrideConfigFile: getFixturePath("eslint.config.js")
+ });
+ const results = await eslint.lintFiles([getFixturePath("files/foo.js2")]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0);
+ });
+
+ it("should fall back to defaults when extensions is set to an empty array", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath(),
+ overrideConfigFile: true,
+ ignore: false,
+ overrideConfig: {
+ rules: {
+ quotes: ["error", "double"]
+ }
+ },
+ extensions: []
+ });
+
+ const results = await eslint.lintFiles([getFixturePath("single-quoted.js")]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 1);
+ assert.strictEqual(results[0].messages[0].ruleId, "quotes");
+ assert.strictEqual(results[0].messages[0].severity, 2);
+ assert.strictEqual(results[0].errorCount, 1);
+ assert.strictEqual(results[0].warningCount, 0);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].fixableErrorCount, 1);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ });
+
+ it("should report zero messages when given a directory with a .js and a .js2 file", async () => {
+ eslint = new FlatESLint({
+ extensions: [".js", ".js2"],
+ ignore: false,
+ cwd: getFixturePath(".."),
+ overrideConfigFile: getFixturePath("eslint.config.js")
+ });
+ const results = await eslint.lintFiles(["fixtures/files/"]);
+
+ assert.strictEqual(results.length, 2);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[1].messages.length, 0);
+ });
+
+ it("should report zero messages when given a '**' pattern with a .js and a .js2 file", async () => {
+ eslint = new FlatESLint({
+ extensions: [".js", ".js2"],
+ ignore: false,
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: getFixturePath("eslint.config.js")
+
+ });
+ const results = await eslint.lintFiles(["fixtures/files/*"]);
+
+ assert.strictEqual(results.length, 2);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[1].messages.length, 0);
+ });
+
+ it("should resolve globs when 'globInputPaths' option is true", async () => {
+ eslint = new FlatESLint({
+ extensions: [".js", ".js2"],
+ ignore: false,
+ cwd: getFixturePath(".."),
+ overrideConfigFile: getFixturePath("eslint.config.js")
+
+ });
+ const results = await eslint.lintFiles(["fixtures/files/*"]);
+
+ assert.strictEqual(results.length, 2);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[1].messages.length, 0);
+ });
+
+ it("should not resolve globs when 'globInputPaths' option is false", async () => {
+ eslint = new FlatESLint({
+ extensions: [".js", ".js2"],
+ ignore: false,
+ cwd: getFixturePath(".."),
+ overrideConfigFile: true,
+ globInputPaths: false
+ });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["fixtures/files/*"]);
+ }, /No files matching 'fixtures\/files\/\*' were found \(glob was disabled\)\./u);
+ });
+
+ describe("Ignoring Files", () => {
+
+ it("should report on all files passed explicitly, even if ignored by default", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath("cli-engine")
+ });
+ const results = await eslint.lintFiles(["node_modules/foo.js"]);
+ const expectedMsg = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.";
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].errorCount, 0);
+ assert.strictEqual(results[0].warningCount, 1);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].fixableErrorCount, 0);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ assert.strictEqual(results[0].messages[0].message, expectedMsg);
+ });
+
+ it("should report on globs with explicit inclusion of dotfiles", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath("cli-engine"),
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ quotes: [2, "single"]
+ }
+ }
+ });
+ const results = await eslint.lintFiles(["hidden/.hiddenfolder/*.js"]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].errorCount, 1);
+ assert.strictEqual(results[0].warningCount, 0);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].fixableErrorCount, 1);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ });
+
+ it("should ignore node_modules files when using ignore file", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath("cli-engine"),
+ overrideConfigFile: true
+ });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["node_modules"]);
+ }, /All files matched by 'node_modules\/\*\*\/\*.js' are ignored\./u);
+ });
+
+ // https://github.com/eslint/eslint/issues/5547
+ it("should ignore node_modules files even with ignore: false", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath("cli-engine"),
+ ignore: false
+ });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["node_modules"]);
+ }, /All files matched by 'node_modules\/\*\*\/\*\.js' are ignored\./u);
+ });
+
+ it("should throw an error when given a directory with all eslint excluded files in the directory", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath(".eslintignore")
+ });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles([getFixturePath("./cli-engine/")]);
+ }, /All files matched by '.*?cli-engine[\\/]\*\*[\\/]\*\.js' are ignored/u);
+ });
+
+ it("should throw an error when all given files are ignored", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath(".eslintignore")
+ });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["tests/fixtures/cli-engine/"]);
+ }, /All files matched by 'tests\/fixtures\/cli-engine\/\*\*\/\*\.js' are ignored\./u);
+ });
+
+ it("should throw an error when all given files are ignored even with a `./` prefix", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath(".eslintignore")
+ });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["./tests/fixtures/cli-engine/"]);
+ }, /All files matched by 'tests\/fixtures\/cli-engine\/\*\*\/\*\.js' are ignored\./u);
+ });
+
+ // https://github.com/eslint/eslint/issues/3788
+ it("should ignore one-level down node_modules when ignore file has 'node_modules/' in it", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath("cli-engine", "nested_node_modules", ".eslintignore"),
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ quotes: [2, "double"]
+ }
+ },
+ cwd: getFixturePath("cli-engine", "nested_node_modules")
+ });
+ const results = await eslint.lintFiles(["."]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].errorCount, 0);
+ assert.strictEqual(results[0].warningCount, 0);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].fixableErrorCount, 0);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ });
+
+ // https://github.com/eslint/eslint/issues/3812
+ it("should ignore all files and throw an error when fixtures/ is in ignore file", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath("cli-engine/.eslintignore2"),
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ quotes: [2, "double"]
+ }
+ }
+ });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["./tests/fixtures/cli-engine/"]);
+ }, /All files matched by 'tests\/fixtures\/cli-engine\/\*\*\/\*\.js' are ignored\./u);
+ });
+
+ it("should throw an error when all given files are ignored via ignore-pattern", async () => {
+ eslint = new FlatESLint({
+ overrideConfig: {
+ ignorePatterns: "tests/fixtures/single-quoted.js"
+ }
+ });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["tests/fixtures/*-quoted.js"]);
+ }, /All files matched by 'tests\/fixtures\/\*-quoted\.js' are ignored\./u);
+ });
+
+ it("should return a warning when an explicitly given file is ignored", async () => {
+ eslint = new FlatESLint({
+ ignorePath: getFixturePath(".eslintignore"),
+ cwd: getFixturePath()
+ });
+ const filePath = getFixturePath("passing.js");
+ const results = await eslint.lintFiles([filePath]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].filePath, filePath);
+ assert.strictEqual(results[0].messages[0].severity, 1);
+ assert.strictEqual(results[0].messages[0].message, "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.");
+ assert.strictEqual(results[0].errorCount, 0);
+ assert.strictEqual(results[0].warningCount, 1);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].fixableErrorCount, 0);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ });
+
+ it("should return two messages when given a file in excluded files list while ignore is off", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath(),
+ ignorePath: getFixturePath(".eslintignore"),
+ ignore: false,
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ "no-undef": 2
+ }
+ }
+ });
+ const filePath = fs.realpathSync(getFixturePath("undef.js"));
+ const results = await eslint.lintFiles([filePath]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].filePath, filePath);
+ assert.strictEqual(results[0].messages[0].ruleId, "no-undef");
+ assert.strictEqual(results[0].messages[0].severity, 2);
+ assert.strictEqual(results[0].messages[1].ruleId, "no-undef");
+ assert.strictEqual(results[0].messages[1].severity, 2);
+ });
+ });
+
+
+ it("should report zero messages when given a pattern with a .js and a .js2 file", async () => {
+ eslint = new FlatESLint({
+ extensions: [".js", ".js2"],
+ ignore: false,
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true
+ });
+ const results = await eslint.lintFiles(["fixtures/files/*.?s*"]);
+
+ assert.strictEqual(results.length, 2);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[1].messages.length, 0);
+ });
+
+ it("should return one error message when given a config with rules with options and severity level set to error", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath(),
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ quotes: ["error", "double"]
+ }
+ },
+ ignore: false
+ });
+ const results = await eslint.lintFiles([getFixturePath("single-quoted.js")]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 1);
+ assert.strictEqual(results[0].messages[0].ruleId, "quotes");
+ assert.strictEqual(results[0].messages[0].severity, 2);
+ assert.strictEqual(results[0].errorCount, 1);
+ assert.strictEqual(results[0].warningCount, 0);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].fixableErrorCount, 1);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ });
+
+ it("should return 5 results when given a config and a directory of 5 valid files", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ semi: 1,
+ strict: 0
+ }
+ }
+ });
+
+ const formattersDir = getFixturePath("formatters");
+ const results = await eslint.lintFiles([formattersDir]);
+
+ assert.strictEqual(results.length, 5);
+ assert.strictEqual(path.relative(formattersDir, results[0].filePath), "async.js");
+ assert.strictEqual(results[0].errorCount, 0);
+ assert.strictEqual(results[0].warningCount, 0);
+ assert.strictEqual(results[0].fatalErrorCount, 0);
+ assert.strictEqual(results[0].fixableErrorCount, 0);
+ assert.strictEqual(results[0].fixableWarningCount, 0);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(path.relative(formattersDir, results[1].filePath), "broken.js");
+ assert.strictEqual(results[1].errorCount, 0);
+ assert.strictEqual(results[1].warningCount, 0);
+ assert.strictEqual(results[1].fatalErrorCount, 0);
+ assert.strictEqual(results[1].fixableErrorCount, 0);
+ assert.strictEqual(results[1].fixableWarningCount, 0);
+ assert.strictEqual(results[1].messages.length, 0);
+ assert.strictEqual(path.relative(formattersDir, results[2].filePath), "cwd.js");
+ assert.strictEqual(results[2].errorCount, 0);
+ assert.strictEqual(results[2].warningCount, 0);
+ assert.strictEqual(results[2].fatalErrorCount, 0);
+ assert.strictEqual(results[2].fixableErrorCount, 0);
+ assert.strictEqual(results[2].fixableWarningCount, 0);
+ assert.strictEqual(results[2].messages.length, 0);
+ assert.strictEqual(path.relative(formattersDir, results[3].filePath), "simple.js");
+ assert.strictEqual(results[3].errorCount, 0);
+ assert.strictEqual(results[3].warningCount, 0);
+ assert.strictEqual(results[3].fatalErrorCount, 0);
+ assert.strictEqual(results[3].fixableErrorCount, 0);
+ assert.strictEqual(results[3].fixableWarningCount, 0);
+ assert.strictEqual(results[3].messages.length, 0);
+ assert.strictEqual(path.relative(formattersDir, results[4].filePath), path.join("test", "simple.js"));
+ assert.strictEqual(results[4].errorCount, 0);
+ assert.strictEqual(results[4].warningCount, 0);
+ assert.strictEqual(results[4].fatalErrorCount, 0);
+ assert.strictEqual(results[4].fixableErrorCount, 0);
+ assert.strictEqual(results[4].fixableWarningCount, 0);
+ assert.strictEqual(results[4].messages.length, 0);
+ });
+
+ it("should return zero messages when given a config with browser globals", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: getFixturePath("configurations", "env-browser.js")
+ });
+ const results = await eslint.lintFiles([fs.realpathSync(getFixturePath("globals-browser.js"))]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0, "Should have no messages.");
+ });
+
+ it("should return zero messages when given an option to add browser globals", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ overrideConfig: {
+ languageOptions: {
+ globals: {
+ window: false
+ }
+ },
+ rules: {
+ "no-alert": 0,
+ "no-undef": 2
+ }
+ }
+ });
+ const results = await eslint.lintFiles([fs.realpathSync(getFixturePath("globals-browser.js"))]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0);
+ });
+
+ it("should return zero messages when given a config with sourceType set to commonjs and Node.js globals", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: getFixturePath("configurations", "env-node.js")
+ });
+ const results = await eslint.lintFiles([fs.realpathSync(getFixturePath("globals-node.js"))]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0, "Should have no messages.");
+ });
+
+ it("should not return results from previous call when calling more than once", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: getFixturePath("eslint.config.js"),
+ ignore: false,
+ overrideConfig: {
+ rules: {
+ semi: 2
+ }
+ }
+ });
+ const failFilePath = fs.realpathSync(getFixturePath("missing-semicolon.js"));
+ const passFilePath = fs.realpathSync(getFixturePath("passing.js"));
+
+ let results = await eslint.lintFiles([failFilePath]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].filePath, failFilePath);
+ assert.strictEqual(results[0].messages.length, 1);
+ assert.strictEqual(results[0].messages[0].ruleId, "semi");
+ assert.strictEqual(results[0].messages[0].severity, 2);
+
+ results = await eslint.lintFiles([passFilePath]);
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].filePath, passFilePath);
+ assert.strictEqual(results[0].messages.length, 0);
+ });
+
+ it("should return zero messages when executing a file with a shebang", async () => {
+ eslint = new FlatESLint({
+ ignore: false,
+ cwd: getFixturePath(),
+ overrideConfigFile: getFixturePath("eslint.config.js")
+ });
+ const results = await eslint.lintFiles([getFixturePath("shebang.js")]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0, "Should have lint messages.");
+ });
+
+ it("should return zero messages when executing without a config file", async () => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath(),
+ ignore: false,
+ overrideConfigFile: true
+ });
+ const filePath = fs.realpathSync(getFixturePath("missing-semicolon.js"));
+ const results = await eslint.lintFiles([filePath]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].filePath, filePath);
+ assert.strictEqual(results[0].messages.length, 0);
+ });
+
+ // working
+ describe("Deprecated Rules", () => {
+
+ it("should warn when deprecated rules are configured", async () => {
+ eslint = new FlatESLint({
+ cwd: originalDir,
+ overrideConfig: {
+ rules: {
+ "indent-legacy": 1,
+ "require-jsdoc": 1,
+ "valid-jsdoc": 1
+ }
+ }
+ });
+ const results = await eslint.lintFiles(["lib/cli*.js"]);
+
+ assert.deepStrictEqual(
+ results[0].usedDeprecatedRules,
+ [
+ { ruleId: "indent-legacy", replacedBy: ["indent"] },
+ { ruleId: "require-jsdoc", replacedBy: [] },
+ { ruleId: "valid-jsdoc", replacedBy: [] }
+ ]
+ );
+ });
+
+ it("should not warn when deprecated rules are not configured", async () => {
+ eslint = new FlatESLint({
+ cwd: originalDir,
+ overrideConfig: {
+ rules: { indent: 1, "valid-jsdoc": 0, "require-jsdoc": 0 }
+ }
+ });
+ const results = await eslint.lintFiles(["lib/cli*.js"]);
+
+ assert.deepStrictEqual(results[0].usedDeprecatedRules, []);
+ });
+
+ it("should warn when deprecated rules are found in a config", async () => {
+ eslint = new FlatESLint({
+ cwd: originalDir,
+ overrideConfigFile: "tests/fixtures/cli-engine/deprecated-rule-config/eslint.config.js"
+ });
+ const results = await eslint.lintFiles(["lib/cli*.js"]);
+
+ assert.deepStrictEqual(
+ results[0].usedDeprecatedRules,
+ [{ ruleId: "indent-legacy", replacedBy: ["indent"] }]
+ );
+ });
+ });
+
+ // working
+ describe("Fix Mode", () => {
+
+ it("correctly autofixes semicolon-conflicting-fixes", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ fix: true
+ });
+ const inputPath = getFixturePath("autofix/semicolon-conflicting-fixes.js");
+ const outputPath = getFixturePath("autofix/semicolon-conflicting-fixes.expected.js");
+ const results = await eslint.lintFiles([inputPath]);
+ const expectedOutput = fs.readFileSync(outputPath, "utf8");
+
+ assert.strictEqual(results[0].output, expectedOutput);
+ });
+
+ it("correctly autofixes return-conflicting-fixes", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ fix: true
+ });
+ const inputPath = getFixturePath("autofix/return-conflicting-fixes.js");
+ const outputPath = getFixturePath("autofix/return-conflicting-fixes.expected.js");
+ const results = await eslint.lintFiles([inputPath]);
+ const expectedOutput = fs.readFileSync(outputPath, "utf8");
+
+ assert.strictEqual(results[0].output, expectedOutput);
+ });
+
+ it("should return fixed text on multiple files when in fix mode", async () => {
+
+ /**
+ * Converts CRLF to LF in output.
+ * This is a workaround for git's autocrlf option on Windows.
+ * @param {Object} result A result object to convert.
+ * @returns {void}
+ */
+ function convertCRLF(result) {
+ if (result && result.output) {
+ result.output = result.output.replace(/\r\n/gu, "\n");
+ }
+ }
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ fix: true,
+ overrideConfig: {
+ rules: {
+ semi: 2,
+ quotes: [2, "double"],
+ eqeqeq: 2,
+ "no-undef": 2,
+ "space-infix-ops": 2
+ }
+ }
+ });
+ const results = await eslint.lintFiles([path.resolve(fixtureDir, `${fixtureDir}/fixmode`)]);
+
+ results.forEach(convertCRLF);
+ assert.deepStrictEqual(results, [
+ {
+ filePath: fs.realpathSync(path.resolve(fixtureDir, "fixmode/multipass.js")),
+ messages: [],
+ errorCount: 0,
+ warningCount: 0,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ output: "true ? \"yes\" : \"no\";\n",
+ usedDeprecatedRules: []
+ },
+ {
+ filePath: fs.realpathSync(path.resolve(fixtureDir, "fixmode/ok.js")),
+ messages: [],
+ errorCount: 0,
+ warningCount: 0,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ usedDeprecatedRules: []
+ },
+ {
+ filePath: fs.realpathSync(path.resolve(fixtureDir, "fixmode/quotes-semi-eqeqeq.js")),
+ messages: [
+ {
+ column: 9,
+ line: 2,
+ endColumn: 11,
+ endLine: 2,
+ message: "Expected '===' and instead saw '=='.",
+ messageId: "unexpected",
+ nodeType: "BinaryExpression",
+ ruleId: "eqeqeq",
+ severity: 2
+ }
+ ],
+ errorCount: 1,
+ warningCount: 0,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ output: "var msg = \"hi\";\nif (msg == \"hi\") {\n\n}\n",
+ usedDeprecatedRules: []
+ },
+ {
+ filePath: fs.realpathSync(path.resolve(fixtureDir, "fixmode/quotes.js")),
+ messages: [
+ {
+ column: 18,
+ line: 1,
+ endColumn: 21,
+ endLine: 1,
+ messageId: "undef",
+ message: "'foo' is not defined.",
+ nodeType: "Identifier",
+ ruleId: "no-undef",
+ severity: 2
+ }
+ ],
+ errorCount: 1,
+ warningCount: 0,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ output: "var msg = \"hi\" + foo;\n",
+ usedDeprecatedRules: []
+ }
+ ]);
+ });
+
+ // Cannot be run properly until cache is implemented
+ xit("should run autofix even if files are cached without autofix results", async () => {
+ const baseOptions = {
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ semi: 2,
+ quotes: [2, "double"],
+ eqeqeq: 2,
+ "no-undef": 2,
+ "space-infix-ops": 2
+ }
+ }
+ };
+
+ eslint = new FlatESLint(Object.assign({}, baseOptions, { cache: true, fix: false }));
+
+ // Do initial lint run and populate the cache file
+ await eslint.lintFiles([path.resolve(fixtureDir, `${fixtureDir}/fixmode`)]);
+
+ eslint = new FlatESLint(Object.assign({}, baseOptions, { cache: true, fix: true }));
+ const results = await eslint.lintFiles([path.resolve(fixtureDir, `${fixtureDir}/fixmode`)]);
+
+ assert(results.some(result => result.output));
+ });
+ });
+
+ describe("plugins", () => {
+ it("should return two messages when executing with config file that specifies a plugin", async () => {
+ eslint = eslintWithPlugins({
+ cwd: path.resolve(fixtureDir, ".."),
+ overrideConfigFile: getFixturePath("configurations", "plugins-with-prefix.js")
+ });
+ const results = await eslint.lintFiles([fs.realpathSync(getFixturePath("rules", "test/test-custom-rule.js"))]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 2, "Expected two messages.");
+ assert.strictEqual(results[0].messages[0].ruleId, "example/example-rule");
+ });
+
+ it("should return two messages when executing with cli option that specifies a plugin", async () => {
+ eslint = eslintWithPlugins({
+ cwd: path.resolve(fixtureDir, ".."),
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: { "example/example-rule": 1 }
+ }
+ });
+ const results = await eslint.lintFiles([fs.realpathSync(getFixturePath("rules", "test", "test-custom-rule.js"))]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 2);
+ assert.strictEqual(results[0].messages[0].ruleId, "example/example-rule");
+ });
+
+ it("should return two messages when executing with cli option that specifies preloaded plugin", async () => {
+ eslint = new FlatESLint({
+ cwd: path.resolve(fixtureDir, ".."),
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: { "test/example-rule": 1 }
+ },
+ plugins: {
+ "eslint-plugin-test": { rules: { "example-rule": require("../../fixtures/rules/custom-rule") } }
+ }
+ });
+ const results = await eslint.lintFiles([fs.realpathSync(getFixturePath("rules", "test", "test-custom-rule.js"))]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 2);
+ assert.strictEqual(results[0].messages[0].ruleId, "test/example-rule");
+ });
+ });
+
+ xdescribe("cache", () => {
+
+ /**
+ * helper method to delete a file without caring about exceptions
+ * @param {string} filePath The file path
+ * @returns {void}
+ */
+ function doDelete(filePath) {
+ try {
+ fs.unlinkSync(filePath);
+ } catch {
+
+ /*
+ * we don't care if the file didn't exist, since our
+ * intention was to remove the file
+ */
+ }
+ }
+
+ /**
+ * helper method to delete the cache files created during testing
+ * @returns {void}
+ */
+ function deleteCache() {
+ doDelete(path.resolve(".eslintcache"));
+ doDelete(path.resolve(".cache/custom-cache"));
+ }
+
+ beforeEach(() => {
+ deleteCache();
+ });
+
+ afterEach(() => {
+ sinon.restore();
+ deleteCache();
+ });
+
+ describe("when the cacheFile is a directory or looks like a directory", () => {
+
+ /**
+ * helper method to delete the cache files created during testing
+ * @returns {void}
+ */
+ function deleteCacheDir() {
+ try {
+ fs.unlinkSync("./tmp/.cacheFileDir/.cache_hashOfCurrentWorkingDirectory");
+ } catch {
+
+ /*
+ * we don't care if the file didn't exist, since our
+ * intention was to remove the file
+ */
+ }
+ }
+ beforeEach(() => {
+ deleteCacheDir();
+ });
+
+ afterEach(() => {
+ deleteCacheDir();
+ });
+
+ it("should create the cache file inside the provided directory", async () => {
+ assert(!shell.test("-d", path.resolve("./tmp/.cacheFileDir/.cache_hashOfCurrentWorkingDirectory")), "the cache for eslint does not exist");
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation: "./tmp/.cacheFileDir/",
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"],
+ ignore: false
+ });
+ const file = getFixturePath("cache/src", "test-file.js");
+
+ await eslint.lintFiles([file]);
+
+ assert(shell.test("-f", path.resolve(`./tmp/.cacheFileDir/.cache_${hash(process.cwd())}`)), "the cache for eslint was created");
+
+ sinon.restore();
+ });
+ });
+
+ it("should create the cache file inside the provided directory using the cacheLocation option", async () => {
+ assert(!shell.test("-d", path.resolve("./tmp/.cacheFileDir/.cache_hashOfCurrentWorkingDirectory")), "the cache for eslint does not exist");
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation: "./tmp/.cacheFileDir/",
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"],
+ ignore: false
+ });
+ const file = getFixturePath("cache/src", "test-file.js");
+
+ await eslint.lintFiles([file]);
+
+ assert(shell.test("-f", path.resolve(`./tmp/.cacheFileDir/.cache_${hash(process.cwd())}`)), "the cache for eslint was created");
+
+ sinon.restore();
+ });
+
+ it("should create the cache file inside cwd when no cacheLocation provided", async () => {
+ const cwd = path.resolve(getFixturePath("cli-engine"));
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ cache: true,
+ cwd,
+ overrideConfig: {
+ rules: {
+ "no-console": 0
+ }
+ },
+ extensions: ["js"],
+ ignore: false
+ });
+ const file = getFixturePath("cli-engine", "console.js");
+
+ await eslint.lintFiles([file]);
+
+ assert(shell.test("-f", path.resolve(cwd, ".eslintcache")), "the cache for eslint was created at provided cwd");
+ });
+
+ it("should invalidate the cache if the configuration changed between executions", async () => {
+ assert(!shell.test("-f", path.resolve(".eslintcache")), "the cache for eslint does not exist");
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"],
+ ignore: false
+ });
+
+ let spy = sinon.spy(fs, "readFileSync");
+
+ let file = getFixturePath("cache/src", "test-file.js");
+
+ file = fs.realpathSync(file);
+ const results = await eslint.lintFiles([file]);
+
+ for (const { errorCount, warningCount } of results) {
+ assert.strictEqual(errorCount + warningCount, 0, "the file passed without errors or warnings");
+ }
+ assert.strictEqual(spy.getCall(0).args[0], file, "the module read the file because is considered changed");
+ assert(shell.test("-f", path.resolve(".eslintcache")), "the cache for eslint was created");
+
+ // destroy the spy
+ sinon.restore();
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ overrideConfig: {
+ rules: {
+ "no-console": 2,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"],
+ ignore: false
+ });
+
+ // create a new spy
+ spy = sinon.spy(fs, "readFileSync");
+
+ const [cachedResult] = await eslint.lintFiles([file]);
+
+ assert.strictEqual(spy.getCall(0).args[0], file, "the module read the file because is considered changed because the config changed");
+ assert.strictEqual(cachedResult.errorCount, 1, "since configuration changed the cache was not used an one error was reported");
+ assert(shell.test("-f", path.resolve(".eslintcache")), "the cache for eslint was created");
+ });
+
+ it("should remember the files from a previous run and do not operate on them if not changed", async () => {
+ assert(!shell.test("-f", path.resolve(".eslintcache")), "the cache for eslint does not exist");
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"],
+ ignore: false
+ });
+
+ let spy = sinon.spy(fs, "readFileSync");
+
+ let file = getFixturePath("cache/src", "test-file.js");
+
+ file = fs.realpathSync(file);
+
+ const result = await eslint.lintFiles([file]);
+
+ assert.strictEqual(spy.getCall(0).args[0], file, "the module read the file because is considered changed");
+ assert(shell.test("-f", path.resolve(".eslintcache")), "the cache for eslint was created");
+
+ // destroy the spy
+ sinon.restore();
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"],
+ ignore: false
+ });
+
+ // create a new spy
+ spy = sinon.spy(fs, "readFileSync");
+
+ const cachedResult = await eslint.lintFiles([file]);
+
+ assert.deepStrictEqual(result, cachedResult, "the result is the same regardless of using cache or not");
+
+ // assert the file was not processed because the cache was used
+ assert(!spy.calledWith(file), "the file was not loaded because it used the cache");
+ });
+
+ it("should remember the files from a previous run and do not operate on then if not changed", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+ const eslintOptions = {
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"],
+ cwd: path.join(fixtureDir, "..")
+ };
+
+ assert(!shell.test("-f", cacheLocation), "the cache for eslint does not exist");
+
+ eslint = new FlatESLint(eslintOptions);
+
+ let file = getFixturePath("cache/src", "test-file.js");
+
+ file = fs.realpathSync(file);
+
+ await eslint.lintFiles([file]);
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint was created");
+
+ eslintOptions.cache = false;
+ eslint = new FlatESLint(eslintOptions);
+
+ await eslint.lintFiles([file]);
+
+ assert(!shell.test("-f", cacheLocation), "the cache for eslint was deleted since last run did not used the cache");
+ });
+
+ it("should store in the cache a file that failed the test", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ assert(!shell.test("-f", cacheLocation), "the cache for eslint does not exist");
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+ const badFile = fs.realpathSync(getFixturePath("cache/src", "fail-file.js"));
+ const goodFile = fs.realpathSync(getFixturePath("cache/src", "test-file.js"));
+ const result = await eslint.lintFiles([badFile, goodFile]);
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint was created");
+ const fileCache = fCache.createFromFile(cacheLocation);
+ const { cache } = fileCache;
+
+ assert.strictEqual(typeof cache.getKey(goodFile), "object", "the entry for the good file is in the cache");
+ assert.strictEqual(typeof cache.getKey(badFile), "object", "the entry for the bad file is in the cache");
+ const cachedResult = await eslint.lintFiles([badFile, goodFile]);
+
+ assert.deepStrictEqual(result, cachedResult, "result is the same with or without cache");
+ });
+
+ it("should not contain in the cache a file that was deleted", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ doDelete(cacheLocation);
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+ const badFile = fs.realpathSync(getFixturePath("cache/src", "fail-file.js"));
+ const goodFile = fs.realpathSync(getFixturePath("cache/src", "test-file.js"));
+ const toBeDeletedFile = fs.realpathSync(getFixturePath("cache/src", "file-to-delete.js"));
+
+ await eslint.lintFiles([badFile, goodFile, toBeDeletedFile]);
+ const fileCache = fCache.createFromFile(cacheLocation);
+ let { cache } = fileCache;
+
+ assert.strictEqual(typeof cache.getKey(toBeDeletedFile), "object", "the entry for the file to be deleted is in the cache");
+
+ // delete the file from the file system
+ fs.unlinkSync(toBeDeletedFile);
+
+ /*
+ * file-entry-cache@2.0.0 will remove from the cache deleted files
+ * even when they were not part of the array of files to be analyzed
+ */
+ await eslint.lintFiles([badFile, goodFile]);
+
+ cache = JSON.parse(fs.readFileSync(cacheLocation));
+
+ assert.strictEqual(typeof cache[toBeDeletedFile], "undefined", "the entry for the file to be deleted is not in the cache");
+ });
+
+ it("should contain files that were not visited in the cache provided they still exist", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ doDelete(cacheLocation);
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+ const badFile = fs.realpathSync(getFixturePath("cache/src", "fail-file.js"));
+ const goodFile = fs.realpathSync(getFixturePath("cache/src", "test-file.js"));
+ const testFile2 = fs.realpathSync(getFixturePath("cache/src", "test-file2.js"));
+
+ await eslint.lintFiles([badFile, goodFile, testFile2]);
+
+ let fileCache = fCache.createFromFile(cacheLocation);
+ let { cache } = fileCache;
+
+ assert.strictEqual(typeof cache.getKey(testFile2), "object", "the entry for the test-file2 is in the cache");
+
+ /*
+ * we pass a different set of files minus test-file2
+ * previous version of file-entry-cache would remove the non visited
+ * entries. 2.0.0 version will keep them unless they don't exist
+ */
+ await eslint.lintFiles([badFile, goodFile]);
+
+ fileCache = fCache.createFromFile(cacheLocation);
+ cache = fileCache.cache;
+
+ assert.strictEqual(typeof cache.getKey(testFile2), "object", "the entry for the test-file2 is in the cache");
+ });
+
+ it("should not delete cache when executing on text", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ cacheLocation,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint exists");
+
+ await eslint.lintText("var foo = 'bar';");
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint still exists");
+ });
+
+ it("should not delete cache when executing on text with a provided filename", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ cacheLocation,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint exists");
+
+ await eslint.lintText("var bar = foo;", { filePath: "fixtures/passing.js" });
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint still exists");
+ });
+
+ it("should not delete cache when executing on files with --cache flag", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ cache: true,
+ cacheLocation,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+ const file = getFixturePath("cli-engine", "console.js");
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint exists");
+
+ await eslint.lintFiles([file]);
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint still exists");
+ });
+
+ it("should delete cache when executing on files without --cache flag", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ cacheLocation,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+ const file = getFixturePath("cli-engine", "console.js");
+
+ assert(shell.test("-f", cacheLocation), "the cache for eslint exists");
+
+ await eslint.lintFiles([file]);
+
+ assert(!shell.test("-f", cacheLocation), "the cache for eslint has been deleted");
+ });
+
+ describe("cacheFile", () => {
+ it("should use the specified cache file", async () => {
+ const customCacheFile = path.resolve(".cache/custom-cache");
+
+ assert(!shell.test("-f", customCacheFile), "the cache for eslint does not exist");
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+
+ // specify a custom cache file
+ cacheLocation: customCacheFile,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"],
+ cwd: path.join(fixtureDir, "..")
+ });
+ const badFile = fs.realpathSync(getFixturePath("cache/src", "fail-file.js"));
+ const goodFile = fs.realpathSync(getFixturePath("cache/src", "test-file.js"));
+ const result = await eslint.lintFiles([badFile, goodFile]);
+
+ assert(shell.test("-f", customCacheFile), "the cache for eslint was created");
+ const fileCache = fCache.createFromFile(customCacheFile);
+ const { cache } = fileCache;
+
+ assert(typeof cache.getKey(goodFile) === "object", "the entry for the good file is in the cache");
+
+ assert(typeof cache.getKey(badFile) === "object", "the entry for the bad file is in the cache");
+ const cachedResult = await eslint.lintFiles([badFile, goodFile]);
+
+ assert.deepStrictEqual(result, cachedResult, "result is the same with or without cache");
+ });
+ });
+
+ describe("cacheStrategy", () => {
+ it("should detect changes using a file's modification time when set to 'metadata'", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ doDelete(cacheLocation);
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation,
+ cacheStrategy: "metadata",
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+ const badFile = fs.realpathSync(getFixturePath("cache/src", "fail-file.js"));
+ const goodFile = fs.realpathSync(getFixturePath("cache/src", "test-file.js"));
+
+ await eslint.lintFiles([badFile, goodFile]);
+ let fileCache = fCache.createFromFile(cacheLocation);
+ const entries = fileCache.normalizeEntries([badFile, goodFile]);
+
+ entries.forEach(entry => {
+ assert(entry.changed === false, `the entry for ${entry.key} is initially unchanged`);
+ });
+
+ // this should result in a changed entry
+ shell.touch(goodFile);
+ fileCache = fCache.createFromFile(cacheLocation);
+ assert(fileCache.getFileDescriptor(badFile).changed === false, `the entry for ${badFile} is unchanged`);
+ assert(fileCache.getFileDescriptor(goodFile).changed === true, `the entry for ${goodFile} is changed`);
+ });
+
+ it("should not detect changes using a file's modification time when set to 'content'", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ doDelete(cacheLocation);
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation,
+ cacheStrategy: "content",
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+ const badFile = fs.realpathSync(getFixturePath("cache/src", "fail-file.js"));
+ const goodFile = fs.realpathSync(getFixturePath("cache/src", "test-file.js"));
+
+ await eslint.lintFiles([badFile, goodFile]);
+ let fileCache = fCache.createFromFile(cacheLocation, true);
+ let entries = fileCache.normalizeEntries([badFile, goodFile]);
+
+ entries.forEach(entry => {
+ assert(entry.changed === false, `the entry for ${entry.key} is initially unchanged`);
+ });
+
+ // this should NOT result in a changed entry
+ shell.touch(goodFile);
+ fileCache = fCache.createFromFile(cacheLocation, true);
+ entries = fileCache.normalizeEntries([badFile, goodFile]);
+ entries.forEach(entry => {
+ assert(entry.changed === false, `the entry for ${entry.key} remains unchanged`);
+ });
+ });
+
+ it("should detect changes using a file's contents when set to 'content'", async () => {
+ const cacheLocation = getFixturePath(".eslintcache");
+
+ doDelete(cacheLocation);
+
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+
+ // specifying cache true the cache will be created
+ cache: true,
+ cacheLocation,
+ cacheStrategy: "content",
+ overrideConfig: {
+ rules: {
+ "no-console": 0,
+ "no-unused-vars": 2
+ }
+ },
+ extensions: ["js"]
+ });
+ const badFile = fs.realpathSync(getFixturePath("cache/src", "fail-file.js"));
+ const goodFile = fs.realpathSync(getFixturePath("cache/src", "test-file.js"));
+ const goodFileCopy = path.resolve(`${path.dirname(goodFile)}`, "test-file-copy.js");
+
+ shell.cp(goodFile, goodFileCopy);
+
+ await eslint.lintFiles([badFile, goodFileCopy]);
+ let fileCache = fCache.createFromFile(cacheLocation, true);
+ const entries = fileCache.normalizeEntries([badFile, goodFileCopy]);
+
+ entries.forEach(entry => {
+ assert(entry.changed === false, `the entry for ${entry.key} is initially unchanged`);
+ });
+
+ // this should result in a changed entry
+ shell.sed("-i", "abc", "xzy", goodFileCopy);
+ fileCache = fCache.createFromFile(cacheLocation, true);
+ assert(fileCache.getFileDescriptor(badFile).changed === false, `the entry for ${badFile} is unchanged`);
+ assert(fileCache.getFileDescriptor(goodFileCopy).changed === true, `the entry for ${goodFileCopy} is changed`);
+ });
+ });
+ });
+
+ describe("processors", () => {
+
+ it("should return two messages when executing with config file that specifies preloaded processor", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: [
+ {
+ plugins: {
+ test: {
+ processors: {
+ txt: {
+ preprocess(text) {
+ return [text];
+ },
+ postprocess(messages) {
+ return messages[0];
+ }
+ }
+ }
+ }
+ },
+ processor: "test/txt",
+ rules: {
+ "no-console": 2,
+ "no-unused-vars": 2
+ }
+ },
+ {
+ files: ["**/*.txt/*.txt"]
+ }
+ ],
+
+ extensions: ["js", "txt"],
+ cwd: path.join(fixtureDir, "..")
+ });
+ const results = await eslint.lintFiles([fs.realpathSync(getFixturePath("processors", "test", "test-processor.txt"))]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 2);
+ });
+
+ it("should run processors when calling lintFiles with config file that specifies preloaded processor", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: [
+ {
+ plugins: {
+ test: {
+ processors: {
+ txt: {
+ preprocess(text) {
+ return [text.replace("a()", "b()")];
+ },
+ postprocess(messages) {
+ messages[0][0].ruleId = "post-processed";
+ return messages[0];
+ }
+ }
+ }
+ }
+ },
+ processor: "test/txt",
+ rules: {
+ "no-console": 2,
+ "no-unused-vars": 2
+ }
+ },
+ {
+ files: ["**/*.txt/*.txt"]
+ }
+ ],
+ extensions: ["js", "txt"],
+ cwd: path.join(fixtureDir, "..")
+ });
+ const results = await eslint.lintFiles([getFixturePath("processors", "test", "test-processor.txt")]);
+
+ assert.strictEqual(results[0].messages[0].message, "'b' is defined but never used.");
+ assert.strictEqual(results[0].messages[0].ruleId, "post-processed");
+ });
+
+ it("should run processors when calling lintText with config file that specifies preloaded processor", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: [
+ {
+ plugins: {
+ test: {
+ processors: {
+ txt: {
+ preprocess(text) {
+ return [text.replace("a()", "b()")];
+ },
+ postprocess(messages) {
+ messages[0][0].ruleId = "post-processed";
+ return messages[0];
+ }
+ }
+ }
+ }
+ },
+ processor: "test/txt",
+ rules: {
+ "no-console": 2,
+ "no-unused-vars": 2
+ }
+ },
+ {
+ files: ["**/*.txt/*.txt"]
+ }
+ ],
+ extensions: ["js", "txt"],
+ ignore: false
+ });
+ const results = await eslint.lintText("function a() {console.log(\"Test\");}", { filePath: "tests/fixtures/processors/test/test-processor.txt" });
+
+ assert.strictEqual(results[0].messages[0].message, "'b' is defined but never used.");
+ assert.strictEqual(results[0].messages[0].ruleId, "post-processed");
+ });
+
+ it("should run processors when calling lintText with processor resolves same extension but different content correctly", async () => {
+ let count = 0;
+
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: [
+ {
+ plugins: {
+ test: {
+ processors: {
+ txt: {
+ preprocess(text) {
+ count++;
+ return [
+ {
+
+ // it will be run twice, and text will be as-is at the second time, then it will not run third time
+ text: text.replace("a()", "b()"),
+ filename: ".txt"
+ }
+ ];
+ },
+ postprocess(messages) {
+ messages[0][0].ruleId = "post-processed";
+ return messages[0];
+ }
+ }
+ }
+ }
+ },
+ processor: "test/txt"
+ },
+ {
+ files: ["**/*.txt/*.txt"],
+ rules: {
+ "no-console": 2,
+ "no-unused-vars": 2
+ }
+ }
+ ],
+ extensions: ["txt"],
+ ignore: false
+ });
+ const results = await eslint.lintText("function a() {console.log(\"Test\");}", { filePath: "tests/fixtures/processors/test/test-processor.txt" });
+
+ assert.strictEqual(count, 2);
+ assert.strictEqual(results[0].messages[0].message, "'b' is defined but never used.");
+ assert.strictEqual(results[0].messages[0].ruleId, "post-processed");
+ });
+
+ describe("autofixing with processors", () => {
+ const HTML_PROCESSOR = Object.freeze({
+ preprocess(text) {
+ return [text.replace(/^", { filePath: "foo.html" });
+
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[0].output, "");
+ });
+
+ it("should not run in autofix mode when using a processor that does not support autofixing", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ files: ["**/*.html"],
+ plugins: {
+ test: { processors: { html: HTML_PROCESSOR } }
+ },
+ processor: "test/html",
+ rules: {
+ semi: 2
+ }
+ },
+ ignore: false,
+ fix: true
+ });
+ const results = await eslint.lintText("", { filePath: "foo.html" });
+
+ assert.strictEqual(results[0].messages.length, 1);
+ assert(!Object.prototype.hasOwnProperty.call(results[0], "output"));
+ });
+
+ it("should not run in autofix mode when `fix: true` is not provided, even if the processor supports autofixing", async () => {
+ eslint = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ files: ["**/*.html"],
+ plugins: {
+ test: { processors: { html: Object.assign({ supportsAutofix: true }, HTML_PROCESSOR) } }
+ },
+ processor: "test/html",
+ rules: {
+ semi: 2
+ }
+ },
+ extensions: ["js", "txt"],
+ ignore: false
+ });
+ const results = await eslint.lintText("", { filePath: "foo.html" });
+
+ assert.strictEqual(results[0].messages.length, 1);
+ assert(!Object.prototype.hasOwnProperty.call(results[0], "output"));
+ });
+ });
+ });
+
+ describe("Patterns which match no file should throw errors.", () => {
+ beforeEach(() => {
+ eslint = new FlatESLint({
+ cwd: getFixturePath("cli-engine"),
+ overrideConfigFile: true
+ });
+ });
+
+ it("one file", async () => {
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["non-exist.js"]);
+ }, /No files matching 'non-exist\.js' were found\./u);
+ });
+
+ it("should throw if the directory exists and is empty", async () => {
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["empty"]);
+ }, /No files matching 'empty\/\*\*\/\*\.js' were found\./u);
+ });
+
+ it("one glob pattern", async () => {
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["non-exist/**/*.js"]);
+ }, /No files matching 'non-exist\/\*\*\/\*\.js' were found\./u);
+ });
+
+ it("two files", async () => {
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["aaa.js", "bbb.js"]);
+ }, /No files matching 'aaa\.js' were found\./u);
+ });
+
+ it("a mix of an existing file and a non-existing file", async () => {
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["console.js", "non-exist.js"]);
+ }, /No files matching 'non-exist\.js' were found\./u);
+ });
+ });
+
+ describe("multiple processors", () => {
+ const root = path.join(os.tmpdir(), "eslint/eslint/multiple-processors");
+ const commonFiles = {
+ "node_modules/pattern-processor/index.js": fs.readFileSync(
+ require.resolve("../../fixtures/processors/pattern-processor"),
+ "utf8"
+ ),
+ "node_modules/eslint-plugin-markdown/index.js": `
+ const { defineProcessor } = require("pattern-processor");
+ const processor = defineProcessor(${/```(\w+)\n([\s\S]+?)\n```/gu});
+ exports.processors = {
+ "markdown": { ...processor, supportsAutofix: true },
+ "non-fixable": processor
+ };
+ `,
+ "node_modules/eslint-plugin-html/index.js": `
+ const { defineProcessor } = require("pattern-processor");
+ const processor = defineProcessor(${/
+
+ \`\`\`
+ `
+ };
+
+ // unique directory for each test to avoid quirky disk-cleanup errors
+ let id;
+
+ beforeEach(() => (id = Date.now().toString()));
+ afterEach(async () => fsp.rmdir(root, { recursive: true, force: true }));
+
+ it("should lint only JavaScript blocks if '--ext' was not given.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: path.join(root, id),
+ files: {
+ ...commonFiles,
+ "eslint.config.js": `module.exports = [
+ {
+ plugins: {
+ markdown: require("eslint-plugin-markdown"),
+ html: require("eslint-plugin-html")
+ }
+ },
+ {
+ files: ["**/*.js"],
+ rules: { semi: "error" }
+ },
+ {
+ files: ["**/*.md"],
+ processor: "markdown/markdown"
+ }
+ ];`
+ }
+ });
+
+ await teardown.prepare();
+ eslint = new FlatESLint({ cwd: teardown.getPath() });
+ const results = await eslint.lintFiles(["test.md"]);
+
+ assert.strictEqual(results.length, 1, "Should have one result.");
+ assert.strictEqual(results[0].messages.length, 1, "Should have one message.");
+ assert.strictEqual(results[0].messages[0].ruleId, "semi");
+ assert.strictEqual(results[0].messages[0].line, 2, "Message should be on line 2.");
+ });
+
+ it("should fix only JavaScript blocks if '--ext' was not given.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: path.join(root, id),
+ files: {
+ ...commonFiles,
+ "eslint.config.js": `module.exports = [
+ {
+ plugins: {
+ markdown: require("eslint-plugin-markdown")
+ }
+ },
+ {
+ files: ["**/*.js"],
+ rules: { semi: "error" }
+ },
+ {
+ files: ["**/*.md"],
+ processor: "markdown/markdown"
+ }
+ ];`
+ }
+ });
+
+ await teardown.prepare();
+ eslint = new FlatESLint({ cwd: teardown.getPath(), fix: true });
+ const results = await eslint.lintFiles(["test.md"]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[0].output, unIndent`
+ \`\`\`js
+ console.log("hello");${/* ← fixed */""}
+ \`\`\`
+ \`\`\`html
+ Hello
+
+
+ \`\`\`
+ `);
+ });
+
+ it("should lint HTML blocks as well with multiple processors if represented in config.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: path.join(root, id),
+ files: {
+ ...commonFiles,
+ "eslint.config.js": `module.exports = [
+ {
+ plugins: {
+ markdown: require("eslint-plugin-markdown"),
+ html: require("eslint-plugin-html")
+ }
+ },
+ {
+ files: ["**/*.js"],
+ rules: { semi: "error" }
+ },
+ {
+ files: ["**/*.md"],
+ processor: "markdown/markdown"
+ },
+ {
+ files: ["**/*.html"],
+ processor: "html/html"
+ }
+ ];`
+ }
+ });
+
+ await teardown.prepare();
+ eslint = new FlatESLint({ cwd: teardown.getPath(), extensions: ["js", "html"] });
+ const results = await eslint.lintFiles(["test.md"]);
+
+ assert.strictEqual(results.length, 1, "Should have one result.");
+ assert.strictEqual(results[0].messages.length, 2, "Should have two messages.");
+ assert.strictEqual(results[0].messages[0].ruleId, "semi"); // JS block
+ assert.strictEqual(results[0].messages[0].line, 2, "First error should be on line 2");
+ assert.strictEqual(results[0].messages[1].ruleId, "semi"); // JS block in HTML block
+ assert.strictEqual(results[0].messages[1].line, 7, "Second error should be on line 7.");
+ });
+
+ it("should fix HTML blocks as well with multiple processors if represented in config.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: path.join(root, id),
+ files: {
+ ...commonFiles,
+ "eslint.config.js": `module.exports = [
+ {
+ plugins: {
+ markdown: require("eslint-plugin-markdown"),
+ html: require("eslint-plugin-html")
+ }
+ },
+ {
+ files: ["**/*.js"],
+ rules: { semi: "error" }
+ },
+ {
+ files: ["**/*.md"],
+ processor: "markdown/markdown"
+ },
+ {
+ files: ["**/*.html"],
+ processor: "html/html"
+ }
+ ];`
+ }
+ });
+
+ await teardown.prepare();
+ eslint = new FlatESLint({ cwd: teardown.getPath(), extensions: ["js", "html"], fix: true });
+ const results = await eslint.lintFiles(["test.md"]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 0);
+ assert.strictEqual(results[0].output, unIndent`
+ \`\`\`js
+ console.log("hello");${/* ← fixed */""}
+ \`\`\`
+ \`\`\`html
+ Hello
+
+
+ \`\`\`
+ `);
+ });
+
+ it("should use the config '**/*.html/*.js' to lint JavaScript blocks in HTML.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: path.join(root, id),
+ files: {
+ ...commonFiles,
+ "eslint.config.js": `module.exports = [
+ {
+ plugins: {
+ markdown: require("eslint-plugin-markdown"),
+ html: require("eslint-plugin-html")
+ }
+ },
+ {
+ files: ["**/*.js"],
+ rules: { semi: "error" }
+ },
+ {
+ files: ["**/*.md"],
+ processor: "markdown/markdown"
+ },
+ {
+ files: ["**/*.html"],
+ processor: "html/html"
+ },
+ {
+ files: ["**/*.html/*.js"],
+ rules: {
+ semi: "off",
+ "no-console": "error"
+ }
+ }
+
+ ];`
+
+ }
+ });
+
+ await teardown.prepare();
+ eslint = new FlatESLint({ cwd: teardown.getPath(), extensions: ["js", "html"] });
+ const results = await eslint.lintFiles(["test.md"]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 2);
+ assert.strictEqual(results[0].messages[0].ruleId, "semi");
+ assert.strictEqual(results[0].messages[0].line, 2);
+ assert.strictEqual(results[0].messages[1].ruleId, "no-console");
+ assert.strictEqual(results[0].messages[1].line, 7);
+ });
+
+ it("should use the same config as one which has 'processor' property in order to lint blocks in HTML if the processor was legacy style.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: path.join(root, id),
+ files: {
+ ...commonFiles,
+ "eslint.config.js": `module.exports = [
+ {
+ plugins: {
+ markdown: require("eslint-plugin-markdown"),
+ html: require("eslint-plugin-html")
+ },
+ rules: { semi: "error" }
+ },
+ {
+ files: ["**/*.md"],
+ processor: "markdown/markdown"
+ },
+ {
+ files: ["**/*.html"],
+ processor: "html/legacy", // this processor returns strings rather than '{ text, filename }'
+ rules: {
+ semi: "off",
+ "no-console": "error"
+ }
+ },
+ {
+ files: ["**/*.html/*.js"],
+ rules: {
+ semi: "error",
+ "no-console": "off"
+ }
+ }
+
+ ];`
+ }
+ });
+
+ await teardown.prepare();
+ eslint = new FlatESLint({ cwd: teardown.getPath(), extensions: ["js", "html"] });
+ const results = await eslint.lintFiles(["test.md"]);
+
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].messages.length, 3);
+ assert.strictEqual(results[0].messages[0].ruleId, "semi");
+ assert.strictEqual(results[0].messages[0].line, 2);
+ assert.strictEqual(results[0].messages[1].ruleId, "no-console");
+ assert.strictEqual(results[0].messages[1].line, 7);
+ assert.strictEqual(results[0].messages[2].ruleId, "no-console");
+ assert.strictEqual(results[0].messages[2].line, 10);
+ });
+
+ it("should throw an error if invalid processor was specified.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: path.join(root, id),
+ files: {
+ ...commonFiles,
+ "eslint.config.js": `module.exports = [
+ {
+ plugins: {
+ markdown: require("eslint-plugin-markdown"),
+ html: require("eslint-plugin-html")
+ }
+ },
+ {
+ files: ["**/*.md"],
+ processor: "markdown/unknown"
+ }
+
+ ];`
+ }
+ });
+
+ await teardown.prepare();
+ eslint = new FlatESLint({ cwd: teardown.getPath() });
+
+ await assert.rejects(async () => {
+ await eslint.lintFiles(["test.md"]);
+ }, /Key "processor": Could not find "unknown" in plugin "markdown"/u);
+ });
+
+ });
+
+ describe("glob pattern '[ab].js'", () => {
+ const root = getFixturePath("cli-engine/unmatched-glob");
+
+ let cleanup;
+
+ beforeEach(() => {
+ cleanup = () => { };
+ });
+
+ afterEach(() => cleanup());
+
+ it("should match '[ab].js' if existed.", async () => {
+
+ const teardown = createCustomTeardown({
+ cwd: root,
+ files: {
+ "a.js": "",
+ "b.js": "",
+ "ab.js": "",
+ "[ab].js": "",
+ "eslint.config.js": "module.exports = [];"
+ }
+ });
+
+ await teardown.prepare();
+ cleanup = teardown.cleanup;
+
+ eslint = new FlatESLint({ cwd: teardown.getPath() });
+ const results = await eslint.lintFiles(["[ab].js"]);
+ const filenames = results.map(r => path.basename(r.filePath));
+
+ assert.deepStrictEqual(filenames, ["[ab].js"]);
+ });
+
+ it("should match 'a.js' and 'b.js' if '[ab].js' didn't existed.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: root,
+ files: {
+ "a.js": "",
+ "b.js": "",
+ "ab.js": "",
+ "eslint.config.js": "module.exports = [];"
+ }
+ });
+
+ await teardown.prepare();
+ cleanup = teardown.cleanup;
+ eslint = new FlatESLint({ cwd: teardown.getPath() });
+ const results = await eslint.lintFiles(["[ab].js"]);
+ const filenames = results.map(r => path.basename(r.filePath));
+
+ assert.deepStrictEqual(filenames, ["a.js", "b.js"]);
+ });
+ });
+
+ describe("with 'noInlineConfig' setting", () => {
+ const root = getFixturePath("cli-engine/noInlineConfig");
+
+ let cleanup;
+
+ beforeEach(() => {
+ cleanup = () => { };
+ });
+
+ afterEach(() => cleanup());
+
+ it("should warn directive comments if 'noInlineConfig' was given.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: root,
+ files: {
+ "test.js": "/* globals foo */",
+ "eslint.config.js": "module.exports = [{ linterOptions: { noInlineConfig: true } }];"
+ }
+ });
+
+ await teardown.prepare();
+ cleanup = teardown.cleanup;
+ eslint = new FlatESLint({ cwd: teardown.getPath() });
+
+ const results = await eslint.lintFiles(["test.js"]);
+ const messages = results[0].messages;
+
+ assert.strictEqual(messages.length, 1);
+ assert.strictEqual(messages[0].message, "'/*globals*/' has no effect because you have 'noInlineConfig' setting in your config.");
+ });
+
+ });
+
+ describe("with 'reportUnusedDisableDirectives' setting", () => {
+ const root = getFixturePath("cli-engine/reportUnusedDisableDirectives");
+
+ let cleanup;
+
+ beforeEach(() => {
+ cleanup = () => { };
+ });
+
+ afterEach(() => cleanup());
+
+ it("should warn unused 'eslint-disable' comments if 'reportUnusedDisableDirectives' was given.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: root,
+ files: {
+ "test.js": "/* eslint-disable eqeqeq */",
+ "eslint.config.js": "module.exports = { linterOptions: { reportUnusedDisableDirectives: true } }"
+ }
+ });
+
+
+ await teardown.prepare();
+ cleanup = teardown.cleanup;
+ eslint = new FlatESLint({ cwd: teardown.getPath() });
+
+ const results = await eslint.lintFiles(["test.js"]);
+ const messages = results[0].messages;
+
+ assert.strictEqual(messages.length, 1);
+ assert.strictEqual(messages[0].severity, 1);
+ assert.strictEqual(messages[0].message, "Unused eslint-disable directive (no problems were reported from 'eqeqeq').");
+ });
+
+ describe("the runtime option overrides config files.", () => {
+ it("should not warn unused 'eslint-disable' comments if 'reportUnusedDisableDirectives=off' was given in runtime.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: root,
+ files: {
+ "test.js": "/* eslint-disable eqeqeq */",
+ ".eslintrc.yml": "reportUnusedDisableDirectives: true"
+ }
+ });
+
+ await teardown.prepare();
+ cleanup = teardown.cleanup;
+
+ eslint = new FlatESLint({
+ cwd: teardown.getPath(),
+ reportUnusedDisableDirectives: "off"
+ });
+
+ const results = await eslint.lintFiles(["test.js"]);
+ const messages = results[0].messages;
+
+ assert.strictEqual(messages.length, 0);
+ });
+
+ it("should warn unused 'eslint-disable' comments as error if 'reportUnusedDisableDirectives=error' was given in runtime.", async () => {
+ const teardown = createCustomTeardown({
+ cwd: root,
+ files: {
+ "test.js": "/* eslint-disable eqeqeq */",
+ ".eslintrc.yml": "reportUnusedDisableDirectives: true"
+ }
+ });
+
+ await teardown.prepare();
+ cleanup = teardown.cleanup;
+
+ eslint = new FlatESLint({
+ cwd: teardown.getPath(),
+ reportUnusedDisableDirectives: "error"
+ });
+
+ const results = await eslint.lintFiles(["test.js"]);
+ const messages = results[0].messages;
+
+ assert.strictEqual(messages.length, 1);
+ assert.strictEqual(messages[0].severity, 2);
+ assert.strictEqual(messages[0].message, "Unused eslint-disable directive (no problems were reported from 'eqeqeq').");
+ });
+ });
+ });
+
+ it("should throw if non-boolean value is given to 'options.warnIgnored' option", async () => {
+ eslint = new FlatESLint();
+ await assert.rejects(() => eslint.lintFiles(777), /'patterns' must be a non-empty string or an array of non-empty strings/u);
+ await assert.rejects(() => eslint.lintFiles([null]), /'patterns' must be a non-empty string or an array of non-empty strings/u);
+ });
+ });
+
+ describe("Fix Types", () => {
+
+ let eslint;
+
+ it("should throw an error when an invalid fix type is specified", () => {
+ assert.throws(() => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ fix: true,
+ fixTypes: ["layou"]
+ });
+ }, /'fixTypes' must be an array of any of "directive", "problem", "suggestion", and "layout"\./iu);
+ });
+
+ it("should not fix any rules when fixTypes is used without fix", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ fix: false,
+ fixTypes: ["layout"]
+ });
+ const inputPath = getFixturePath("fix-types/fix-only-semi.js");
+ const results = await eslint.lintFiles([inputPath]);
+
+ assert.strictEqual(results[0].output, void 0);
+ });
+
+ it("should not fix non-style rules when fixTypes has only 'layout'", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ fix: true,
+ fixTypes: ["layout"]
+ });
+ const inputPath = getFixturePath("fix-types/fix-only-semi.js");
+ const outputPath = getFixturePath("fix-types/fix-only-semi.expected.js");
+ const results = await eslint.lintFiles([inputPath]);
+ const expectedOutput = fs.readFileSync(outputPath, "utf8");
+
+ assert.strictEqual(results[0].output, expectedOutput);
+ });
+
+ it("should not fix style or problem rules when fixTypes has only 'suggestion'", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ fix: true,
+ fixTypes: ["suggestion"]
+ });
+ const inputPath = getFixturePath("fix-types/fix-only-prefer-arrow-callback.js");
+ const outputPath = getFixturePath("fix-types/fix-only-prefer-arrow-callback.expected.js");
+ const results = await eslint.lintFiles([inputPath]);
+ const expectedOutput = fs.readFileSync(outputPath, "utf8");
+
+ assert.strictEqual(results[0].output, expectedOutput);
+ });
+
+ it("should fix both style and problem rules when fixTypes has 'suggestion' and 'layout'", async () => {
+ eslint = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ fix: true,
+ fixTypes: ["suggestion", "layout"]
+ });
+ const inputPath = getFixturePath("fix-types/fix-both-semi-and-prefer-arrow-callback.js");
+ const outputPath = getFixturePath("fix-types/fix-both-semi-and-prefer-arrow-callback.expected.js");
+ const results = await eslint.lintFiles([inputPath]);
+ const expectedOutput = fs.readFileSync(outputPath, "utf8");
+
+ assert.strictEqual(results[0].output, expectedOutput);
+ });
+
+ });
+
+ describe("isPathIgnored", () => {
+ it("should check if the given path is ignored", async () => {
+ const engine = new FlatESLint({
+ ignorePath: getFixturePath(".eslintignore2"),
+ cwd: getFixturePath()
+ });
+
+ assert(await engine.isPathIgnored("undef.js"));
+ assert(!await engine.isPathIgnored("passing.js"));
+ });
+
+ it("should return false if ignoring is disabled", async () => {
+ const engine = new FlatESLint({
+ ignore: false,
+ ignorePath: getFixturePath(".eslintignore2"),
+ cwd: getFixturePath()
+ });
+
+ assert(!await engine.isPathIgnored("undef.js"));
+ });
+
+ // https://github.com/eslint/eslint/issues/5547
+ it("should return true for default ignores even if ignoring is disabled", async () => {
+ const engine = new FlatESLint({
+ ignore: false,
+ cwd: getFixturePath("cli-engine")
+ });
+
+ assert(await engine.isPathIgnored("node_modules/foo.js"));
+ });
+
+ describe("about the default ignore patterns", () => {
+ it("should always apply default ignore patterns if ignore option is true", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "node_modules/package/file.js")));
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "subdir/node_modules/package/file.js")));
+ });
+
+ it("should still apply default ignore patterns if ignore option is is false", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ ignore: false, cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "node_modules/package/file.js")));
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "subdir/node_modules/package/file.js")));
+ });
+
+ it("should allow subfolders of defaultPatterns to be unignored by ignorePattern", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({
+ cwd,
+ overrideConfigFile: true,
+ ignorePatterns: "!/node_modules/package"
+ });
+
+ const result = await engine.isPathIgnored(getFixturePath("ignored-paths", "node_modules", "package", "file.js"));
+
+ assert(!result, "File should not be ignored");
+ });
+
+ it("should allow subfolders of defaultPatterns to be unignored by ignorePath", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({
+ cwd,
+ overrideConfigFile: true,
+ ignorePath: getFixturePath("ignored-paths", ".eslintignoreWithUnignoredDefaults")
+ });
+
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "node_modules", "package", "file.js")));
+ });
+
+ it("should ignore .git directory", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", ".git/bar")));
+ });
+
+ it("should still ignore .git directory when ignore option disabled", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ ignore: false, cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", ".git/bar")));
+ });
+
+ it("should not ignore absolute paths containing '..'", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ cwd });
+
+ assert(!await engine.isPathIgnored(`${getFixturePath("ignored-paths", "foo")}/../unignored.js`));
+ });
+
+ it("should ignore /node_modules/ relative to .eslintignore when loaded", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ ignorePath: getFixturePath("ignored-paths", ".eslintignore"), cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "node_modules", "existing.js")));
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "foo", "node_modules", "existing.js")));
+ });
+
+ it("should ignore /node_modules/ relative to cwd without an .eslintignore", async () => {
+ const cwd = getFixturePath("ignored-paths", "no-ignore-file");
+ const engine = new FlatESLint({ cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "no-ignore-file", "node_modules", "existing.js")));
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "no-ignore-file", "foo", "node_modules", "existing.js")));
+ });
+ });
+
+ describe("with no .eslintignore file", () => {
+ it("should not travel to parent directories to find .eslintignore when it's missing and cwd is provided", async () => {
+ const cwd = getFixturePath("ignored-paths", "configurations");
+ const engine = new FlatESLint({ cwd });
+
+ // a .eslintignore in parent directories includes `*.js`, but don't load it.
+ assert(!await engine.isPathIgnored("foo.js"));
+ assert(await engine.isPathIgnored("node_modules/foo.js"));
+ });
+
+ it("should return false for files outside of the cwd (with no ignore file provided)", async () => {
+
+ // Default ignore patterns should not inadvertently ignore files in parent directories
+ const engine = new FlatESLint({ cwd: getFixturePath("ignored-paths", "no-ignore-file") });
+
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "undef.js")));
+ });
+ });
+
+ describe("with .eslintignore file or package.json file", () => {
+ it("should load .eslintignore from cwd when explicitly passed", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ cwd });
+
+ // `${cwd}/.eslintignore` includes `sampleignorepattern`.
+ assert(await engine.isPathIgnored("sampleignorepattern"));
+ });
+
+ });
+
+ describe("with ignorePatterns option", () => {
+ it("should accept a string for options.ignorePatterns", async () => {
+ const cwd = getFixturePath("ignored-paths", "ignore-pattern");
+ const engine = new FlatESLint({
+ ignorePatterns: ["ignore-me.txt"],
+ cwd
+ });
+
+ assert(await engine.isPathIgnored("ignore-me.txt"));
+ });
+
+ it("should accept an array for options.ignorePattern", async () => {
+ const engine = new FlatESLint({
+ ignorePatterns: ["a.js", "b.js"],
+ overrideConfigFile: true
+ });
+
+ assert(await engine.isPathIgnored("a.js"), "a.js should be ignored");
+ assert(await engine.isPathIgnored("b.js"), "b.js should be ignored");
+ assert(!await engine.isPathIgnored("c.js"), "c.js should not be ignored");
+ });
+
+ it("should return true for files which match an ignorePattern even if they do not exist on the filesystem", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({
+ ignorePatterns: ["not-a-file"],
+ cwd
+ });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "not-a-file")));
+ });
+
+ it("should return true for file matching an ignore pattern exactly", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ ignorePatterns: ["undef.js"], cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "undef.js")));
+ });
+
+ it("should return false for file in subfolder of cwd matching an ignore pattern with leading '/'", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const filePath = getFixturePath("ignored-paths", "subdir", "undef.js");
+ const engine = new FlatESLint({
+ ignorePatterns: ["/undef.js"],
+ overrideConfigFile: true,
+ cwd
+ });
+
+ assert(!await engine.isPathIgnored(filePath));
+ });
+
+ it("should return true for file matching a child of an ignore pattern", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ ignorePatterns: ["ignore-pattern"], cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "ignore-pattern", "ignore-me.txt")));
+ });
+
+ it("should return true for file matching a grandchild of an ignore pattern", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ ignorePatterns: ["ignore-pattern"], cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "ignore-pattern", "subdir", "ignore-me.txt")));
+ });
+
+ it("should return false for file not matching any ignore pattern", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({ ignorePatterns: ["failing.js"], cwd });
+
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "unignored.js")));
+ });
+
+ it("two globstar '**' ignore pattern should ignore files in nested directories", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ ignorePatterns: ["**/*.js"],
+ cwd
+ });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "foo.js")), "foo.js should be ignored");
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "foo/bar.js")), "foo/bar.js should be ignored");
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "foo/bar/baz.js")), "foo/bar/baz.js");
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "foo.cjs")), "foo.cjs should not be ignored");
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "foo/bar.cjs")), "foo/bar.cjs should not be ignored");
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "foo/bar/baz.cjs")), "foo/bar/baz.cjs should not be ignored");
+ });
+ });
+
+ describe("with ignorePath option", () => {
+ it("initialization with ignorePath should work when cwd is a parent directory", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", "custom-name", "ignore-file");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(await engine.isPathIgnored("custom-name/foo.js"));
+ });
+
+ it("initialization with ignorePath should work when the file is in the cwd", async () => {
+ const cwd = getFixturePath("ignored-paths", "custom-name");
+ const ignorePath = getFixturePath("ignored-paths", "custom-name", "ignore-file");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(await engine.isPathIgnored("foo.js"));
+ });
+
+ it("initialization with ignorePath should work when cwd is a subdirectory", async () => {
+ const cwd = getFixturePath("ignored-paths", "custom-name", "subdirectory");
+ const ignorePath = getFixturePath("ignored-paths", "custom-name", "ignore-file");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(await engine.isPathIgnored("../custom-name/foo.js"));
+ });
+
+ it("missing ignore file should throw error", done => {
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", "not-a-directory", ".foobaz");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ engine.isPathIgnored("foo.js").then(() => {
+ assert.fail("missing file should not succeed");
+ }).catch(error => {
+ assert(/Cannot read ignore file/u.test(error));
+ done();
+ });
+ });
+
+ it("should return false for files outside of ignorePath's directory", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", "custom-name", "ignore-file");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "undef.js")));
+ });
+
+ it("should resolve relative paths from CWD", async () => {
+ const cwd = getFixturePath("ignored-paths", "subdir");
+
+ // /undef.js in ignore file
+ const ignorePath = getFixturePath("ignored-paths", ".eslintignoreForDifferentCwd");
+ const engine = new FlatESLint({ ignorePath, cwd, overrideConfigFile: true });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "subdir/undef.js")), "subdir/undef.js should be ignored");
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "subdir/subdir/undef.js")), "subdir/subdir/undef.js should not be ignored");
+ });
+
+ it("should resolve relative paths from CWD when it's in a child directory", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", "subdir/.eslintignoreInChildDir");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "subdir/undef.js")));
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "undef.js")));
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "foo.js")));
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "subdir/foo.js")));
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "node_modules/bar.js")));
+ });
+
+ it("should resolve relative paths from CWD when it contains negated globs", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", "subdir/.eslintignoreInChildDir");
+ const engine = new FlatESLint({
+ ignorePath,
+ cwd,
+ overrideConfig: {
+ files: ["**/*.txt"]
+ }
+ });
+
+ assert(await engine.isPathIgnored("subdir/blah.txt"), "subdir/blah.txt should be ignore");
+ assert(await engine.isPathIgnored("blah.txt"), "blah.txt should be ignored");
+ assert(await engine.isPathIgnored("subdir/bar.txt"), "subdir/bar.txt should be ignored");
+ assert(!await engine.isPathIgnored("bar.txt"), "bar.txt should not be ignored");
+ assert(!await engine.isPathIgnored("baz.txt"), "baz.txt should not be ignored");
+ assert(!await engine.isPathIgnored("subdir/baz.txt"), "subdir/baz.txt should not be ignored");
+ });
+
+ it("should resolve default ignore patterns from the CWD even when the ignorePath is in a subdirectory", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", "subdir/.eslintignoreInChildDir");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(await engine.isPathIgnored("node_modules/blah.js"));
+ });
+
+ it("should resolve default ignore patterns from the CWD even when the ignorePath is in a parent directory", async () => {
+ const cwd = getFixturePath("ignored-paths", "subdir");
+ const ignorePath = getFixturePath("ignored-paths", ".eslintignoreForDifferentCwd");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(await engine.isPathIgnored("node_modules/blah.js"));
+ });
+
+ it("should handle .eslintignore which contains CRLF correctly.", async () => {
+ const ignoreFileContent = fs.readFileSync(getFixturePath("ignored-paths", "crlf/.eslintignore"), "utf8");
+
+ assert(ignoreFileContent.includes("\r"), "crlf/.eslintignore should contains CR.", "Ignore file must have CRLF for test to pass.");
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", "crlf/.eslintignore");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "crlf/hide1/a.js")));
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "crlf/hide2/a.js")));
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "crlf/hide3/a.js")));
+ });
+
+ it("should ignore a non-negated pattern", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", ".eslintignoreWithNegation");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(await engine.isPathIgnored(getFixturePath("ignored-paths", "negation", "ignore.js")));
+ });
+
+ it("should not ignore a negated pattern", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const ignorePath = getFixturePath("ignored-paths", ".eslintignoreWithNegation");
+ const engine = new FlatESLint({ ignorePath, cwd });
+
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "negation", "unignore.js")));
+ });
+ });
+
+ describe("with ignorePath option and ignorePatterns option", () => {
+ it("should return false for ignored file when unignored with ignore pattern", async () => {
+ const cwd = getFixturePath("ignored-paths");
+ const engine = new FlatESLint({
+ ignorePath: getFixturePath("ignored-paths", ".eslintignoreForNegationTest"),
+ ignorePatterns: ["!undef.js"],
+ cwd
+ });
+
+ assert(!await engine.isPathIgnored(getFixturePath("ignored-paths", "undef.js")));
+ });
+ });
+
+ it("should throw if non-string value is given to 'filePath' parameter", async () => {
+ const eslint = new FlatESLint();
+
+ await assert.rejects(() => eslint.isPathIgnored(null), /'filePath' must be a non-empty string/u);
+ });
+ });
+
+ describe("loadFormatter()", () => {
+ it("should return a formatter object when a bundled formatter is requested", async () => {
+ const engine = new FlatESLint();
+ const formatter = await engine.loadFormatter("compact");
+
+ assert.strictEqual(typeof formatter, "object");
+ assert.strictEqual(typeof formatter.format, "function");
+ });
+
+ it("should return a formatter object when no argument is passed", async () => {
+ const engine = new FlatESLint();
+ const formatter = await engine.loadFormatter();
+
+ assert.strictEqual(typeof formatter, "object");
+ assert.strictEqual(typeof formatter.format, "function");
+ });
+
+ it("should return a formatter object when a custom formatter is requested", async () => {
+ const engine = new FlatESLint();
+ const formatter = await engine.loadFormatter(getFixturePath("formatters", "simple.js"));
+
+ assert.strictEqual(typeof formatter, "object");
+ assert.strictEqual(typeof formatter.format, "function");
+ });
+
+ it("should return a formatter object when a custom formatter is requested, also if the path has backslashes", async () => {
+ const engine = new FlatESLint({
+ cwd: path.join(fixtureDir, "..")
+ });
+ const formatter = await engine.loadFormatter(".\\fixtures\\formatters\\simple.js");
+
+ assert.strictEqual(typeof formatter, "object");
+ assert.strictEqual(typeof formatter.format, "function");
+ });
+
+ it("should return a formatter object when a formatter prefixed with eslint-formatter is requested", async () => {
+ const engine = new FlatESLint({
+ cwd: getFixturePath("cli-engine")
+ });
+ const formatter = await engine.loadFormatter("bar");
+
+ assert.strictEqual(typeof formatter, "object");
+ assert.strictEqual(typeof formatter.format, "function");
+ });
+
+ it("should return a formatter object when a formatter is requested, also when the eslint-formatter prefix is included in the format argument", async () => {
+ const engine = new FlatESLint({
+ cwd: getFixturePath("cli-engine")
+ });
+ const formatter = await engine.loadFormatter("eslint-formatter-bar");
+
+ assert.strictEqual(typeof formatter, "object");
+ assert.strictEqual(typeof formatter.format, "function");
+ });
+
+ it("should return a formatter object when a formatter is requested within a scoped npm package", async () => {
+ const engine = new FlatESLint({
+ cwd: getFixturePath("cli-engine")
+ });
+ const formatter = await engine.loadFormatter("@somenamespace/foo");
+
+ assert.strictEqual(typeof formatter, "object");
+ assert.strictEqual(typeof formatter.format, "function");
+ });
+
+ it("should return a formatter object when a formatter is requested within a scoped npm package, also when the eslint-formatter prefix is included in the format argument", async () => {
+ const engine = new FlatESLint({
+ cwd: getFixturePath("cli-engine")
+ });
+ const formatter = await engine.loadFormatter("@somenamespace/eslint-formatter-foo");
+
+ assert.strictEqual(typeof formatter, "object");
+ assert.strictEqual(typeof formatter.format, "function");
+ });
+
+ it("should throw if a custom formatter doesn't exist", async () => {
+ const engine = new FlatESLint();
+ const formatterPath = getFixturePath("formatters", "doesntexist.js");
+ const fullFormatterPath = path.resolve(formatterPath);
+
+ await assert.rejects(async () => {
+ await engine.loadFormatter(formatterPath);
+ }, new RegExp(escapeStringRegExp(`There was a problem loading formatter: ${fullFormatterPath}\nError: Cannot find module '${fullFormatterPath}'`), "u"));
+ });
+
+ it("should throw if a built-in formatter doesn't exist", async () => {
+ const engine = new FlatESLint();
+ const fullFormatterPath = path.resolve(__dirname, "../../../lib/cli-engine/formatters/special");
+
+ await assert.rejects(async () => {
+ await engine.loadFormatter("special");
+ }, new RegExp(escapeStringRegExp(`There was a problem loading formatter: ${fullFormatterPath}.js\nError: Cannot find module '${fullFormatterPath}.js'`), "u"));
+ });
+
+ it("should throw if the required formatter exists but has an error", async () => {
+ const engine = new FlatESLint();
+ const formatterPath = getFixturePath("formatters", "broken.js");
+
+ await assert.rejects(async () => {
+ await engine.loadFormatter(formatterPath);
+
+ // for some reason, the error here contains multiple "there was a problem loading formatter" lines, so omitting
+ }, new RegExp(escapeStringRegExp("Error: Cannot find module 'this-module-does-not-exist'"), "u"));
+ });
+
+ it("should throw if a non-string formatter name is passed", async () => {
+ const engine = new FlatESLint();
+
+ await assert.rejects(async () => {
+ await engine.loadFormatter(5);
+ }, /'name' must be a string/u);
+ });
+ });
+
+ describe("getErrorResults()", () => {
+
+ it("should report 5 error messages when looking for errors only", async () => {
+ process.chdir(originalDir);
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ quotes: "error",
+ "no-var": "error",
+ "eol-last": "error",
+ "no-unused-vars": "error"
+ }
+ }
+ });
+ const results = await engine.lintText("var foo = 'bar';");
+ const errorResults = FlatESLint.getErrorResults(results);
+
+ assert.strictEqual(errorResults[0].messages.length, 4, "messages.length is wrong");
+ assert.strictEqual(errorResults[0].errorCount, 4, "errorCount is wrong");
+ assert.strictEqual(errorResults[0].fixableErrorCount, 3, "fixableErrorCount is wrong");
+ assert.strictEqual(errorResults[0].fixableWarningCount, 0, "fixableWarningCount is wrong");
+ assert.strictEqual(errorResults[0].messages[0].ruleId, "no-var");
+ assert.strictEqual(errorResults[0].messages[0].severity, 2);
+ assert.strictEqual(errorResults[0].messages[1].ruleId, "no-unused-vars");
+ assert.strictEqual(errorResults[0].messages[1].severity, 2);
+ assert.strictEqual(errorResults[0].messages[2].ruleId, "quotes");
+ assert.strictEqual(errorResults[0].messages[2].severity, 2);
+ assert.strictEqual(errorResults[0].messages[3].ruleId, "eol-last");
+ assert.strictEqual(errorResults[0].messages[3].severity, 2);
+ });
+
+ it("should not mutate passed report parameter", async () => {
+ process.chdir(originalDir);
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: { quotes: [1, "double"] }
+ }
+ });
+ const results = await engine.lintText("var foo = 'bar';");
+ const reportResultsLength = results[0].messages.length;
+
+ FlatESLint.getErrorResults(results);
+
+ assert.strictEqual(results[0].messages.length, reportResultsLength);
+ });
+
+ it("should report a warningCount of 0 when looking for errors only", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ strict: ["error", "global"],
+ quotes: "error",
+ "no-var": "error",
+ "eol-last": "error",
+ "no-unused-vars": "error"
+ }
+ }
+ });
+ const lintResults = await engine.lintText("var foo = 'bar';");
+ const errorResults = FlatESLint.getErrorResults(lintResults);
+
+ assert.strictEqual(errorResults[0].warningCount, 0);
+ assert.strictEqual(errorResults[0].fixableWarningCount, 0);
+ });
+
+ it("should return 0 error or warning messages even when the file has warnings", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ ignorePath: path.join(fixtureDir, ".eslintignore"),
+ cwd: path.join(fixtureDir, "..")
+ });
+ const options = {
+ filePath: "fixtures/passing.js",
+ warnIgnored: true
+ };
+ const results = await engine.lintText("var bar = foo;", options);
+ const errorReport = FlatESLint.getErrorResults(results);
+
+ assert.strictEqual(errorReport.length, 0);
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].errorCount, 0);
+ assert.strictEqual(results[0].warningCount, 1);
+ });
+
+ it("should return source code of file in the `source` property", async () => {
+ process.chdir(originalDir);
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: { quotes: [2, "double"] }
+ }
+ });
+ const results = await engine.lintText("var foo = 'bar';");
+ const errorResults = FlatESLint.getErrorResults(results);
+
+ assert.strictEqual(errorResults[0].messages.length, 1);
+ assert.strictEqual(errorResults[0].source, "var foo = 'bar';");
+ });
+
+ it("should contain `output` property after fixes", async () => {
+ process.chdir(originalDir);
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ fix: true,
+ overrideConfig: {
+ rules: {
+ semi: 2,
+ "no-console": 2
+ }
+ }
+ });
+ const results = await engine.lintText("console.log('foo')");
+ const errorResults = FlatESLint.getErrorResults(results);
+
+ assert.strictEqual(errorResults[0].messages.length, 1);
+ assert.strictEqual(errorResults[0].output, "console.log('foo');");
+ });
+ });
+
+ describe("getRulesMetaForResults()", () => {
+
+ it("should throw an error when results were not created from this instance", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: true
+ });
+
+ assert.throws(() => {
+ engine.getRulesMetaForResults([
+ {
+ filePath: "path/to/file.js",
+ messages: [
+ {
+ ruleId: "curly",
+ severity: 2,
+ message: "Expected { after 'if' condition.",
+ line: 2,
+ column: 1,
+ nodeType: "IfStatement"
+ },
+ {
+ ruleId: "no-process-exit",
+ severity: 2,
+ message: "Don't use process.exit(); throw an error instead.",
+ line: 3,
+ column: 1,
+ nodeType: "CallExpression"
+ }
+ ],
+ errorCount: 2,
+ warningCount: 0,
+ fatalErrorCount: 0,
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ source:
+ "var err = doStuff();\nif (err) console.log('failed tests: ' + err);\nprocess.exit(1);\n"
+ }
+ ]);
+ }, /Results object was not created from this ESLint instance/u);
+ });
+
+ it("should return empty object when there are no linting errors", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: true
+ });
+
+ const rulesMeta = engine.getRulesMetaForResults([]);
+
+ assert.strictEqual(Object.keys(rulesMeta).length, 0);
+ });
+
+ it("should return one rule meta when there is a linting error", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ semi: 2
+ }
+ }
+ });
+
+ const results = await engine.lintText("a", { filePath: "foo.js" });
+ const rulesMeta = engine.getRulesMetaForResults(results);
+
+ assert.strictEqual(rulesMeta.semi, coreRules.get("semi").meta);
+ });
+
+ it("should return multiple rule meta when there are multiple linting errors", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ rules: {
+ semi: 2,
+ quotes: [2, "double"]
+ }
+ }
+ });
+
+ const results = await engine.lintText("'a'");
+ const rulesMeta = engine.getRulesMetaForResults(results);
+
+ assert.strictEqual(rulesMeta.semi, coreRules.get("semi").meta);
+ assert.strictEqual(rulesMeta.quotes, coreRules.get("quotes").meta);
+ });
+
+ it("should return multiple rule meta when there are multiple linting errors from a plugin", async () => {
+ const nodePlugin = require("eslint-plugin-n");
+ const engine = new FlatESLint({
+ overrideConfigFile: true,
+ overrideConfig: {
+ plugins: {
+ n: nodePlugin
+ },
+ rules: {
+ "n/no-new-require": 2,
+ semi: 2,
+ quotes: [2, "double"]
+ }
+ }
+ });
+
+ const results = await engine.lintText("new require('hi')");
+ const rulesMeta = engine.getRulesMetaForResults(results);
+
+ assert.strictEqual(rulesMeta.semi, coreRules.get("semi").meta);
+ assert.strictEqual(rulesMeta.quotes, coreRules.get("quotes").meta);
+ assert.strictEqual(
+ rulesMeta["n/no-new-require"],
+ nodePlugin.rules["no-new-require"].meta
+ );
+ });
+ });
+
+ describe("outputFixes()", () => {
+ afterEach(() => {
+ sinon.verifyAndRestore();
+ });
+
+ it("should call fs.writeFile() for each result with output", async () => {
+ const fakeFS = {
+ writeFile: sinon.spy(() => Promise.resolve())
+ };
+ const spy = fakeFS.writeFile;
+ const { FlatESLint: localESLint } = proxyquire("../../../lib/eslint/flat-eslint", {
+ fs: {
+ promises: fakeFS
+ }
+ });
+
+ const results = [
+ {
+ filePath: path.resolve("foo.js"),
+ output: "bar"
+ },
+ {
+ filePath: path.resolve("bar.js"),
+ output: "baz"
+ }
+ ];
+
+ await localESLint.outputFixes(results);
+
+ assert.strictEqual(spy.callCount, 2);
+ assert(spy.firstCall.calledWithExactly(path.resolve("foo.js"), "bar"), "First call was incorrect.");
+ assert(spy.secondCall.calledWithExactly(path.resolve("bar.js"), "baz"), "Second call was incorrect.");
+ });
+
+ it("should call fs.writeFile() for each result with output and not at all for a result without output", async () => {
+ const fakeFS = {
+ writeFile: sinon.spy(() => Promise.resolve())
+ };
+ const spy = fakeFS.writeFile;
+ const { FlatESLint: localESLint } = proxyquire("../../../lib/eslint/flat-eslint", {
+ fs: {
+ promises: fakeFS
+ }
+ });
+ const results = [
+ {
+ filePath: path.resolve("foo.js"),
+ output: "bar"
+ },
+ {
+ filePath: path.resolve("abc.js")
+ },
+ {
+ filePath: path.resolve("bar.js"),
+ output: "baz"
+ }
+ ];
+
+ await localESLint.outputFixes(results);
+
+ assert.strictEqual(spy.callCount, 2, "Call count was wrong");
+ assert(spy.firstCall.calledWithExactly(path.resolve("foo.js"), "bar"), "First call was incorrect.");
+ assert(spy.secondCall.calledWithExactly(path.resolve("bar.js"), "baz"), "Second call was incorrect.");
+ });
+
+ it("should throw if non object array is given to 'results' parameter", async () => {
+ await assert.rejects(() => FlatESLint.outputFixes(null), /'results' must be an array/u);
+ await assert.rejects(() => FlatESLint.outputFixes([null]), /'results' must include only objects/u);
+ });
+ });
+
+ describe("when evaluating code with comments to change config when allowInlineConfig is disabled", () => {
+ it("should report a violation for disabling rules", async () => {
+ const code = [
+ "alert('test'); // eslint-disable-line no-alert"
+ ].join("\n");
+ const config = {
+ ignore: true,
+ overrideConfigFile: true,
+ allowInlineConfig: false,
+ overrideConfig: {
+ rules: {
+ "eol-last": 0,
+ "no-alert": 1,
+ "no-trailing-spaces": 0,
+ strict: 0,
+ quotes: 0
+ }
+ }
+ };
+ const eslintCLI = new FlatESLint(config);
+ const results = await eslintCLI.lintText(code);
+ const messages = results[0].messages;
+
+ assert.strictEqual(messages.length, 1);
+ assert.strictEqual(messages[0].ruleId, "no-alert");
+ });
+
+ it("should not report a violation by default", async () => {
+ const code = [
+ "alert('test'); // eslint-disable-line no-alert"
+ ].join("\n");
+ const config = {
+ ignore: true,
+ overrideConfigFile: true,
+ allowInlineConfig: true,
+ overrideConfig: {
+ rules: {
+ "eol-last": 0,
+ "no-alert": 1,
+ "no-trailing-spaces": 0,
+ strict: 0,
+ quotes: 0
+ }
+ }
+ };
+ const eslintCLI = new FlatESLint(config);
+ const results = await eslintCLI.lintText(code);
+ const messages = results[0].messages;
+
+ assert.strictEqual(messages.length, 0);
+ });
+ });
+
+ describe("when evaluating code when reportUnusedDisableDirectives is enabled", () => {
+ it("should report problems for unused eslint-disable directives", async () => {
+ const eslint = new FlatESLint({ overrideConfigFile: true, reportUnusedDisableDirectives: "error" });
+
+ assert.deepStrictEqual(
+ await eslint.lintText("/* eslint-disable */"),
+ [
+ {
+ filePath: "",
+ messages: [
+ {
+ ruleId: null,
+ message: "Unused eslint-disable directive (no problems were reported).",
+ line: 1,
+ column: 1,
+ fix: {
+ range: [0, 20],
+ text: " "
+ },
+ severity: 2,
+ nodeType: null
+ }
+ ],
+ errorCount: 1,
+ warningCount: 0,
+ fatalErrorCount: 0,
+ fixableErrorCount: 1,
+ fixableWarningCount: 0,
+ source: "/* eslint-disable */",
+ usedDeprecatedRules: []
+ }
+ ]
+ );
+ });
+ });
+
+ describe("when retrieving version number", () => {
+ it("should return current version number", () => {
+ const eslintCLI = require("../../../lib/eslint/flat-eslint").FlatESLint;
+ const version = eslintCLI.version;
+
+ assert.strictEqual(typeof version, "string");
+ assert(parseInt(version[0], 10) >= 3);
+ });
+ });
+
+ describe("mutability", () => {
+
+ describe("rules", () => {
+ it("Loading rules in one instance doesn't mutate to another instance", async () => {
+ const filePath = getFixturePath("single-quoted.js");
+ const engine1 = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true,
+ overrideConfig: {
+ plugins: {
+ example: {
+ rules: {
+ "example-rule"() {
+ return {};
+ }
+ }
+ }
+ },
+ rules: { "example/example-rule": 1 }
+ }
+ });
+ const engine2 = new FlatESLint({
+ cwd: path.join(fixtureDir, ".."),
+ overrideConfigFile: true
+ });
+ const fileConfig1 = await engine1.calculateConfigForFile(filePath);
+ const fileConfig2 = await engine2.calculateConfigForFile(filePath);
+
+ // plugin
+ assert.deepStrictEqual(fileConfig1.rules["example/example-rule"], [1], "example is present for engine 1");
+ assert.strictEqual(fileConfig2.rules, void 0, "example is not present for engine 2");
+ });
+ });
+ });
+
+ describe("with ignores config", () => {
+ const root = getFixturePath("cli-engine/ignore-patterns");
+
+ describe("ignores can add an ignore pattern ('foo.js').", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root,
+ files: {
+ "eslint.config.js": `module.exports = {
+ ignores: ["**/foo.js"]
+ };`,
+ "foo.js": "",
+ "bar.js": "",
+ "subdir/foo.js": "",
+ "subdir/bar.js": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'isPathIgnored()' should return 'true' for 'foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("foo.js"), true);
+ assert.strictEqual(await engine.isPathIgnored("subdir/foo.js"), true);
+ });
+
+ it("'isPathIgnored()' should return 'false' for 'bar.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("bar.js"), false);
+ assert.strictEqual(await engine.isPathIgnored("subdir/bar.js"), false);
+ });
+
+ it("'lintFiles()' should not verify 'foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("**/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(root, "bar.js"),
+ path.join(root, "eslint.config.js"),
+ path.join(root, "subdir/bar.js")
+ ]);
+ });
+ });
+
+ describe("ignores can add ignore patterns ('**/foo.js', '/bar.js').", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root + Date.now(),
+ files: {
+ "eslint.config.js": `module.exports = {
+ ignores: ["**/foo.js", "bar.js"]
+ };`,
+ "foo.js": "",
+ "bar.js": "",
+ "baz.js": "",
+ "subdir/foo.js": "",
+ "subdir/bar.js": "",
+ "subdir/baz.js": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'isPathIgnored()' should return 'true' for 'foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("foo.js"), true);
+ assert.strictEqual(await engine.isPathIgnored("subdir/foo.js"), true);
+ });
+
+ it("'isPathIgnored()' should return 'true' for '/bar.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("bar.js"), true);
+ assert.strictEqual(await engine.isPathIgnored("subdir/bar.js"), false);
+ });
+
+ it("'lintFiles()' should not verify 'foo.js' and '/bar.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("**/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(getPath(), "baz.js"),
+ path.join(getPath(), "eslint.config.js"),
+ path.join(getPath(), "subdir/bar.js"),
+ path.join(getPath(), "subdir/baz.js")
+ ]);
+ });
+ });
+
+
+ /*
+ * These tests fail due to a bug in fast-flob that doesn't allow
+ * negated patterns inside of ignores. These tests won't work until
+ * this bug is fixed:
+ * https://github.com/mrmlnc/fast-glob/issues/356
+ */
+ xdescribe("ignorePatterns can unignore '/node_modules/foo'.", () => {
+
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root,
+ files: {
+ "eslint.config.js": `module.exports = {
+ ignores: ["!**/node_modules/foo/**"]
+ };`,
+ "node_modules/foo/index.js": "",
+ "node_modules/foo/.dot.js": "",
+ "node_modules/bar/index.js": "",
+ "foo.js": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'isPathIgnored()' should return 'false' for 'node_modules/foo/index.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("node_modules/foo/index.js"), false);
+ });
+
+ it("'isPathIgnored()' should return 'false' for 'node_modules/foo/.dot.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("node_modules/foo/.dot.js"), false);
+ });
+
+ it("'isPathIgnored()' should return 'true' for 'node_modules/bar/index.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("node_modules/bar/index.js"), true);
+ });
+
+ it("'lintFiles()' should verify 'node_modules/foo/index.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("**/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(root, "eslint.config.js"),
+ path.join(root, "foo.js"),
+ path.join(root, "node_modules/foo/index.js")
+ ]);
+ });
+ });
+
+ xdescribe(".eslintignore can re-ignore files that are unignored by ignorePatterns.", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root,
+ files: {
+ "eslint.config.js": `module.exports = ${JSON.stringify({
+ ignores: ["!.*"]
+ })}`,
+ ".eslintignore": ".foo*",
+ ".foo.js": "",
+ ".bar.js": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'isPathIgnored()' should return 'true' for re-ignored '.foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored(".foo.js"), true);
+ });
+
+ it("'isPathIgnored()' should return 'false' for unignored '.bar.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored(".bar.js"), false);
+ });
+
+ it("'lintFiles()' should not lint re-ignored '.foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("**/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(root, ".bar.js"),
+ path.join(root, "eslint.config.js")
+ ]);
+ });
+ });
+
+ xdescribe(".eslintignore can unignore files that are ignored by ignorePatterns.", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root,
+ files: {
+ "eslint.config.js": `module.exports = ${JSON.stringify({
+ ignores: ["**/*.js"]
+ })}`,
+ ".eslintignore": "!foo.js",
+ "foo.js": "",
+ "bar.js": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'isPathIgnored()' should return 'false' for unignored 'foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("foo.js"), false);
+ });
+
+ it("'isPathIgnored()' should return 'true' for ignored 'bar.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+
+ assert.strictEqual(await engine.isPathIgnored("bar.js"), true);
+ });
+
+ it("'lintFiles()' should verify unignored 'foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("**/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(root, "foo.js")
+ ]);
+ });
+ });
+
+ describe("ignores in a config file should not be used if ignore: false.", () => {
+
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root,
+ files: {
+ "eslint.config.js": `module.exports = {
+ ignores: ["*.js"]
+ }`,
+ "foo.js": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'isPathIgnored()' should return 'false' for 'foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath(), ignore: false });
+
+ assert.strictEqual(await engine.isPathIgnored("foo.js"), false);
+ });
+
+ it("'lintFiles()' should verify 'foo.js'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath(), ignore: false });
+ const filePaths = (await engine.lintFiles("**/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(root, "eslint.config.js"),
+ path.join(root, "foo.js")
+ ]);
+ });
+ });
+
+ });
+
+ describe("config.files adds lint targets", () => {
+ const root = getFixturePath("cli-engine/additional-lint-targets");
+
+
+ describe("if { files: 'foo/*.txt', ignores: '**/ignore.txt' } is present,", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root + 1,
+ files: {
+ "eslint.config.js": `module.exports = [{
+ files: ["foo/*.txt"],
+ ignores: ["**/ignore.txt"]
+ }];`,
+ "foo/nested/test.txt": "",
+ "foo/test.js": "",
+ "foo/test.txt": "",
+ "foo/ignore.txt": "",
+ "bar/test.js": "",
+ "bar/test.txt": "",
+ "bar/ignore.txt": "",
+ "test.js": "",
+ "test.txt": "",
+ "ignore.txt": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'lintFiles()' with a directory path should contain 'foo/test.txt'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("."))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(getPath(), "bar/test.js"),
+ path.join(getPath(), "eslint.config.js"),
+ path.join(getPath(), "foo/test.js"),
+ path.join(getPath(), "foo/test.txt"),
+ path.join(getPath(), "test.js")
+ ]);
+ });
+
+ it("'lintFiles()' with a glob pattern '*.js' should not contain 'foo/test.txt'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("**/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(getPath(), "bar/test.js"),
+ path.join(getPath(), "eslint.config.js"),
+ path.join(getPath(), "foo/test.js"),
+ path.join(getPath(), "test.js")
+ ]);
+ });
+ });
+
+ describe("if { files: 'foo/*.txt', ignores: '**/ignore.txt' } is present and subdirectory is passed,", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root + 2,
+ files: {
+ "eslint.config.js": `module.exports = [{
+ files: ["foo/*.txt"],
+ ignores: ["**/ignore.txt"]
+ }];`,
+ "foo/nested/test.txt": "",
+ "foo/test.js": "",
+ "foo/test.txt": "",
+ "foo/ignore.txt": "",
+ "bar/test.js": "",
+ "bar/test.txt": "",
+ "bar/ignore.txt": "",
+ "test.js": "",
+ "test.txt": "",
+ "ignore.txt": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'lintFiles()' with a directory path should contain 'foo/test.txt'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("foo"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(getPath(), "foo/test.js"),
+ path.join(getPath(), "foo/test.txt")
+ ]);
+ });
+
+ it("'lintFiles()' with a glob pattern '*.js' should not contain 'foo/test.txt'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("foo/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(getPath(), "foo/test.js")
+ ]);
+ });
+ });
+
+ describe("if { files: 'foo/**/*.txt' } is present,", () => {
+
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root + 3,
+ files: {
+ "eslint.config.js": `module.exports = [
+ {
+ files: ["foo/**/*.txt"]
+ }
+ ]`,
+ "foo/nested/test.txt": "",
+ "foo/test.js": "",
+ "foo/test.txt": "",
+ "bar/test.js": "",
+ "bar/test.txt": "",
+ "test.js": "",
+ "test.txt": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'lintFiles()' with a directory path should contain 'foo/test.txt' and 'foo/nested/test.txt'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("."))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(getPath(), "bar/test.js"),
+ path.join(getPath(), "eslint.config.js"),
+ path.join(getPath(), "foo/nested/test.txt"),
+ path.join(getPath(), "foo/test.js"),
+ path.join(getPath(), "foo/test.txt"),
+ path.join(getPath(), "test.js")
+ ]);
+ });
+ });
+
+ describe("if { files: 'foo/**/*' } is present,", () => {
+
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: root + 4,
+ files: {
+ "eslint.config.js": `module.exports = [
+ {
+ files: ["foo/**/*"]
+ }
+ ]`,
+ "foo/nested/test.txt": "",
+ "foo/test.js": "",
+ "foo/test.txt": "",
+ "bar/test.js": "",
+ "bar/test.txt": "",
+ "test.js": "",
+ "test.txt": ""
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'lintFiles()' with a directory path should NOT contain 'foo/test.txt' and 'foo/nested/test.txt'.", async () => {
+ const engine = new FlatESLint({ cwd: getPath() });
+ const filePaths = (await engine.lintFiles("."))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(filePaths, [
+ path.join(getPath(), "bar/test.js"),
+ path.join(getPath(), "eslint.config.js"),
+ path.join(getPath(), "foo/test.js"),
+ path.join(getPath(), "test.js")
+ ]);
+ });
+ });
+
+ });
+
+ describe("'ignores', 'files' of the configuration that the '--config' option provided should be resolved from CWD.", () => {
+ const root = getFixturePath("cli-engine/config-and-overrides-files");
+
+ describe("if { files: 'foo/*.txt', ... } is present by '--config node_modules/myconf/eslint.config.js',", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: `${root}a1`,
+ files: {
+ "node_modules/myconf/eslint.config.js": `module.exports = [
+ {
+ files: ["foo/*.js"],
+ rules: {
+ eqeqeq: "error"
+ }
+ }
+ ];`,
+ "node_modules/myconf/foo/test.js": "a == b",
+ "foo/test.js": "a == b"
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'lintFiles()' with 'foo/test.js' should use the files entry.", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: "node_modules/myconf/eslint.config.js",
+ cwd: getPath(),
+ ignore: false
+ });
+ const results = await engine.lintFiles("foo/test.js");
+
+ // Expected to be an 'eqeqeq' error because the file matches to `$CWD/foo/*.js`.
+ assert.deepStrictEqual(results, [
+ {
+ errorCount: 1,
+ filePath: path.join(getPath(), "foo/test.js"),
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ messages: [
+ {
+ column: 3,
+ endColumn: 5,
+ endLine: 1,
+ line: 1,
+ message: "Expected '===' and instead saw '=='.",
+ messageId: "unexpected",
+ nodeType: "BinaryExpression",
+ ruleId: "eqeqeq",
+ severity: 2
+ }
+ ],
+ source: "a == b",
+ usedDeprecatedRules: [],
+ warningCount: 0,
+ fatalErrorCount: 0
+ }
+ ]);
+ });
+
+ it("'lintFiles()' with 'node_modules/myconf/foo/test.js' should NOT use the files entry.", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: "node_modules/myconf/eslint.config.js",
+ cwd: getPath(),
+ ignore: false
+ });
+ const results = await engine.lintFiles("node_modules/myconf/foo/test.js");
+
+ // Expected to be no errors because the file doesn't match to `$CWD/foo/*.js`.
+ assert.deepStrictEqual(results, [
+ {
+ errorCount: 0,
+ filePath: path.join(getPath(), "node_modules/myconf/foo/test.js"),
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ messages: [
+ {
+ fatal: false,
+ message: "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override.",
+ severity: 1
+ }
+ ],
+ usedDeprecatedRules: [],
+ warningCount: 1,
+ fatalErrorCount: 0
+ }
+ ]);
+ });
+ });
+
+ describe("if { files: '*', ignores: 'foo/*.txt', ... } is present by '--config bar/myconf/eslint.config.js',", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: `${root}a2`,
+ files: {
+ "bar/myconf/eslint.config.js": `module.exports = [
+ {
+ files: ["**/*"],
+ ignores: ["foo/*.js"],
+ rules: {
+ eqeqeq: "error"
+ }
+ }
+ ]`,
+ "bar/myconf/foo/test.js": "a == b",
+ "foo/test.js": "a == b"
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'lintFiles()' with 'foo/test.js' should have no errors because no rules are enabled.", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: "bar/myconf/eslint.config.js",
+ cwd: getPath(),
+ ignore: false
+ });
+ const results = await engine.lintFiles("foo/test.js");
+
+ // Expected to be no errors because the file matches to `$CWD/foo/*.js`.
+ assert.deepStrictEqual(results, [
+ {
+ errorCount: 0,
+ filePath: path.join(getPath(), "foo/test.js"),
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ messages: [],
+ usedDeprecatedRules: [],
+ warningCount: 0,
+ fatalErrorCount: 0
+ }
+ ]);
+ });
+
+ it("'lintFiles()' with 'bar/myconf/foo/test.js' should have an error because eqeqeq is enabled.", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: "bar/myconf/eslint.config.js",
+ cwd: getPath(),
+ ignore: false
+ });
+ const results = await engine.lintFiles("bar/myconf/foo/test.js");
+
+ // Expected to be an 'eqeqeq' error because the file doesn't match to `$CWD/foo/*.js`.
+ assert.deepStrictEqual(results, [
+ {
+ errorCount: 1,
+ filePath: path.join(getPath(), "bar/myconf/foo/test.js"),
+ fixableErrorCount: 0,
+ fixableWarningCount: 0,
+ messages: [
+ {
+ column: 3,
+ endColumn: 5,
+ endLine: 1,
+ line: 1,
+ message: "Expected '===' and instead saw '=='.",
+ messageId: "unexpected",
+ nodeType: "BinaryExpression",
+ ruleId: "eqeqeq",
+ severity: 2
+ }
+ ],
+ source: "a == b",
+ usedDeprecatedRules: [],
+ warningCount: 0,
+ fatalErrorCount: 0
+ }
+ ]);
+ });
+ });
+
+ // dependent on https://github.com/mrmlnc/fast-glob/issues/86
+ xdescribe("if { ignores: 'foo/*.js', ... } is present by '--config node_modules/myconf/eslint.config.js',", () => {
+ const { prepare, cleanup, getPath } = createCustomTeardown({
+ cwd: `${root}a3`,
+ files: {
+ "node_modules/myconf/eslint.config.js": `module.exports = {
+ ignores: ["**/eslint.config.js", "!node_modules/myconf", "foo/*.js"],
+ rules: {
+ eqeqeq: "error"
+ }
+ }`,
+ "node_modules/myconf/foo/test.js": "a == b",
+ "foo/test.js": "a == b"
+ }
+ });
+
+ beforeEach(prepare);
+ afterEach(cleanup);
+
+ it("'lintFiles()' with '**/*.js' should iterate 'node_modules/myconf/foo/test.js' but not 'foo/test.js'.", async () => {
+ const engine = new FlatESLint({
+ overrideConfigFile: "node_modules/myconf/eslint.config.js",
+ cwd: getPath()
+ });
+ const files = (await engine.lintFiles("**/*.js"))
+ .map(r => r.filePath)
+ .sort();
+
+ assert.deepStrictEqual(files, [
+ path.join(getPath(), "node_modules/myconf/foo/test.js")
+ ]);
+ });
+ });
+ });
+
+});
diff --git a/tests/lib/linter/apply-disable-directives.js b/tests/lib/linter/apply-disable-directives.js
index 512e400832e..de56f729627 100644
--- a/tests/lib/linter/apply-disable-directives.js
+++ b/tests/lib/linter/apply-disable-directives.js
@@ -667,7 +667,7 @@ describe("apply-disable-directives", () => {
line: 1,
column: 1,
ruleId: null,
- justification: "justificatiion"
+ justification: "justification"
}],
problems: [{ line: 3, column: 3, ruleId: "foo" }]
}),
diff --git a/tests/lib/linter/code-path-analysis/code-path.js b/tests/lib/linter/code-path-analysis/code-path.js
index 760d5b39989..40fb017ed7b 100644
--- a/tests/lib/linter/code-path-analysis/code-path.js
+++ b/tests/lib/linter/code-path-analysis/code-path.js
@@ -54,7 +54,7 @@ function getOrderOfTraversing(codePath, options, callback) {
codePath.traverseSegments(options, (segment, controller) => {
retv.push(segment.id);
if (callback) {
- callback(segment, controller); // eslint-disable-line node/callback-return -- At end of inner function
+ callback(segment, controller); // eslint-disable-line n/callback-return -- At end of inner function
}
});
@@ -69,7 +69,7 @@ describe("CodePathAnalyzer", () => {
/*
* If you need to output the code paths and DOT graph information for a
- * particular piece of code, udpate and uncomment the following test and
+ * particular piece of code, update and uncomment the following test and
* then run:
* DEBUG=eslint:code-path npx mocha tests/lib/linter/code-path-analysis/
*
diff --git a/tests/lib/linter/config-comment-parser.js b/tests/lib/linter/config-comment-parser.js
index f51fe693a73..e9f595d7750 100644
--- a/tests/lib/linter/config-comment-parser.js
+++ b/tests/lib/linter/config-comment-parser.js
@@ -215,7 +215,7 @@ describe("ConfigCommentParser", () => {
});
});
- it("should parse list config with two items and exta whitespace", () => {
+ it("should parse list config with two items and extra whitespace", () => {
const code = " a , b ";
const result = commentParser.parseListConfig(code);
diff --git a/tests/lib/linter/linter.js b/tests/lib/linter/linter.js
index 8c121808e1b..407194d47e7 100644
--- a/tests/lib/linter/linter.js
+++ b/tests/lib/linter/linter.js
@@ -2625,7 +2625,7 @@ describe("Linter", () => {
assert.strictEqual(suppressedMessages[1].ruleId, "quotes");
});
- it("should ignore violations of multiple rules when specified in mixed sinlge line and multi line comments", () => {
+ it("should ignore violations of multiple rules when specified in mixed single line and multi line comments", () => {
const code = [
"/* eslint-disable-next-line",
"no-alert",
@@ -3915,7 +3915,7 @@ var a = "test2";
assert.strictEqual(suppressedMessages[0].suppressions.length, 2);
});
- it("reports problems for multiple unused eslint-disable comments with mutliple ruleIds", () => {
+ it("reports problems for multiple unused eslint-disable comments with multiple ruleIds", () => {
const code = [
"/* eslint no-undef: 2, no-void: 2 */",
"/* eslint-disable no-undef -- j1 */",
@@ -6660,6 +6660,31 @@ var a = "test2";
assert.strictEqual(preprocess.calledOnce, true);
assert.deepStrictEqual(preprocess.args[0], [code, filename]);
});
+
+ it("should catch preprocess error.", () => {
+ const code = "foo";
+ const preprocess = sinon.spy(() => {
+ throw Object.assign(new SyntaxError("Invalid syntax"), {
+ lineNumber: 1,
+ column: 1
+ });
+ });
+
+ const messages = linter.verify(code, {}, { filename, preprocess });
+
+ assert.strictEqual(preprocess.calledOnce, true);
+ assert.deepStrictEqual(preprocess.args[0], [code, filename]);
+ assert.deepStrictEqual(messages, [
+ {
+ ruleId: null,
+ fatal: true,
+ severity: 2,
+ message: "Preprocessing error: Invalid syntax",
+ line: 1,
+ column: 1
+ }
+ ]);
+ });
});
describe("postprocessors", () => {
@@ -7000,6 +7025,22 @@ var a = "test2";
assert(ok);
});
+
+ it("should throw when rule's create() function does not return an object", () => {
+ const config = { rules: { checker: "error" } };
+
+ linter.defineRule("checker", () => null); // returns null
+
+ assert.throws(() => {
+ linter.verify("abc", config, filename);
+ }, "The create() function for rule 'checker' did not return an object.");
+
+ linter.defineRule("checker", () => {}); // returns undefined
+
+ assert.throws(() => {
+ linter.verify("abc", config, filename);
+ }, "The create() function for rule 'checker' did not return an object.");
+ });
});
describe("Custom parser", () => {
@@ -7106,7 +7147,7 @@ var a = "test2";
it("should not modify a parser error message without a leading line: prefix", () => {
linter.defineParser("no-line-error", testParsers.noLineError);
- const messages = linter.verify(";", { parser: "no-line-error" }, "filename");
+ const messages = linter.verify(";", { parser: "no-line-error" }, filename);
const suppressedMessages = linter.getSuppressedMessages();
assert.strictEqual(messages.length, 1);
@@ -7909,7 +7950,7 @@ describe("Linter with FlatConfigArray", () => {
languageOptions: {
parser: testParsers.lineError
}
- }, "filename");
+ }, filename);
const suppressedMessages = linter.getSuppressedMessages();
assert.strictEqual(messages.length, 1);
@@ -7924,7 +7965,7 @@ describe("Linter with FlatConfigArray", () => {
languageOptions: {
parser: testParsers.noLineError
}
- }, "filename");
+ }, filename);
const suppressedMessages = linter.getSuppressedMessages();
assert.strictEqual(messages.length, 1);
@@ -8237,7 +8278,7 @@ describe("Linter with FlatConfigArray", () => {
it("should report an error when JSX code is encountered and JSX is not enabled", () => {
const code = "var myDivElement = ;";
- const messages = linter.verify(code, {}, "filename");
+ const messages = linter.verify(code, {}, filename);
const suppressedMessages = linter.getSuppressedMessages();
assert.strictEqual(messages.length, 1);
@@ -8258,7 +8299,7 @@ describe("Linter with FlatConfigArray", () => {
}
}
}
- }, "filename");
+ }, filename);
const suppressedMessages = linter.getSuppressedMessages();
assert.strictEqual(messages.length, 0);
@@ -8277,7 +8318,7 @@ describe("Linter with FlatConfigArray", () => {
}
}
- }, "filename");
+ }, "filename.js");
const suppressedMessages = linter.getSuppressedMessages();
assert.strictEqual(messages.length, 0);
@@ -8577,6 +8618,23 @@ describe("Linter with FlatConfigArray", () => {
assert.strictEqual(suppressedMessages.length, 0);
});
+ it("should report ignored file when filename isn't matched in the config array", () => {
+
+ const code = "foo()\n alert('test')";
+ const config = { rules: { "no-mixed-spaces-and-tabs": 1, "eol-last": 1, semi: [1, "always"] } };
+
+ const messages = linter.verify(code, config, "filename.ts");
+
+ assert.strictEqual(messages.length, 1);
+ assert.deepStrictEqual(messages[0], {
+ ruleId: null,
+ severity: 1,
+ message: "No matching configuration found for filename.ts.",
+ line: 0,
+ column: 0
+ });
+ });
+
describe("Plugins", () => {
it("should not load rule definition when rule isn't used", () => {
@@ -12562,7 +12620,7 @@ var a = "test2";
const code = `
/* eslint-disable-next-line no-alert --
description on why this exception is seen as appropriate but past a
- comfortable reading line length
+ comfortable reading line length
*/
alert("buzz");
`;
@@ -12689,7 +12747,7 @@ var a = "test2";
assert.strictEqual(suppressedMessages[1].ruleId, "quotes");
});
- it("should ignore violations of multiple rules when specified in mixed sinlge line and multi line comments", () => {
+ it("should ignore violations of multiple rules when specified in mixed single line and multi line comments", () => {
const code = [
"/* eslint-disable-next-line",
"no-alert",
@@ -15142,6 +15200,37 @@ var a = "test2";
assert.strictEqual(preprocess.calledOnce, true);
assert.deepStrictEqual(preprocess.args[0], [code, filename]);
});
+
+ it("should catch preprocess error.", () => {
+ const code = "foo";
+ const preprocess = sinon.spy(() => {
+ throw Object.assign(new SyntaxError("Invalid syntax"), {
+ lineNumber: 1,
+ column: 1
+ });
+ });
+
+ const configs = createFlatConfigArray([
+ extraConfig
+ ]);
+
+ configs.normalizeSync();
+
+ const messages = linter.verify(code, configs, { filename, preprocess });
+
+ assert.strictEqual(preprocess.calledOnce, true);
+ assert.deepStrictEqual(preprocess.args[0], [code, filename]);
+ assert.deepStrictEqual(messages, [
+ {
+ ruleId: null,
+ fatal: true,
+ severity: 2,
+ message: "Preprocessing error: Invalid syntax",
+ line: 1,
+ column: 1
+ }
+ ]);
+ });
});
describe("postprocessors", () => {
diff --git a/tests/lib/linter/node-event-generator.js b/tests/lib/linter/node-event-generator.js
index 4004f7a2835..2719bf30e30 100644
--- a/tests/lib/linter/node-event-generator.js
+++ b/tests/lib/linter/node-event-generator.js
@@ -60,7 +60,7 @@ describe("NodeEventGenerator", () => {
assert(emitter.emit.calledWith("Foo", dummyNode));
});
- it("should generate events for exitting AST node.", () => {
+ it("should generate events for exiting AST node.", () => {
const dummyNode = { type: "Foo", value: 1 };
generator.leaveNode(dummyNode);
diff --git a/tests/lib/rule-tester/rule-tester.js b/tests/lib/rule-tester/rule-tester.js
index ba12bdc38a2..0e35258750c 100644
--- a/tests/lib/rule-tester/rule-tester.js
+++ b/tests/lib/rule-tester/rule-tester.js
@@ -1710,73 +1710,6 @@ describe("RuleTester", () => {
}, "Error must specify 'messageId' if 'data' is used.");
});
- // fixable rules with or without `meta` property
- it("should not throw an error if a rule that has `meta.fixable` produces fixes", () => {
- const replaceProgramWith5Rule = {
- meta: {
- fixable: "code"
- },
- create(context) {
- return {
- Program(node) {
- context.report({ node, message: "bad", fix: fixer => fixer.replaceText(node, "5") });
- }
- };
- }
- };
-
- ruleTester.run("replaceProgramWith5", replaceProgramWith5Rule, {
- valid: [],
- invalid: [
- { code: "var foo = bar;", output: "5", errors: 1 }
- ]
- });
- });
- it("should throw an error if a new-format rule that doesn't have `meta` produces fixes", () => {
- const replaceProgramWith5Rule = {
- create(context) {
- return {
- Program(node) {
- context.report({ node, message: "bad", fix: fixer => fixer.replaceText(node, "5") });
- }
- };
- }
- };
-
- assert.throws(() => {
- ruleTester.run("replaceProgramWith5", replaceProgramWith5Rule, {
- valid: [],
- invalid: [
- { code: "var foo = bar;", output: "5", errors: 1 }
- ]
- });
- }, /Fixable rules must set the `meta\.fixable` property/u);
- });
- it("should throw an error if a legacy-format rule produces fixes", () => {
-
- /**
- * Legacy-format rule (a function instead of an object with `create` method).
- * @param {RuleContext} context The ESLint rule context object.
- * @returns {Object} Listeners.
- */
- function replaceProgramWith5Rule(context) {
- return {
- Program(node) {
- context.report({ node, message: "bad", fix: fixer => fixer.replaceText(node, "5") });
- }
- };
- }
-
- assert.throws(() => {
- ruleTester.run("replaceProgramWith5", replaceProgramWith5Rule, {
- valid: [],
- invalid: [
- { code: "var foo = bar;", output: "5", errors: 1 }
- ]
- });
- }, /Fixable rules must set the `meta\.fixable` property/u);
- });
-
describe("suggestions", () => {
it("should pass with valid suggestions (tested using desc)", () => {
ruleTester.run("suggestions-basic", require("../../fixtures/testers/rule-tester/suggestions").basic, {
@@ -2295,6 +2228,265 @@ describe("RuleTester", () => {
});
});
+ describe("deprecations", () => {
+ let processStub;
+ const ruleWithNoSchema = {
+ meta: {
+ type: "suggestion"
+ },
+ create(context) {
+ return {
+ Program(node) {
+ context.report({ node, message: "bad" });
+ }
+ };
+ }
+ };
+ const ruleWithNoMeta = {
+ create(context) {
+ return {
+ Program(node) {
+ context.report({ node, message: "bad" });
+ }
+ };
+ }
+ };
+
+ beforeEach(() => {
+ processStub = sinon.stub(process, "emitWarning");
+ });
+
+ afterEach(() => {
+ processStub.restore();
+ });
+
+ it("should log a deprecation warning when using the legacy function-style API for rule", () => {
+
+ /**
+ * Legacy-format rule (a function instead of an object with `create` method).
+ * @param {RuleContext} context The ESLint rule context object.
+ * @returns {Object} Listeners.
+ */
+ function functionStyleRule(context) {
+ return {
+ Program(node) {
+ context.report({ node, message: "bad" });
+ }
+ };
+ }
+
+ ruleTester.run("function-style-rule", functionStyleRule, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 1, "calls `process.emitWarning()` once");
+ assert.deepStrictEqual(
+ processStub.getCall(0).args,
+ [
+ "\"function-style-rule\" rule is using the deprecated function-style format and will stop working in ESLint v9. Please use object-style format: https://eslint.org/docs/developer-guide/working-with-rules",
+ "DeprecationWarning"
+ ]
+ );
+ });
+
+ it("should log a deprecation warning when meta is not defined for the rule", () => {
+ ruleTester.run("rule-with-no-meta-1", ruleWithNoMeta, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", options: [{ foo: true }], errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 1, "calls `process.emitWarning()` once");
+ assert.deepStrictEqual(
+ processStub.getCall(0).args,
+ [
+ "\"rule-with-no-meta-1\" rule has options but is missing the \"meta.schema\" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/developer-guide/working-with-rules#options-schemas",
+ "DeprecationWarning"
+ ]
+ );
+ });
+
+ it("should log a deprecation warning when schema is not defined for the rule", () => {
+ ruleTester.run("rule-with-no-schema-1", ruleWithNoSchema, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", options: [{ foo: true }], errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 1, "calls `process.emitWarning()` once");
+ assert.deepStrictEqual(
+ processStub.getCall(0).args,
+ [
+ "\"rule-with-no-schema-1\" rule has options but is missing the \"meta.schema\" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/developer-guide/working-with-rules#options-schemas",
+ "DeprecationWarning"
+ ]
+ );
+ });
+
+ it("should log a deprecation warning when schema is `undefined`", () => {
+ const ruleWithUndefinedSchema = {
+ meta: {
+ type: "problem",
+ // eslint-disable-next-line no-undefined -- intentioally added for test case
+ schema: undefined
+ },
+ create(context) {
+ return {
+ Program(node) {
+ context.report({ node, message: "bad" });
+ }
+ };
+ }
+ };
+
+ ruleTester.run("rule-with-undefined-schema", ruleWithUndefinedSchema, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", options: [{ foo: true }], errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 1, "calls `process.emitWarning()` once");
+ assert.deepStrictEqual(
+ processStub.getCall(0).args,
+ [
+ "\"rule-with-undefined-schema\" rule has options but is missing the \"meta.schema\" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/developer-guide/working-with-rules#options-schemas",
+ "DeprecationWarning"
+ ]
+ );
+ });
+
+ it("should log a deprecation warning when schema is `null`", () => {
+ const ruleWithNullSchema = {
+ meta: {
+ type: "problem",
+ schema: null
+ },
+ create(context) {
+ return {
+ Program(node) {
+ context.report({ node, message: "bad" });
+ }
+ };
+ }
+ };
+
+ ruleTester.run("rule-with-null-schema", ruleWithNullSchema, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", options: [{ foo: true }], errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 1, "calls `process.emitWarning()` once");
+ assert.deepStrictEqual(
+ processStub.getCall(0).args,
+ [
+ "\"rule-with-null-schema\" rule has options but is missing the \"meta.schema\" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/developer-guide/working-with-rules#options-schemas",
+ "DeprecationWarning"
+ ]
+ );
+ });
+
+ it("should not log a deprecation warning when schema is an empty array", () => {
+ const ruleWithEmptySchema = {
+ meta: {
+ type: "suggestion",
+ schema: []
+ },
+ create(context) {
+ return {
+ Program(node) {
+ context.report({ node, message: "bad" });
+ }
+ };
+ }
+ };
+
+ ruleTester.run("rule-with-no-options", ruleWithEmptySchema, {
+ valid: [],
+ invalid: [{ code: "var foo = bar;", errors: 1 }]
+ });
+
+ assert.strictEqual(processStub.callCount, 0, "never calls `process.emitWarning()`");
+ });
+
+ it("When the rule is an object-style rule, the legacy rule API warning is not emitted", () => {
+ ruleTester.run("rule-with-no-schema-2", ruleWithNoSchema, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 0, "never calls `process.emitWarning()`");
+ });
+
+ it("When the rule has meta.schema and there are test cases with options, the missing schema warning is not emitted", () => {
+ const ruleWithSchema = {
+ meta: {
+ type: "suggestion",
+ schema: [{
+ type: "boolean"
+ }]
+ },
+ create(context) {
+ return {
+ Program(node) {
+ context.report({ node, message: "bad" });
+ }
+ };
+ }
+ };
+
+ ruleTester.run("rule-with-schema", ruleWithSchema, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", options: [true], errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 0, "never calls `process.emitWarning()`");
+ });
+
+ it("When the rule does not have meta, but there are no test cases with options, the missing schema warning is not emitted", () => {
+ ruleTester.run("rule-with-no-meta-2", ruleWithNoMeta, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 0, "never calls `process.emitWarning()`");
+ });
+
+ it("When the rule has meta without meta.schema, but there are no test cases with options, the missing schema warning is not emitted", () => {
+ ruleTester.run("rule-with-no-schema-3", ruleWithNoSchema, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 0, "never calls `process.emitWarning()`");
+ });
+ it("When the rule has meta without meta.schema, and some test cases have options property but it's an empty array, the missing schema warning is not emitted", () => {
+ ruleTester.run("rule-with-no-schema-4", ruleWithNoSchema, {
+ valid: [],
+ invalid: [
+ { code: "var foo = bar;", options: [], errors: 1 }
+ ]
+ });
+
+ assert.strictEqual(processStub.callCount, 0, "never calls `process.emitWarning()`");
+ });
+ });
+
/**
* Asserts that a particular value will be emitted from an EventEmitter.
* @param {EventEmitter} emitter The emitter that should emit a value
diff --git a/tests/lib/rules/array-bracket-newline.js b/tests/lib/rules/array-bracket-newline.js
index 90ee8213b77..3f2b66f549f 100644
--- a/tests/lib/rules/array-bracket-newline.js
+++ b/tests/lib/rules/array-bracket-newline.js
@@ -440,7 +440,7 @@ ruleTester.run("array-bracket-newline", rule, {
invalid: [
- // default : { mutliline : true}
+ // default : { multiline : true}
{
code: `var foo = [
[1,2]
diff --git a/tests/lib/rules/arrow-parens.js b/tests/lib/rules/arrow-parens.js
index d2f32a784a3..c7af7f6dea8 100644
--- a/tests/lib/rules/arrow-parens.js
+++ b/tests/lib/rules/arrow-parens.js
@@ -46,7 +46,7 @@ const valid = [
{ code: "a.then((foo) => {});", options: ["always"] },
{ code: "a.then((foo) => { if (true) {}; });", options: ["always"] },
{ code: "a.then(async (foo) => { if (true) {}; });", options: ["always"], parserOptions: { ecmaVersion: 8 } },
- { code: "(a: T) => a", options: ["always"], parser: parser("identifer-type") },
+ { code: "(a: T) => a", options: ["always"], parser: parser("identifier-type") },
{ code: "(a): T => a", options: ["always"], parser: parser("return-type") },
// "as-needed"
@@ -64,7 +64,7 @@ const valid = [
{ code: "async a => a", options: ["as-needed"], parserOptions: { ecmaVersion: 8 } },
{ code: "async ([a, b]) => {}", options: ["as-needed"], parserOptions: { ecmaVersion: 8 } },
{ code: "async (a, b) => {}", options: ["as-needed"], parserOptions: { ecmaVersion: 8 } },
- { code: "(a: T) => a", options: ["as-needed"], parser: parser("identifer-type") },
+ { code: "(a: T) => a", options: ["as-needed"], parser: parser("identifier-type") },
{ code: "(a): T => a", options: ["as-needed"], parser: parser("return-type") },
// "as-needed", { "requireForBlockBody": true }
@@ -83,7 +83,7 @@ const valid = [
{ code: "a => ({})", options: ["as-needed", { requireForBlockBody: true }] },
{ code: "async a => ({})", options: ["as-needed", { requireForBlockBody: true }], parserOptions: { ecmaVersion: 8 } },
{ code: "async a => a", options: ["as-needed", { requireForBlockBody: true }], parserOptions: { ecmaVersion: 8 } },
- { code: "(a: T) => a", options: ["as-needed", { requireForBlockBody: true }], parser: parser("identifer-type") },
+ { code: "(a: T) => a", options: ["as-needed", { requireForBlockBody: true }], parser: parser("identifier-type") },
{ code: "(a): T => a", options: ["as-needed", { requireForBlockBody: true }], parser: parser("return-type") },
{
code: "const f = (/** @type {number} */a/**hello*/) => a + a;",
diff --git a/tests/lib/rules/camelcase.js b/tests/lib/rules/camelcase.js
index 79c237ce202..f634c71b43d 100644
--- a/tests/lib/rules/camelcase.js
+++ b/tests/lib/rules/camelcase.js
@@ -409,7 +409,7 @@ ruleTester.run("camelcase", rule, {
parserOptions: { ecmaVersion: 2022 }
},
- // Combinations of `properties` and `ignoreDestructring`
+ // Combinations of `properties` and `ignoreDestructuring`
{
code: `
const { some_property } = obj;
@@ -1447,7 +1447,7 @@ ruleTester.run("camelcase", rule, {
errors: [{ messageId: "notCamelCasePrivate", data: { name: "snake_case" } }]
},
- // Combinations of `properties` and `ignoreDestructring`
+ // Combinations of `properties` and `ignoreDestructuring`
{
code: `
const { some_property } = obj;
diff --git a/tests/lib/rules/comma-spacing.js b/tests/lib/rules/comma-spacing.js
index df7dac6324a..a3b23b62d73 100644
--- a/tests/lib/rules/comma-spacing.js
+++ b/tests/lib/rules/comma-spacing.js
@@ -27,19 +27,36 @@ ruleTester.run("comma-spacing", rule, {
"myfunc(404, // comment\n true, /* bla bla bla */ 'hello');",
{ code: "myfunc(404, // comment\n true,/* bla bla bla */ 'hello');", options: [{ before: false, after: false }] },
"var a = 1, b = 2;",
+ "var arr = [,];",
"var arr = [, ];",
+ "var arr = [ ,];",
+ "var arr = [ , ];",
+ "var arr = [1,];",
"var arr = [1, ];",
"var arr = [, 2];",
+ "var arr = [ , 2];",
"var arr = [1, 2];",
+ "var arr = [,,];",
+ "var arr = [ ,,];",
+ "var arr = [, ,];",
+ "var arr = [,, ];",
+ "var arr = [ , ,];",
+ "var arr = [ ,, ];",
"var arr = [, , ];",
+ "var arr = [ , , ];",
"var arr = [1, , ];",
"var arr = [, 2, ];",
"var arr = [, , 3];",
+ "var arr = [,, 3];",
"var arr = [1, 2, ];",
"var arr = [, 2, 3];",
"var arr = [1, , 3];",
"var arr = [1, 2, 3];",
+ "var arr = [1, 2, 3,];",
+ "var arr = [1, 2, 3, ];",
"var obj = {'foo':'bar', 'baz':'qur'};",
+ "var obj = {'foo':'bar', 'baz':'qur', };",
+ "var obj = {'foo':'bar', 'baz':'qur',};",
"var obj = {'foo':'bar', 'baz':\n'qur'};",
"var obj = {'foo':\n'bar', 'baz':\n'qur'};",
"function foo(a, b){}",
@@ -74,20 +91,34 @@ ruleTester.run("comma-spacing", rule, {
{ code: "var a = 1 ,b = 2;", options: [{ before: true, after: false }] },
{ code: "function foo(a ,b){}", options: [{ before: true, after: false }] },
{ code: "var arr = [,];", options: [{ before: true, after: false }] },
+ { code: "var arr = [ ,];", options: [{ before: true, after: false }] },
+ { code: "var arr = [, ];", options: [{ before: true, after: false }] },
+ { code: "var arr = [ , ];", options: [{ before: true, after: false }] },
{ code: "var arr = [1 ,];", options: [{ before: true, after: false }] },
+ { code: "var arr = [1 , ];", options: [{ before: true, after: false }] },
{ code: "var arr = [ ,2];", options: [{ before: true, after: false }] },
{ code: "var arr = [1 ,2];", options: [{ before: true, after: false }] },
{ code: "var arr = [,,];", options: [{ before: true, after: false }] },
+ { code: "var arr = [ ,,];", options: [{ before: true, after: false }] },
+ { code: "var arr = [, ,];", options: [{ before: true, after: false }] },
+ { code: "var arr = [,, ];", options: [{ before: true, after: false }] },
+ { code: "var arr = [ , ,];", options: [{ before: true, after: false }] },
+ { code: "var arr = [ ,, ];", options: [{ before: true, after: false }] },
+ { code: "var arr = [, , ];", options: [{ before: true, after: false }] },
+ { code: "var arr = [ , , ];", options: [{ before: true, after: false }] },
{ code: "var arr = [1 , ,];", options: [{ before: true, after: false }] },
{ code: "var arr = [ ,2 ,];", options: [{ before: true, after: false }] },
+ { code: "var arr = [,2 , ];", options: [{ before: true, after: false }] },
{ code: "var arr = [ , ,3];", options: [{ before: true, after: false }] },
{ code: "var arr = [1 ,2 ,];", options: [{ before: true, after: false }] },
{ code: "var arr = [ ,2 ,3];", options: [{ before: true, after: false }] },
{ code: "var arr = [1 , ,3];", options: [{ before: true, after: false }] },
{ code: "var arr = [1 ,2 ,3];", options: [{ before: true, after: false }] },
{ code: "var obj = {'foo':'bar' , 'baz':'qur'};", options: [{ before: true, after: true }] },
+ { code: "var obj = {'foo':'bar' ,'baz':'qur' , };", options: [{ before: true, after: false }] },
{ code: "var a = 1 , b = 2;", options: [{ before: true, after: true }] },
{ code: "var arr = [, ];", options: [{ before: true, after: true }] },
+ { code: "var arr = [,,];", options: [{ before: true, after: true }] },
{ code: "var arr = [1 , ];", options: [{ before: true, after: true }] },
{ code: "var arr = [ , 2];", options: [{ before: true, after: true }] },
{ code: "var arr = [1 , 2];", options: [{ before: true, after: true }] },
@@ -107,6 +138,7 @@ ruleTester.run("comma-spacing", rule, {
{ code: "var arr = [ ,2];", options: [{ before: false, after: false }] },
{ code: "var arr = [1,2];", options: [{ before: false, after: false }] },
{ code: "var arr = [,,];", options: [{ before: false, after: false }] },
+ { code: "var arr = [ , , ];", options: [{ before: false, after: false }] },
{ code: "var arr = [ ,,];", options: [{ before: false, after: false }] },
{ code: "var arr = [1,,];", options: [{ before: false, after: false }] },
{ code: "var arr = [,2,];", options: [{ before: false, after: false }] },
@@ -120,12 +152,22 @@ ruleTester.run("comma-spacing", rule, {
{ code: "var a; console.log(`${a}`, \"a\");", parserOptions: { ecmaVersion: 6 } },
{ code: "var [a, b] = [1, 2];", parserOptions: { ecmaVersion: 6 } },
{ code: "var [a, b, ] = [1, 2];", parserOptions: { ecmaVersion: 6 } },
+ { code: "var [a, b,] = [1, 2];", parserOptions: { ecmaVersion: 6 } },
{ code: "var [a, , b] = [1, 2, 3];", parserOptions: { ecmaVersion: 6 } },
+ { code: "var [a,, b] = [1, 2, 3];", parserOptions: { ecmaVersion: 6 } },
{ code: "var [ , b] = a;", parserOptions: { ecmaVersion: 6 } },
{ code: "var [, b] = a;", parserOptions: { ecmaVersion: 6 } },
+ { code: "var { a,} = a;", parserOptions: { ecmaVersion: 6 } },
+ { code: "import { a,} from 'mod';", parserOptions: { ecmaVersion: 6, sourceType: "module" } },
{ code: ",", parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
{ code: " , ", parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
- { code: "Hello, world", options: [{ before: true, after: false }], parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } }
+ { code: "Hello, world", options: [{ before: true, after: false }], parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
+
+ // For backwards compatibility. Ignoring spacing between a comment and comma of a null element was possibly unintentional.
+ { code: "[a, /**/ , ]", options: [{ before: false, after: true }] },
+ { code: "[a , /**/, ]", options: [{ before: true, after: true }] },
+ { code: "[a, /**/ , ] = foo", options: [{ before: false, after: true }], parserOptions: { ecmaVersion: 6 } },
+ { code: "[a , /**/, ] = foo", options: [{ before: true, after: true }], parserOptions: { ecmaVersion: 6 } }
],
invalid: [
@@ -198,17 +240,6 @@ ruleTester.run("comma-spacing", rule, {
}
]
},
- {
- code: "var arr = [1 , ];",
- output: "var arr = [1 ,];",
- options: [{ before: true, after: false }],
- errors: [
- {
- message: "There should be no space after ','.",
- type: "Punctuator"
- }
- ]
- },
{
code: "var arr = [1 ,2];",
output: "var arr = [1, 2];",
diff --git a/tests/lib/rules/indent.js b/tests/lib/rules/indent.js
index 39476791420..0785083d0ac 100644
--- a/tests/lib/rules/indent.js
+++ b/tests/lib/rules/indent.js
@@ -776,6 +776,21 @@ ruleTester.run("indent", rule, {
`,
options: [2, { VariableDeclarator: 2, SwitchCase: 1 }]
},
+ {
+ code: unIndent`
+ with (a)
+ b();
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ with (a)
+ b();
+ c();
+ `,
+ options: [4]
+ },
{
code: unIndent`
if(true)
@@ -6082,6 +6097,270 @@ ruleTester.run("indent", rule, {
`,
options: [4, { FunctionExpression: { body: 2 }, StaticBlock: { body: 2 } }],
parserOptions: { ecmaVersion: 2022 }
+ },
+
+ // https://github.com/eslint/eslint/issues/15930
+ {
+ code: unIndent`
+ if (2 > 1)
+ \tconsole.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: ["tab"]
+ },
+ {
+ code: unIndent`
+ if (2 > 1)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo) bar();
+ baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo) bar()
+ ;baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar();
+ baz();
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ ; baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ ;baz()
+ qux()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ ;else
+ baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ else
+ baz()
+ ;qux()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ if (bar)
+ baz()
+ ;qux()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ else if (baz)
+ qux()
+ ;quux()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ if (bar)
+ baz()
+ else
+ qux()
+ ;quux()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ ;
+ baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ ;
+ baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ ;baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo);
+ else
+ baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ ;
+ else
+ baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ if (foo)
+ ;else
+ baz()
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ do foo();
+ while (bar)
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ do foo()
+ ;while (bar)
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ do
+ foo();
+ while (bar)
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ do
+ foo()
+ ;while (bar)
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ do;
+ while (foo)
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ do
+ ;
+ while (foo)
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ do
+ ;while (foo)
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ while (2 > 1)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ for (;;)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ for (a in b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ with (a)
+ console.log(b)
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ label: for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4]
+ },
+ {
+ code: unIndent`
+ label:
+ for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4]
}
],
@@ -6699,6 +6978,20 @@ ruleTester.run("indent", rule, {
[2, 4, 0, "Identifier"]
])
},
+ {
+ code: unIndent`
+ with(a)
+ b();
+ `,
+ output: unIndent`
+ with(a)
+ b();
+ `,
+ options: [4],
+ errors: expectedErrors([
+ [2, 4, 0, "Identifier"]
+ ])
+ },
{
code: unIndent`
if(true)
@@ -12623,6 +12916,471 @@ ruleTester.run("indent", rule, {
[6, 12, 0, "Identifier"],
[7, 4, 0, "Punctuator"]
])
+ },
+
+ // https://github.com/eslint/eslint/issues/15930
+ {
+ code: unIndent`
+ if (2 > 1)
+ \tconsole.log('a')
+ \t;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ if (2 > 1)
+ \tconsole.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: ["tab"],
+ errors: expectedErrors("tab", [3, 0, 1, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (2 > 1)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ if (2 > 1)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo) bar();
+ baz()
+ `,
+ output: unIndent`
+ if (foo) bar();
+ baz()
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Identifier"])
+ },
+ {
+ code: unIndent`
+ if (foo) bar()
+ ;baz()
+ `,
+ output: unIndent`
+ if (foo) bar()
+ ;baz()
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar();
+ baz();
+ `,
+ output: unIndent`
+ if (foo)
+ bar();
+ baz();
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Identifier"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ ; baz()
+ `,
+ output: unIndent`
+ if (foo)
+ bar()
+ ; baz()
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ ;baz()
+ qux()
+ `,
+ output: unIndent`
+ if (foo)
+ bar()
+ ;baz()
+ qux()
+ `,
+ options: [4],
+ errors: expectedErrors([
+ [3, 0, 4, "Punctuator"],
+ [4, 0, 4, "Identifier"]
+ ])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ ;else
+ baz()
+ `,
+ output: unIndent`
+ if (foo)
+ bar()
+ ;else
+ baz()
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ else
+ baz()
+ ;qux()
+ `,
+ output: unIndent`
+ if (foo)
+ bar()
+ else
+ baz()
+ ;qux()
+ `,
+ options: [4],
+ errors: expectedErrors([5, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ if (bar)
+ baz()
+ ;qux()
+ `,
+ output: unIndent`
+ if (foo)
+ if (bar)
+ baz()
+ ;qux()
+ `,
+ options: [4],
+ errors: expectedErrors([4, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ else if (baz)
+ qux()
+ ;quux()
+ `,
+ output: unIndent`
+ if (foo)
+ bar()
+ else if (baz)
+ qux()
+ ;quux()
+ `,
+ options: [4],
+ errors: expectedErrors([5, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ if (bar)
+ baz()
+ else
+ qux()
+ ;quux()
+ `,
+ output: unIndent`
+ if (foo)
+ if (bar)
+ baz()
+ else
+ qux()
+ ;quux()
+ `,
+ options: [4],
+ errors: expectedErrors([6, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ bar()
+ ;
+ baz()
+ `,
+ output: unIndent`
+ if (foo)
+ bar()
+ ;
+ baz()
+ `,
+ options: [4],
+ errors: expectedErrors([3, 4, 0, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ ;
+ baz()
+ `,
+ output: unIndent`
+ if (foo)
+ ;
+ baz()
+ `,
+ options: [4],
+ errors: expectedErrors([2, 4, 0, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ ;baz()
+ `,
+ output: unIndent`
+ if (foo)
+ ;baz()
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo);
+ else
+ baz()
+ `,
+ output: unIndent`
+ if (foo);
+ else
+ baz()
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Keyword"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ ;
+ else
+ baz()
+ `,
+ output: unIndent`
+ if (foo)
+ ;
+ else
+ baz()
+ `,
+ options: [4],
+ errors: expectedErrors([2, 4, 0, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ if (foo)
+ ;else
+ baz()
+ `,
+ output: unIndent`
+ if (foo)
+ ;else
+ baz()
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ do foo();
+ while (bar)
+ `,
+ output: unIndent`
+ do foo();
+ while (bar)
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Keyword"])
+ },
+ {
+ code: unIndent`
+ do foo()
+ ;while (bar)
+ `,
+ output: unIndent`
+ do foo()
+ ;while (bar)
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ do
+ foo();
+ while (bar)
+ `,
+ output: unIndent`
+ do
+ foo();
+ while (bar)
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Keyword"])
+ },
+ {
+ code: unIndent`
+ do
+ foo()
+ ;while (bar)
+ `,
+ output: unIndent`
+ do
+ foo()
+ ;while (bar)
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ do;
+ while (foo)
+ `,
+ output: unIndent`
+ do;
+ while (foo)
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Keyword"])
+ },
+ {
+ code: unIndent`
+ do
+ ;
+ while (foo)
+ `,
+ output: unIndent`
+ do
+ ;
+ while (foo)
+ `,
+ options: [4],
+ errors: expectedErrors([2, 4, 0, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ do
+ ;while (foo)
+ `,
+ output: unIndent`
+ do
+ ;while (foo)
+ `,
+ options: [4],
+ errors: expectedErrors([2, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ while (2 > 1)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ while (2 > 1)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ for (;;)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ for (;;)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ for (a in b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ for (a in b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ with (a)
+ console.log(b)
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ with (a)
+ console.log(b)
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ label: for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ label: for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4],
+ errors: expectedErrors([3, 0, 4, "Punctuator"])
+ },
+ {
+ code: unIndent`
+ label:
+ for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ output: unIndent`
+ label:
+ for (a of b)
+ console.log('a')
+ ;[1, 2, 3].forEach(x=>console.log(x))
+ `,
+ options: [4],
+ errors: expectedErrors([4, 0, 4, "Punctuator"])
}
]
});
diff --git a/tests/lib/rules/key-spacing.js b/tests/lib/rules/key-spacing.js
index fde9673a63b..dd0fcbc4dcf 100644
--- a/tests/lib/rules/key-spacing.js
+++ b/tests/lib/rules/key-spacing.js
@@ -896,8 +896,82 @@ ruleTester.run("key-spacing", rule, {
on: "value"
}
}]
- }
- ],
+ },
+
+ // https://github.com/eslint/eslint/issues/15914
+ {
+ code: `
+ var foo = {
+ "a": "bar",
+ "𐌘": "baz"
+ };
+ `,
+ options: [{
+ align: {
+ on: "value"
+ }
+ }]
+ },
+ {
+ code: `
+ var foo = {
+ "a": "bar",
+ "Á": "baz",
+ "o͂": "qux",
+ "m̅": "xyz",
+ "ř": "abc"
+
+ };
+ `,
+ options: [{
+ align: {
+ on: "value"
+ }
+ }]
+ },
+ {
+ code: `
+ var foo = {
+ "🌷": "bar", // 2 code points
+ "🎁": "baz", // 2 code points
+ "🇮🇳": "qux", // 4 code points
+ "🏳️🌈": "xyz", // 6 code points
+ };
+ `,
+ options: [{
+ align: {
+ on: "value"
+ }
+ }]
+ },
+ {
+ code: `
+ const foo = {
+ "a": "bar",
+ [𐌘]: "baz"
+ };
+ `,
+ options: [{
+ align: {
+ on: "value"
+ }
+ }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ const foo = {
+ "abc": "bar",
+ [ 𐌘 ]: "baz"
+ };
+ `,
+ options: [{
+ align: {
+ on: "value"
+ }
+ }],
+ parserOptions: { ecmaVersion: 6 }
+ }],
invalid: [{
code: "var a ={'key' : value };",
output: "var a ={'key':value };",
@@ -2203,5 +2277,103 @@ ruleTester.run("key-spacing", rule, {
{ messageId: "missingValue", data: { computed: "", key: "bar" }, line: 3, column: 12, type: "Literal" },
{ messageId: "missingValue", data: { computed: "", key: "baz" }, line: 3, column: 20, type: "Literal" }
]
- }]
+ },
+ {
+ code: `
+ const foo = {
+ "a": "bar",
+ [ 𐌘 ]: "baz"
+ };
+ `,
+ output: `
+ const foo = {
+ "a": "bar",
+ [ 𐌘 ]: "baz"
+ };
+ `,
+ options: [{
+ align: {
+ on: "value"
+ }
+ }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ { messageId: "missingValue", data: { computed: "", key: "a" }, line: 3, column: 22, type: "Literal" }
+ ]
+ },
+ {
+ code: `
+ const foo = {
+ "a": "bar",
+ [ 𐌘 ]: "baz"
+ };
+ `,
+ output: `
+ const foo = {
+ "a" : "bar",
+ [ 𐌘 ]: "baz"
+ };
+ `,
+ options: [{
+ align: {
+ on: "colon"
+ }
+ }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ { messageId: "missingKey", data: { computed: "", key: "a" }, line: 3, column: 17, type: "Literal" }
+ ]
+ },
+ {
+ code: `
+ const foo = {
+ "a": "bar",
+ "𐌘": "baz"
+ };
+ `,
+ output: `
+ const foo = {
+ "a": "bar",
+ "𐌘": "baz"
+ };
+ `,
+ options: [{
+ align: {
+ on: "value"
+ }
+ }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ { messageId: "extraValue", data: { computed: "", key: "a" }, line: 3, column: 20, type: "Literal" }
+ ]
+ },
+ {
+ code: `
+ var foo = {
+ "🌷": "bar", // 2 code points
+ "🎁": "baz", // 2 code points
+ "🇮🇳": "qux", // 4 code points
+ "🏳️🌈": "xyz", // 6 code points
+ };
+ `,
+ output: `
+ var foo = {
+ "🌷": "bar", // 2 code points
+ "🎁": "baz", // 2 code points
+ "🇮🇳": "qux", // 4 code points
+ "🏳️🌈": "xyz", // 6 code points
+ };
+ `,
+ options: [{
+ align: {
+ on: "value"
+ }
+ }],
+ errors: [
+ { messageId: "extraValue", data: { computed: "", key: "🌷" }, line: 3, column: 21, type: "Literal" },
+ { messageId: "extraValue", data: { computed: "", key: "🎁" }, line: 4, column: 21, type: "Literal" },
+ { messageId: "extraValue", data: { computed: "", key: "🇮🇳" }, line: 5, column: 23, type: "Literal" }
+ ]
+ }
+ ]
});
diff --git a/tests/lib/rules/lines-around-comment.js b/tests/lib/rules/lines-around-comment.js
index 2687f1458aa..379698549e4 100644
--- a/tests/lib/rules/lines-around-comment.js
+++ b/tests/lib/rules/lines-around-comment.js
@@ -364,6 +364,60 @@ ruleTester.run("lines-around-comment", rule, {
parserOptions: { ecmaVersion: 2022 }
},
+ // https://github.com/eslint/eslint/issues/16131
+ {
+ code: `
+ switch (foo) {
+ // this comment is allowed by allowBlockStart: true
+
+ case 1:
+ bar();
+ break;
+
+ // this comment is allowed by allowBlockEnd: true
+ }
+ `,
+ options: [{
+ allowBlockStart: true,
+ beforeLineComment: true,
+ afterLineComment: true,
+ allowBlockEnd: true
+ }]
+ },
+ {
+ code: `
+ switch (foo)
+ {
+ // this comment is allowed by allowBlockStart: true
+
+ case 1:
+ bar();
+ break;
+ }
+ `,
+ options: [{
+ allowBlockStart: true,
+ beforeLineComment: true,
+ afterLineComment: true
+ }]
+ },
+ {
+ code: `
+ switch (
+ function(){}()
+ )
+ {
+ // this comment is allowed by allowBlockStart: true
+ case foo:
+ break;
+ }
+ `,
+ options: [{
+ allowBlockStart: true,
+ beforeLineComment: true
+ }]
+ },
+
// check for block end comments
{
code: "var a,\n// line\n\nb;",
@@ -2106,6 +2160,39 @@ ruleTester.run("lines-around-comment", rule, {
output: "foo;\n\n/* fallthrough */",
options: [],
errors: [{ messageId: "before", type: "Block" }]
+ },
+ {
+ code: `
+ switch (
+ // this comment is not allowed by allowBlockStart: true
+
+ foo
+ )
+ {
+ case 1:
+ bar();
+ break;
+ }
+ `,
+ output: `
+ switch (
+
+ // this comment is not allowed by allowBlockStart: true
+
+ foo
+ )
+ {
+ case 1:
+ bar();
+ break;
+ }
+ `,
+ options: [{
+ allowBlockStart: true,
+ beforeLineComment: true,
+ afterLineComment: true
+ }],
+ errors: [{ messageId: "before", type: "Line" }]
}
]
diff --git a/tests/lib/rules/max-lines-per-function.js b/tests/lib/rules/max-lines-per-function.js
index ba01206f4a3..621d66e312d 100644
--- a/tests/lib/rules/max-lines-per-function.js
+++ b/tests/lib/rules/max-lines-per-function.js
@@ -143,7 +143,7 @@ if ( x === y ) {
options: [{ max: 5, skipComments: true, skipBlankLines: false }]
},
- // IIFEs should be recognised if IIFEs: true
+ // IIFEs should be recognized if IIFEs: true
{
code: `(function(){
let x = 0;
@@ -155,7 +155,7 @@ if ( x === y ) {
options: [{ max: 7, skipComments: true, skipBlankLines: false, IIFEs: true }]
},
- // IIFEs should not be recognised if IIFEs: false
+ // IIFEs should not be recognized if IIFEs: false
{
code: `(function(){
let x = 0;
@@ -167,7 +167,7 @@ if ( x === y ) {
options: [{ max: 2, skipComments: true, skipBlankLines: false, IIFEs: false }]
},
- // Arrow IIFEs should be recognised if IIFEs: true
+ // Arrow IIFEs should be recognized if IIFEs: true
{
code: `(() => {
let x = 0;
@@ -179,7 +179,7 @@ if ( x === y ) {
options: [{ max: 7, skipComments: true, skipBlankLines: false, IIFEs: true }]
},
- // Arrow IIFEs should not be recognised if IIFEs: false
+ // Arrow IIFEs should not be recognized if IIFEs: false
{
code: `(() => {
let x = 0;
@@ -194,7 +194,7 @@ if ( x === y ) {
invalid: [
- // Test simple standalone function is recognised
+ // Test simple standalone function is recognized
{
code: "function name() {\n}",
options: [1],
@@ -203,7 +203,7 @@ if ( x === y ) {
]
},
- // Test anonymous function assigned to variable is recognised
+ // Test anonymous function assigned to variable is recognized
{
code: "var func = function() {\n}",
options: [1],
@@ -212,7 +212,7 @@ if ( x === y ) {
]
},
- // Test arrow functions are recognised
+ // Test arrow functions are recognized
{
code: "const bar = () => {\nconst x = 2 + 1;\nreturn x;\n}",
options: [3],
@@ -221,7 +221,7 @@ if ( x === y ) {
]
},
- // Test inline arrow functions are recognised
+ // Test inline arrow functions are recognized
{
code: "const bar = () =>\n 2",
options: [1],
@@ -369,7 +369,7 @@ if ( x === y ) {
]
},
- // Test regular methods are recognised
+ // Test regular methods are recognized
{
code: `class foo {
method() {
@@ -384,7 +384,7 @@ if ( x === y ) {
]
},
- // Test static methods are recognised
+ // Test static methods are recognized
{
code: `class A {
static
@@ -399,7 +399,7 @@ if ( x === y ) {
]
},
- // Test getters are recognised as properties
+ // Test getters are recognized as properties
{
code: `var obj = {
get
@@ -414,7 +414,7 @@ if ( x === y ) {
]
},
- // Test setters are recognised as properties
+ // Test setters are recognized as properties
{
code: `var obj = {
set
diff --git a/tests/lib/rules/no-constant-binary-expression.js b/tests/lib/rules/no-constant-binary-expression.js
index 5f80e53cdfe..c430c7787fd 100644
--- a/tests/lib/rules/no-constant-binary-expression.js
+++ b/tests/lib/rules/no-constant-binary-expression.js
@@ -21,7 +21,7 @@ const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2021, ecmaFeat
ruleTester.run("no-constant-binary-expression", rule, {
valid: [
- // While this _would_ be a constant condition in React, ESLint has a polciy of not attributing any specific behavior to JSX.
+ // While this _would_ be a constant condition in React, ESLint has a policy of not attributing any specific behavior to JSX.
" && foo",
"<>> && foo",
" ?? foo",
diff --git a/tests/lib/rules/no-constant-condition.js b/tests/lib/rules/no-constant-condition.js
index c22b2947a6f..af7bd355db4 100644
--- a/tests/lib/rules/no-constant-condition.js
+++ b/tests/lib/rules/no-constant-condition.js
@@ -410,7 +410,7 @@ ruleTester.run("no-constant-condition", rule, {
/*
* undefined is always falsy (except in old browsers that let you
- * re-assign, but that's an abscure enough edge case to not worry about)
+ * re-assign, but that's an obscure enough edge case to not worry about)
*/
{ code: "if (undefined) {}", errors: [{ messageId: "unexpected" }] },
diff --git a/tests/lib/rules/no-control-regex.js b/tests/lib/rules/no-control-regex.js
index 059e50dc4e7..14abfbce450 100644
--- a/tests/lib/rules/no-control-regex.js
+++ b/tests/lib/rules/no-control-regex.js
@@ -26,7 +26,14 @@ ruleTester.run("no-control-regex", rule, {
"var regex = RegExp('x1f')",
"new RegExp('[')",
"RegExp('[')",
- "new (function foo(){})('\\x1f')"
+ "new (function foo(){})('\\x1f')",
+ { code: String.raw`/\u{20}/u`, parserOptions: { ecmaVersion: 2015 } },
+ String.raw`/\u{1F}/`,
+ String.raw`/\u{1F}/g`,
+ String.raw`new RegExp("\\u{20}", "u")`,
+ String.raw`new RegExp("\\u{1F}")`,
+ String.raw`new RegExp("\\u{1F}", "g")`,
+ String.raw`new RegExp("\\u{1F}", flags)` // when flags are unknown, this rule assumes there's no `u` flag
],
invalid: [
{ code: String.raw`var regex = /\x1f/`, errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }] },
@@ -46,6 +53,38 @@ ruleTester.run("no-control-regex", rule, {
code: String.raw`var regex = /(?<\u{1d49c}>.)\x1f/`,
parserOptions: { ecmaVersion: 2020 },
errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }]
+ },
+ {
+ code: String.raw`new RegExp("\\u001F", flags)`,
+ errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }]
+ },
+ {
+ code: String.raw`/\u{1111}*\x1F/u`,
+ parserOptions: { ecmaVersion: 2015 },
+ errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }]
+ },
+ {
+ code: String.raw`new RegExp("\\u{1111}*\\x1F", "u")`,
+ parserOptions: { ecmaVersion: 2015 },
+ errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }]
+ },
+ {
+ code: String.raw`/\u{1F}/u`,
+ parserOptions: { ecmaVersion: 2015 },
+ errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }]
+ },
+ {
+ code: String.raw`/\u{1F}/gui`,
+ parserOptions: { ecmaVersion: 2015 },
+ errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }]
+ },
+ {
+ code: String.raw`new RegExp("\\u{1F}", "u")`,
+ errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }]
+ },
+ {
+ code: String.raw`new RegExp("\\u{1F}", "gui")`,
+ errors: [{ messageId: "unexpected", data: { controlChars: "\\x1f" }, type: "Literal" }]
}
]
});
diff --git a/tests/lib/rules/no-extra-parens.js b/tests/lib/rules/no-extra-parens.js
index cb488c891e5..acaacd7a525 100644
--- a/tests/lib/rules/no-extra-parens.js
+++ b/tests/lib/rules/no-extra-parens.js
@@ -1,5 +1,5 @@
/**
- * @fileoverview Disallow parenthesesisng higher precedence subexpressions.
+ * @fileoverview Disallow parenthesising higher precedence subexpressions.
* @author Michael Ficarra
*/
diff --git a/tests/lib/rules/no-misleading-character-class.js b/tests/lib/rules/no-misleading-character-class.js
index a02e5e13e32..0aaf34e5942 100644
--- a/tests/lib/rules/no-misleading-character-class.js
+++ b/tests/lib/rules/no-misleading-character-class.js
@@ -76,223 +76,549 @@ ruleTester.run("no-misleading-character-class", rule, {
// RegExp Literals.
{
code: "var r = /[👍]/",
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = /[👍]/u" }]
+ }]
},
{
code: "var r = /[\\uD83D\\uDC4D]/",
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = /[\\uD83D\\uDC4D]/u" }]
+ }]
+ },
+ {
+ code: "var r = /[👍]/",
+ parserOptions: { ecmaVersion: 3 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: null // ecmaVersion doesn't support the 'u' flag
+ }]
+ },
+ {
+ code: "var r = /[👍]/",
+ parserOptions: { ecmaVersion: 5 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: null // ecmaVersion doesn't support the 'u' flag
+ }]
+ },
+ {
+ code: "var r = /[👍]\\a/",
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: null // pattern would be invalid with the 'u' flag
+ }]
+ },
+ {
+ code: "var r = /(?<=[👍])/",
+ parserOptions: { ecmaVersion: 9 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = /(?<=[👍])/u" }]
+ }]
+ },
+ {
+ code: "var r = /(?<=[👍])/",
+ parserOptions: { ecmaVersion: 2018 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = /(?<=[👍])/u" }]
+ }]
},
{
code: "var r = /[Á]/",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[Á]/u",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u0041\\u0301]/",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u0041\\u0301]/u",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u{41}\\u{301}]/u",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[❇️]/",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[❇️]/u",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u2747\\uFE0F]/",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u2747\\uFE0F]/u",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u{2747}\\u{FE0F}]/u",
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: "var r = /[👶🏻]/",
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = /[👶🏻]/u" }]
+ }]
},
{
code: "var r = /[👶🏻]/u",
- errors: [{ messageId: "emojiModifier" }]
+ errors: [{
+ messageId: "emojiModifier",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\uD83D\\uDC76\\uD83C\\uDFFB]/u",
- errors: [{ messageId: "emojiModifier" }]
+ errors: [{
+ messageId: "emojiModifier",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u{1F476}\\u{1F3FB}]/u",
- errors: [{ messageId: "emojiModifier" }]
+ errors: [{
+ messageId: "emojiModifier",
+ suggestions: null
+ }]
},
{
code: "var r = /[🇯🇵]/",
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = /[🇯🇵]/u" }]
+ }]
+ },
+ {
+ code: "var r = /[🇯🇵]/i",
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = /[🇯🇵]/iu" }]
+ }]
},
{
code: "var r = /[🇯🇵]/u",
- errors: [{ messageId: "regionalIndicatorSymbol" }]
+ errors: [{
+ messageId: "regionalIndicatorSymbol",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\uD83C\\uDDEF\\uD83C\\uDDF5]/u",
- errors: [{ messageId: "regionalIndicatorSymbol" }]
+ errors: [{
+ messageId: "regionalIndicatorSymbol",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u{1F1EF}\\u{1F1F5}]/u",
- errors: [{ messageId: "regionalIndicatorSymbol" }]
+ errors: [{
+ messageId: "regionalIndicatorSymbol",
+ suggestions: null
+ }]
},
{
code: "var r = /[👨👩👦]/",
errors: [
- { messageId: "surrogatePairWithoutUFlag" },
- { messageId: "zwj" }
+ {
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = /[👨👩👦]/u" }]
+ },
+ {
+ messageId: "zwj",
+ suggestions: null
+ }
]
},
{
code: "var r = /[👨👩👦]/u",
- errors: [{ messageId: "zwj" }]
+ errors: [{
+ messageId: "zwj",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\uD83D\\uDC68\\u200D\\uD83D\\uDC69\\u200D\\uD83D\\uDC66]/u",
- errors: [{ messageId: "zwj" }]
+ errors: [{
+ messageId: "zwj",
+ suggestions: null
+ }]
},
{
code: "var r = /[\\u{1F468}\\u{200D}\\u{1F469}\\u{200D}\\u{1F466}]/u",
- errors: [{ messageId: "zwj" }]
+ errors: [{
+ messageId: "zwj",
+ suggestions: null
+ }]
},
// RegExp constructors.
{
code: String.raw`var r = new RegExp("[👍]", "")`,
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("[👍]", "u")` }]
+ }]
+ },
+ {
+ code: "var r = new RegExp('[👍]', ``)",
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = new RegExp('[👍]', `u`)" }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("[👍]", flags)`,
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: null
+ }]
+ },
+ {
+ code: String.raw`const flags = ""; var r = new RegExp("[👍]", flags)`,
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\uD83D\\uDC4D]", "")`,
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("[\\uD83D\\uDC4D]", "u")` }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("[👍]", "")`,
+ parserOptions: { ecmaVersion: 3 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: null // ecmaVersion doesn't support the 'u' flag
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("[👍]", "")`,
+ parserOptions: { ecmaVersion: 5 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: null // ecmaVersion doesn't support the 'u' flag
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("[👍]\\a", "")`,
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: null // pattern would be invalid with the 'u' flag
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("/(?<=[👍])", "")`,
+ parserOptions: { ecmaVersion: 9 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("/(?<=[👍])", "u")` }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("/(?<=[👍])", "")`,
+ parserOptions: { ecmaVersion: 2018 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("/(?<=[👍])", "u")` }]
+ }]
},
{
code: String.raw`var r = new RegExp("[Á]", "")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[Á]", "u")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u0041\\u0301]", "")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u0041\\u0301]", "u")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u{41}\\u{301}]", "u")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[❇️]", "")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[❇️]", "u")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u2747\\uFE0F]", "")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u2747\\uFE0F]", "u")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u{2747}\\u{FE0F}]", "u")`,
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[👶🏻]", "")`,
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("[👶🏻]", "u")` }]
+ }]
},
{
code: String.raw`var r = new RegExp("[👶🏻]", "u")`,
- errors: [{ messageId: "emojiModifier" }]
+ errors: [{
+ messageId: "emojiModifier",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\uD83D\\uDC76\\uD83C\\uDFFB]", "u")`,
- errors: [{ messageId: "emojiModifier" }]
+ errors: [{
+ messageId: "emojiModifier",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u{1F476}\\u{1F3FB}]", "u")`,
- errors: [{ messageId: "emojiModifier" }]
+ errors: [{
+ messageId: "emojiModifier",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[🇯🇵]", "")`,
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("[🇯🇵]", "u")` }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("[🇯🇵]", "i")`,
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("[🇯🇵]", "iu")` }]
+ }]
+ },
+ {
+ code: "var r = new RegExp('[🇯🇵]', `i`)",
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = new RegExp('[🇯🇵]', `iu`)" }]
+ }]
+ },
+ {
+ code: "var r = new RegExp('[🇯🇵]', `${foo}`)",
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: "var r = new RegExp('[🇯🇵]', `${foo}u`)" }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("[🇯🇵]")`,
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("[🇯🇵]", "u")` }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp("[🇯🇵]",)`,
+ parserOptions: { ecmaVersion: 2017 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("[🇯🇵]", "u",)` }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp(("[🇯🇵]"))`,
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp(("[🇯🇵]"), "u")` }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp((("[🇯🇵]")))`,
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp((("[🇯🇵]")), "u")` }]
+ }]
+ },
+ {
+ code: String.raw`var r = new RegExp(("[🇯🇵]"),)`,
+ parserOptions: { ecmaVersion: 2017 },
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp(("[🇯🇵]"), "u",)` }]
+ }]
},
{
code: String.raw`var r = new RegExp("[🇯🇵]", "u")`,
- errors: [{ messageId: "regionalIndicatorSymbol" }]
+ errors: [{
+ messageId: "regionalIndicatorSymbol",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\uD83C\\uDDEF\\uD83C\\uDDF5]", "u")`,
- errors: [{ messageId: "regionalIndicatorSymbol" }]
+ errors: [{
+ messageId: "regionalIndicatorSymbol",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u{1F1EF}\\u{1F1F5}]", "u")`,
- errors: [{ messageId: "regionalIndicatorSymbol" }]
+ errors: [{
+ messageId: "regionalIndicatorSymbol",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[👨👩👦]", "")`,
errors: [
- { messageId: "surrogatePairWithoutUFlag" },
- { messageId: "zwj" }
+ {
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new RegExp("[👨👩👦]", "u")` }]
+ },
+ {
+ messageId: "zwj",
+ suggestions: null
+ }
]
},
{
code: String.raw`var r = new RegExp("[👨👩👦]", "u")`,
- errors: [{ messageId: "zwj" }]
+ errors: [{
+ messageId: "zwj",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\uD83D\\uDC68\\u200D\\uD83D\\uDC69\\u200D\\uD83D\\uDC66]", "u")`,
- errors: [{ messageId: "zwj" }]
+ errors: [{
+ messageId: "zwj",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new RegExp("[\\u{1F468}\\u{200D}\\u{1F469}\\u{200D}\\u{1F466}]", "u")`,
- errors: [{ messageId: "zwj" }]
+ errors: [{
+ messageId: "zwj",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new globalThis.RegExp("[❇️]", "")`,
env: { es2020: true },
- errors: [{ messageId: "combiningClass" }]
+ errors: [{
+ messageId: "combiningClass",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new globalThis.RegExp("[👶🏻]", "u")`,
env: { es2020: true },
- errors: [{ messageId: "emojiModifier" }]
+ errors: [{
+ messageId: "emojiModifier",
+ suggestions: null
+ }]
},
{
code: String.raw`var r = new globalThis.RegExp("[🇯🇵]", "")`,
env: { es2020: true },
- errors: [{ messageId: "surrogatePairWithoutUFlag" }]
+ errors: [{
+ messageId: "surrogatePairWithoutUFlag",
+ suggestions: [{ messageId: "suggestUnicodeFlag", output: String.raw`var r = new globalThis.RegExp("[🇯🇵]", "u")` }]
+ }]
},
{
code: String.raw`var r = new globalThis.RegExp("[\\u{1F468}\\u{200D}\\u{1F469}\\u{200D}\\u{1F466}]", "u")`,
env: { es2020: true },
- errors: [{ messageId: "zwj" }]
+ errors: [{
+ messageId: "zwj",
+ suggestions: null
+ }]
}
]
});
diff --git a/tests/lib/rules/no-multi-assign.js b/tests/lib/rules/no-multi-assign.js
index 7920d9900fb..94db78ff81d 100644
--- a/tests/lib/rules/no-multi-assign.js
+++ b/tests/lib/rules/no-multi-assign.js
@@ -39,7 +39,7 @@ function errorAt(line, column, type) {
const ruleTester = new RuleTester();
-ruleTester.run("no-mutli-assign", rule, {
+ruleTester.run("no-multi-assign", rule, {
valid: [
"var a, b, c,\nd = 0;",
"var a = 1; var b = 2; var c = 3;\nvar d = 0;",
diff --git a/tests/lib/rules/no-octal.js b/tests/lib/rules/no-octal.js
index dd2839e728c..a48bf5a1031 100644
--- a/tests/lib/rules/no-octal.js
+++ b/tests/lib/rules/no-octal.js
@@ -31,77 +31,77 @@ ruleTester.run("no-octal", rule, {
{
code: "var a = 01234;",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "a = 1 + 01234;",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "00",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "08",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "09.1",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "09e1",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "09.1e1",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "018",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "019.1",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "019e1",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
},
{
code: "019.1e1",
errors: [{
- messageId: "noOcatal",
+ messageId: "noOctal",
type: "Literal"
}]
}
diff --git a/tests/lib/rules/no-redeclare.js b/tests/lib/rules/no-redeclare.js
index bbbe5808171..5754d19945f 100644
--- a/tests/lib/rules/no-redeclare.js
+++ b/tests/lib/rules/no-redeclare.js
@@ -105,8 +105,8 @@ ruleTester.run("no-redeclare", rule, {
options: [{ builtinGlobals: true }],
env: { browser: false }
},
- { code: "var glovalThis = foo", options: [{ builtinGlobals: true }], env: { es6: true } },
- { code: "var glovalThis = foo", options: [{ builtinGlobals: true }], env: { es2017: true } },
+ { code: "var globalThis = foo", options: [{ builtinGlobals: true }], env: { es6: true } },
+ { code: "var globalThis = foo", options: [{ builtinGlobals: true }], env: { es2017: true } },
// Comments and built-ins.
{
diff --git a/tests/lib/rules/no-restricted-exports.js b/tests/lib/rules/no-restricted-exports.js
index 6cde658107d..631fd6f02fa 100644
--- a/tests/lib/rules/no-restricted-exports.js
+++ b/tests/lib/rules/no-restricted-exports.js
@@ -401,7 +401,7 @@ ruleTester.run("no-restricted-exports", rule, {
// Note: duplicate identifiers in the same export declaration are a 'duplicate export' syntax error. Example: export var a, a;
- // invalid and valid or multiple ivalid in the same declaration
+ // invalid and valid or multiple invalid in the same declaration
{
code: "export var a, b;",
options: [{ restrictedNamedExports: ["a"] }],
diff --git a/tests/lib/rules/no-restricted-imports.js b/tests/lib/rules/no-restricted-imports.js
index 643c87ede17..5403812de36 100644
--- a/tests/lib/rules/no-restricted-imports.js
+++ b/tests/lib/rules/no-restricted-imports.js
@@ -262,6 +262,26 @@ ruleTester.run("no-restricted-imports", rule, {
importNames: ["DisallowedObject"]
}]
}]
+ },
+ {
+ code: "import { Bar } from '../../my/relative-module';",
+ options: [{
+ patterns: [{
+ group: ["**/my/relative-module"],
+ importNames: ["Foo"]
+ }]
+ }]
+ },
+ {
+
+ // Default import should not be reported unless importNames includes 'default'
+ code: "import Foo from '../../my/relative-module';",
+ options: [{
+ patterns: [{
+ group: ["**/my/relative-module"],
+ importNames: ["Foo"]
+ }]
+ }]
}
],
invalid: [{
@@ -1083,6 +1103,138 @@ ruleTester.run("no-restricted-imports", rule, {
column: 1,
endColumn: 41
}]
+ },
+ {
+ code: "import absoluteWithPatterns from '#foo/bar';",
+ options: [{ patterns: ["\\#foo"] }],
+ errors: [{
+ message: "'#foo/bar' import is restricted from being used by a pattern.",
+ type: "ImportDeclaration",
+ line: 1,
+ column: 1,
+ endColumn: 45
+ }]
+ },
+ {
+ code: "import { Foo } from '../../my/relative-module';",
+ options: [{
+ patterns: [{
+ group: ["**/my/relative-module"],
+ importNames: ["Foo"]
+ }]
+ }],
+ errors: [{
+ type: "ImportDeclaration",
+ line: 1,
+ column: 10,
+ endColumn: 13,
+ message: "'Foo' import from '../../my/relative-module' is restricted from being used by a pattern."
+ }]
+ },
+ {
+ code: "import { Foo, Bar } from '../../my/relative-module';",
+ options: [{
+ patterns: [{
+ group: ["**/my/relative-module"],
+ importNames: ["Foo", "Bar"],
+ message: "Import from @/utils instead."
+ }]
+ }],
+ errors: [{
+ type: "ImportDeclaration",
+ line: 1,
+ column: 10,
+ endColumn: 13,
+ message: "'Foo' import from '../../my/relative-module' is restricted from being used by a pattern. Import from @/utils instead."
+ }, {
+ type: "ImportDeclaration",
+ line: 1,
+ column: 15,
+ endColumn: 18,
+ message: "'Bar' import from '../../my/relative-module' is restricted from being used by a pattern. Import from @/utils instead."
+ }]
+ },
+ {
+
+ /*
+ * Star import should be reported for consistency with `paths` option (see: https://github.com/eslint/eslint/pull/16059#discussion_r908749964)
+ * For example, import * as All allows for calling/referencing the restricted import All.Foo
+ */
+ code: "import * as All from '../../my/relative-module';",
+ options: [{
+ patterns: [{
+ group: ["**/my/relative-module"],
+ importNames: ["Foo"]
+ }]
+ }],
+ errors: [{
+ message: "* import is invalid because 'Foo' from '../../my/relative-module' is restricted from being used by a pattern.",
+ type: "ImportDeclaration",
+ line: 1,
+ column: 8,
+ endColumn: 16
+ }]
+ },
+ {
+
+ /*
+ * Star import should be reported for consistency with `paths` option (see: https://github.com/eslint/eslint/pull/16059#discussion_r908749964)
+ * For example, import * as All allows for calling/referencing the restricted import All.Foo
+ */
+ code: "import * as AllWithCustomMessage from '../../my/relative-module';",
+ options: [{
+ patterns: [{
+ group: ["**/my/relative-module"],
+ importNames: ["Foo"],
+ message: "Import from @/utils instead."
+ }]
+ }],
+ errors: [{
+ message: "* import is invalid because 'Foo' from '../../my/relative-module' is restricted from being used by a pattern. Import from @/utils instead.",
+ type: "ImportDeclaration",
+ line: 1,
+ column: 8,
+ endColumn: 33
+ }]
+ },
+ {
+ code: "import def, * as ns from 'mod';",
+ options: [{
+ patterns: [{
+ group: ["mod"],
+ importNames: ["default"]
+ }]
+ }],
+ errors: [{
+ type: "ImportDeclaration",
+ line: 1,
+ column: 8,
+ endColumn: 11,
+ message: "'default' import from 'mod' is restricted from being used by a pattern."
+ },
+ {
+ type: "ImportDeclaration",
+ line: 1,
+ column: 13,
+ endColumn: 20,
+ message: "* import is invalid because 'default' from 'mod' is restricted from being used by a pattern."
+ }]
+ },
+ {
+ code: "import Foo from 'mod';",
+ options: [{
+ patterns: [{
+ group: ["mod"],
+ importNames: ["default"]
+ }]
+ }],
+ errors: [{
+ type: "ImportDeclaration",
+ line: 1,
+ column: 8,
+ endColumn: 11,
+ message: "'default' import from 'mod' is restricted from being used by a pattern."
+ }]
}
]
});
diff --git a/tests/lib/rules/no-unused-vars.js b/tests/lib/rules/no-unused-vars.js
index e7276f6d417..b723a29abcf 100644
--- a/tests/lib/rules/no-unused-vars.js
+++ b/tests/lib/rules/no-unused-vars.js
@@ -252,6 +252,15 @@ ruleTester.run("no-unused-vars", rule, {
{ code: "(function(obj) { for ( const name in obj ) { return true } })({})", parserOptions: { ecmaVersion: 6 } },
{ code: "(function(obj) { for ( const name in obj ) return true })({})", parserOptions: { ecmaVersion: 6 } },
+ // For-of loops
+ { code: "(function(iter) { let name; for ( name of iter ) return; })({});", parserOptions: { ecmaVersion: 6 } },
+ { code: "(function(iter) { let name; for ( name of iter ) { return; } })({});", parserOptions: { ecmaVersion: 6 } },
+ { code: "(function(iter) { for ( let name of iter ) { return true } })({})", parserOptions: { ecmaVersion: 6 } },
+ { code: "(function(iter) { for ( let name of iter ) return true })({})", parserOptions: { ecmaVersion: 6 } },
+
+ { code: "(function(iter) { for ( const name of iter ) { return true } })({})", parserOptions: { ecmaVersion: 6 } },
+ { code: "(function(iter) { for ( const name of iter ) return true })({})", parserOptions: { ecmaVersion: 6 } },
+
// Sequence Expressions (See https://github.com/eslint/eslint/issues/14325)
{ code: "let x = 0; foo = (0, x++);", parserOptions: { ecmaVersion: 6 } },
{ code: "let x = 0; foo = (0, x += 1);", parserOptions: { ecmaVersion: 6 } },
@@ -704,6 +713,50 @@ ruleTester.run("no-unused-vars", rule, {
}]
},
+ // For-of loops
+ {
+ code: "(function(iter) { var name; for ( name of iter ) { i(); return; } })({});",
+ env: { es6: true },
+ errors: [{
+ line: 1,
+ column: 35,
+ messageId: "unusedVar",
+ data: {
+ varName: "name",
+ action: "assigned a value",
+ additional: ""
+ }
+ }]
+ },
+ {
+ code: "(function(iter) { var name; for ( name of iter ) { } })({});",
+ env: { es6: true },
+ errors: [{
+ line: 1,
+ column: 35,
+ messageId: "unusedVar",
+ data: {
+ varName: "name",
+ action: "assigned a value",
+ additional: ""
+ }
+ }]
+ },
+ {
+ code: "(function(iter) { for ( var name of iter ) { } })({});",
+ env: { es6: true },
+ errors: [{
+ line: 1,
+ column: 29,
+ messageId: "unusedVar",
+ data: {
+ varName: "name",
+ action: "assigned a value",
+ additional: ""
+ }
+ }]
+ },
+
// https://github.com/eslint/eslint/issues/3617
{
code: "\n/* global foobar, foo, bar */\nfoobar;",
diff --git a/tests/lib/rules/no-use-before-define.js b/tests/lib/rules/no-use-before-define.js
index ba80e4075c2..dc858f75287 100644
--- a/tests/lib/rules/no-use-before-define.js
+++ b/tests/lib/rules/no-use-before-define.js
@@ -209,6 +209,38 @@ ruleTester.run("no-use-before-define", rule, {
{
code: "const C = class C { static { C.x; } }",
parserOptions: { ecmaVersion: 2022 }
+ },
+
+ // "allowNamedExports" option
+ {
+ code: "export { a }; const a = 1;",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" }
+ },
+ {
+ code: "export { a as b }; const a = 1;",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" }
+ },
+ {
+ code: "export { a, b }; let a, b;",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" }
+ },
+ {
+ code: "export { a }; var a;",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" }
+ },
+ {
+ code: "export { f }; function f() {}",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" }
+ },
+ {
+ code: "export { C }; class C {}",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" }
}
],
invalid: [
@@ -1091,7 +1123,7 @@ ruleTester.run("no-use-before-define", rule, {
messageId: "usedBeforeDefined",
data: { name: "a" }
}]
- }
+ },
/*
* TODO(mdjermanovic): Add the following test cases once https://github.com/eslint/eslint-scope/issues/59 gets fixed:
@@ -1123,5 +1155,124 @@ ruleTester.run("no-use-before-define", rule, {
* }]
* }
*/
+
+ // "allowNamedExports" option
+ {
+ code: "export { a }; const a = 1;",
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export { a }; const a = 1;",
+ options: [{}],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export { a }; const a = 1;",
+ options: [{ allowNamedExports: false }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export { a }; const a = 1;",
+ options: ["nofunc"],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export { a as b }; const a = 1;",
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export { a, b }; let a, b;",
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [
+ {
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ },
+ {
+ messageId: "usedBeforeDefined",
+ data: { name: "b" }
+ }
+ ]
+ },
+ {
+ code: "export { a }; var a;",
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export { f }; function f() {}",
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "f" }
+ }]
+ },
+ {
+ code: "export { C }; class C {}",
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "C" }
+ }]
+ },
+ {
+ code: "export const foo = a; const a = 1;",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export default a; const a = 1;",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export function foo() { return a; }; const a = 1;",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ },
+ {
+ code: "export class C { foo() { return a; } }; const a = 1;",
+ options: [{ allowNamedExports: true }],
+ parserOptions: { ecmaVersion: 2015, sourceType: "module" },
+ errors: [{
+ messageId: "usedBeforeDefined",
+ data: { name: "a" }
+ }]
+ }
]
});
diff --git a/tests/lib/rules/no-warning-comments.js b/tests/lib/rules/no-warning-comments.js
index c2689defab1..6d4137a5e84 100644
--- a/tests/lib/rules/no-warning-comments.js
+++ b/tests/lib/rules/no-warning-comments.js
@@ -34,10 +34,10 @@ ruleTester.run("no-warning-comments", rule, {
"/* any block comment with TODO, FIXME or XXX */",
"/* any block comment with (TODO, FIXME's or XXX!) */",
{ code: "// comments containing terms as substrings like TodoMVC", options: [{ terms: ["todo"], location: "anywhere" }] },
- { code: "// special regex characters don't cause problems", options: [{ terms: ["[aeiou]"], location: "anywhere" }] },
+ { code: "// special regex characters don't cause a problem", options: [{ terms: ["[aeiou]"], location: "anywhere" }] },
"/*eslint no-warning-comments: [2, { \"terms\": [\"todo\", \"fixme\", \"any other term\"], \"location\": \"anywhere\" }]*/\n\nvar x = 10;\n",
{ code: "/*eslint no-warning-comments: [2, { \"terms\": [\"todo\", \"fixme\", \"any other term\"], \"location\": \"anywhere\" }]*/\n\nvar x = 10;\n", options: [{ location: "anywhere" }] },
- { code: "foo", options: [{ terms: ["foo-bar"] }] }
+ { code: "// foo", options: [{ terms: ["foo-bar"] }] }
],
invalid: [
{
@@ -257,6 +257,136 @@ ruleTester.run("no-warning-comments", rule, {
}
}
]
+ },
+ {
+ code: "// Comment ending with term followed by punctuation TODO!",
+ options: [{ terms: ["todo"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "todo",
+ comment: "Comment ending with term followed by..."
+ }
+ }
+ ]
+ },
+ {
+ code: "// Comment ending with term including punctuation TODO!",
+ options: [{ terms: ["todo!"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "todo!",
+ comment: "Comment ending with term including..."
+ }
+ }
+ ]
+ },
+ {
+ code: "// Comment ending with term including punctuation followed by more TODO!!!",
+ options: [{ terms: ["todo!"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "todo!",
+ comment: "Comment ending with term including..."
+ }
+ }
+ ]
+ },
+ {
+ code: "// !TODO comment starting with term preceded by punctuation",
+ options: [{ terms: ["todo"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "todo",
+ comment: "!TODO comment starting with term..."
+ }
+ }
+ ]
+ },
+ {
+ code: "// !TODO comment starting with term including punctuation",
+ options: [{ terms: ["!todo"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "!todo",
+ comment: "!TODO comment starting with term..."
+ }
+ }
+ ]
+ },
+ {
+ code: "// !!!TODO comment starting with term including punctuation preceded by more",
+ options: [{ terms: ["!todo"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "!todo",
+ comment: "!!!TODO comment starting with term..."
+ }
+ }
+ ]
+ },
+ {
+ code: "// FIX!term ending with punctuation followed word character",
+ options: [{ terms: ["FIX!"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "FIX!",
+ comment: "FIX!term ending with punctuation..."
+ }
+ }
+ ]
+ },
+ {
+ code: "// Term starting with punctuation preceded word character!FIX",
+ options: [{ terms: ["!FIX"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "!FIX",
+ comment: "Term starting with punctuation preceded..."
+ }
+ }
+ ]
+ },
+ {
+ code: "//!XXX comment starting with no spaces (anywhere)",
+ options: [{ terms: ["!xxx"], location: "anywhere" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "!xxx",
+ comment: "!XXX comment starting with no spaces..."
+ }
+ }
+ ]
+ },
+ {
+ code: "//!XXX comment starting with no spaces (start)",
+ options: [{ terms: ["!xxx"], location: "start" }],
+ errors: [
+ {
+ messageId: "unexpectedComment",
+ data: {
+ matchedTerm: "!xxx",
+ comment: "!XXX comment starting with no spaces..."
+ }
+ }
+ ]
}
]
});
diff --git a/tests/lib/rules/padding-line-between-statements.js b/tests/lib/rules/padding-line-between-statements.js
index 51ddf0eb3b5..0d6e93c437a 100644
--- a/tests/lib/rules/padding-line-between-statements.js
+++ b/tests/lib/rules/padding-line-between-statements.js
@@ -2729,7 +2729,7 @@ ruleTester.run("padding-line-between-statements", rule, {
parserOptions: { ecmaVersion: 2022 }
},
{
- code: "class C { static { 'use strict'; let x; } }", // 'use strict'; is "espression", because class static blocks don't have directives
+ code: "class C { static { 'use strict'; let x; } }", // 'use strict'; is "expression", because class static blocks don't have directives
options: [
{ blankLine: "always", prev: "directive", next: "let" }
],
@@ -5188,7 +5188,7 @@ ruleTester.run("padding-line-between-statements", rule, {
errors: [{ messageId: "expectedBlankLine" }]
},
{
- code: "class C { static { 'use strict'; let x; } }", // 'use strict'; is "espression", because class static blocks don't have directives
+ code: "class C { static { 'use strict'; let x; } }", // 'use strict'; is "expression", because class static blocks don't have directives
output: "class C { static { 'use strict';\n\n let x; } }",
options: [
{ blankLine: "always", prev: "expression", next: "let" }
diff --git a/tests/lib/rules/sort-keys.js b/tests/lib/rules/sort-keys.js
index ff6482747ad..5c9523ab68c 100644
--- a/tests/lib/rules/sort-keys.js
+++ b/tests/lib/rules/sort-keys.js
@@ -163,7 +163,202 @@ ruleTester.run("sort-keys", rule, {
{ code: "var obj = {è:4, À:3, 'Z':2, '#':1}", options: ["desc", { natural: true, caseSensitive: false }] },
// desc, natural, insensitive, minKeys should ignore unsorted keys when number of keys is less than minKeys
- { code: "var obj = {a:1, _:2, b:3}", options: ["desc", { natural: true, caseSensitive: false, minKeys: 4 }] }
+ { code: "var obj = {a:1, _:2, b:3}", options: ["desc", { natural: true, caseSensitive: false, minKeys: 4 }] },
+
+ // allowLineSeparatedGroups option
+ {
+ code: `
+ var obj = {
+ e: 1,
+ f: 2,
+ g: 3,
+
+ a: 4,
+ b: 5,
+ c: 6
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }]
+ },
+ {
+ code: `
+ var obj = {
+ b: 1,
+
+ // comment
+ a: 2,
+ c: 3
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }]
+ },
+ {
+ code: `
+ var obj = {
+ b: 1
+
+ ,
+
+ // comment
+ a: 2,
+ c: 3
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }]
+ },
+ {
+ code: `
+ var obj = {
+ c: 1,
+ d: 2,
+
+ b() {
+ },
+ e: 4
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ var obj = {
+ c: 1,
+ d: 2,
+ // comment
+
+ // comment
+ b() {
+ },
+ e: 4
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ var obj = {
+ b,
+
+ [a+b]: 1,
+ a
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ var obj = {
+ c: 1,
+ d: 2,
+
+ a() {
+
+ },
+
+ // abce
+ f: 3,
+
+ /*
+
+ */
+ [a+b]: 1,
+ cc: 1,
+ e: 2
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ var obj = {
+ b: "/*",
+
+ a: "*/",
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }]
+ },
+ {
+ code: `
+ var obj = {
+ b,
+ /*
+ */ //
+
+ a
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ var obj = {
+ b,
+
+ /*
+ */ //
+ a
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ var obj = {
+ b: 1
+
+ ,a: 2
+ };
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ var obj = {
+ b: 1
+ // comment before comma
+
+ ,
+ a: 2
+ };
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 }
+ },
+ {
+ code: `
+ var obj = {
+ b,
+
+ a,
+ ...z,
+ c
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 2018 }
+ },
+ {
+ code: `
+ var obj = {
+ b,
+
+ [foo()]: [
+
+ ],
+ a
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 2018 }
+ }
],
invalid: [
@@ -1761,6 +1956,296 @@ ruleTester.run("sort-keys", rule, {
}
}
]
+ },
+
+ // When allowLineSeparatedGroups option is false
+ {
+ code: `
+ var obj = {
+ b: 1,
+ c: 2,
+ a: 3
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: false }],
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "a",
+ prevName: "c"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ let obj = {
+ b
+
+ ,a
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: false }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "a",
+ prevName: "b"
+ }
+ }
+ ]
+ },
+
+ // When allowLineSeparatedGroups option is true
+ {
+ code: `
+ var obj = {
+ b: 1,
+ c () {
+
+ },
+ a: 3
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "a",
+ prevName: "c"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ var obj = {
+ a: 1,
+ b: 2,
+
+ z () {
+
+ },
+ y: 3
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "y",
+ prevName: "z"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ var obj = {
+ b: 1,
+ c () {
+ },
+ // comment
+ a: 3
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "a",
+ prevName: "c"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ var obj = {
+ b,
+ [a+b]: 1,
+ a // sort-keys: 'a' should be before 'b'
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "a",
+ prevName: "b"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ var obj = {
+ c: 1,
+ d: 2,
+ // comment
+ // comment
+ b() {
+ },
+ e: 4
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "b",
+ prevName: "d"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ var obj = {
+ c: 1,
+ d: 2,
+
+ z() {
+
+ },
+ f: 3,
+ /*
+
+
+ */
+ [a+b]: 1,
+ b: 1,
+ e: 2
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "f",
+ prevName: "z"
+ }
+ },
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "b",
+ prevName: "f"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ var obj = {
+ b: "/*",
+ a: "*/",
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "a",
+ prevName: "b"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ var obj = {
+ b: 1
+ // comment before comma
+ , a: 2
+ };
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 6 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "a",
+ prevName: "b"
+ }
+ }
+ ]
+ },
+ {
+ code: `
+ let obj = {
+ b,
+ [foo()]: [
+ // ↓ this blank is inside a property and therefore should not count
+
+ ],
+ a
+ }
+ `,
+ options: ["asc", { allowLineSeparatedGroups: true }],
+ parserOptions: { ecmaVersion: 2018 },
+ errors: [
+ {
+ messageId: "sortKeys",
+ data: {
+ natural: "",
+ insensitive: "",
+ order: "asc",
+ thisName: "a",
+ prevName: "b"
+ }
+ }
+ ]
}
]
});
diff --git a/tests/lib/rules/space-unary-ops.js b/tests/lib/rules/space-unary-ops.js
index ccee19c663d..9969bbc64e3 100644
--- a/tests/lib/rules/space-unary-ops.js
+++ b/tests/lib/rules/space-unary-ops.js
@@ -1,5 +1,5 @@
/**
- * @fileoverview This rule shoud require or disallow spaces before or after unary operations.
+ * @fileoverview This rule should require or disallow spaces before or after unary operations.
* @author Marcin Kumorek
*/
"use strict";
diff --git a/tests/lib/rules/utils/fix-tracker.js b/tests/lib/rules/utils/fix-tracker.js
index 33fe23eee12..aeed89173bb 100644
--- a/tests/lib/rules/utils/fix-tracker.js
+++ b/tests/lib/rules/utils/fix-tracker.js
@@ -129,7 +129,7 @@ describe("FixTracker", () => {
});
});
- describe("retainSurroungingTokens", () => {
+ describe("retainSurroundingTokens", () => {
it("handles a change to a binary operator", () => {
const sourceCode = createSourceCode("const i = j + k;");
const plusToken = sourceCode.ast.tokens[4];
diff --git a/tests/lib/rules/wrap-iife.js b/tests/lib/rules/wrap-iife.js
index 035e265da40..642e29b26df 100644
--- a/tests/lib/rules/wrap-iife.js
+++ b/tests/lib/rules/wrap-iife.js
@@ -434,7 +434,7 @@ ruleTester.run("wrap-iife", rule, {
},
{
code: "if ((function (){}())) {}",
- output: "if ((function (){})()) {}", // wrap function expression and remove unnecessary grouping parens aroung the call expression
+ output: "if ((function (){})()) {}", // wrap function expression and remove unnecessary grouping parens around the call expression
options: ["inside"],
errors: [wrapExpressionError]
},
@@ -557,7 +557,7 @@ ruleTester.run("wrap-iife", rule, {
},
{
code: "if ((function (){}.call())) {}",
- output: "if ((function (){}).call()) {}", // wrap function expression and remove unnecessary grouping parens aroung the call expression
+ output: "if ((function (){}).call()) {}", // wrap function expression and remove unnecessary grouping parens around the call expression
options: ["inside", { functionPrototypeMethods: true }],
errors: [wrapExpressionError]
},
diff --git a/tests/lib/unsupported-api.js b/tests/lib/unsupported-api.js
index dd88be5e69b..53b466adf06 100644
--- a/tests/lib/unsupported-api.js
+++ b/tests/lib/unsupported-api.js
@@ -23,6 +23,14 @@ describe("unsupported-api", () => {
assert.isFunction(api.FileEnumerator);
});
+ it("should have FlatESLint exposed", () => {
+ assert.isFunction(api.FlatESLint);
+ });
+
+ it("should have FlatRuleTester exposed", () => {
+ assert.isFunction(api.FlatRuleTester);
+ });
+
it("should have builtinRules exposed", () => {
assert.instanceOf(api.builtinRules, LazyLoadingRuleMap);
});
diff --git a/tools/fetch-docs-links.js b/tools/fetch-docs-links.js
new file mode 100644
index 00000000000..3d92633f37f
--- /dev/null
+++ b/tools/fetch-docs-links.js
@@ -0,0 +1,112 @@
+/**
+ * @fileoverview Script to fetch link data.
+ *
+ * To fetch info about all files:
+ *
+ * node tools/fetch-docs-links.js
+ *
+ * To fetch info for just selected files (for use with lint-staged):
+ *
+ * node tools/fetch-docs-links.js docs/src/user-guide/index.md
+ *
+ * @author Nicholas C. Zakas
+ */
+
+"use strict";
+
+//-----------------------------------------------------------------------------
+// Requirements
+//-----------------------------------------------------------------------------
+
+const matter = require("gray-matter");
+const metascraper = require("metascraper")([
+ require("metascraper-image")(),
+ require("metascraper-logo")(),
+ require("metascraper-logo-favicon")(),
+ require("metascraper-title")(),
+ require("metascraper-description")()
+]);
+const got = require("got");
+const path = require("path");
+const fs = require("fs").promises;
+const glob = require("fast-glob");
+
+//-----------------------------------------------------------------------------
+// Data
+//-----------------------------------------------------------------------------
+
+const BASE_DIR = path.resolve(__dirname, "../");
+const SRC_DIR = path.resolve(BASE_DIR, "docs/src");
+const DATA_DIR = path.resolve(SRC_DIR, "_data");
+const DATA_FILE_PATH = path.resolve(DATA_DIR, "further_reading_links.json");
+
+// determine which files to check
+let filenames = process.argv.slice(2);
+
+if (filenames.length === 0) {
+ filenames = glob.sync("docs/src/rules/*.md", { cwd: BASE_DIR });
+}
+
+filenames = filenames.map(filename => path.resolve(BASE_DIR, filename));
+
+//-----------------------------------------------------------------------------
+// Helpers
+//-----------------------------------------------------------------------------
+
+/**
+ * Fetches metadata information for a given URL.
+ * @param {string} url The URL to fetch data for.
+ * @returns {Promise