Unverified Commit 50a36eec authored by Houssein Djirdeh's avatar Houssein Djirdeh Committed by GitHub

ESLint Updates (#25895)

* lots of eslint updates

* adds eslint: dirs flag to next.config.js

* update lint command in docs

* update per review comments

* re-add --no-lint command for build

* Apply suggestions from code review
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 7b77415f
...@@ -86,12 +86,15 @@ npx next start -p 4000 ...@@ -86,12 +86,15 @@ npx next start -p 4000
## Lint ## Lint
`next lint` runs ESLint for all files in the `pages` directory and provides a guided setup to install any required dependencies if ESLint is not already configured in your application. `next lint` runs ESLint for all files in the `pages`, `components`, and `lib` directories. It also
provides a guided setup to install any required dependencies if ESLint is not already configured in
your application.
You can also run ESLint on other directories with the `--dir` flag: If you have other directories that you would like to lint, you can specify them using the `--dir`
flag:
```bash ```bash
next lint --dir components next lint --dir utils
``` ```
## Telemetry ## Telemetry
......
---
description: Next.js reports ESLint errors and warnings during builds by default. Learn how to opt-out of this behavior here.
---
# Ignoring ESLint
When ESLint is detected in your project, Next.js fails your **production build** (`next build`) when errors are present.
If you'd like Next.js to dangerously produce production code even when your application has ESLint errors, you can disable the built-in linting step completely.
> Be sure you have configured ESLint to run in a separate part of your workflow (for example, in CI or a pre-commit hook).
Open `next.config.js` and enable the `ignoreDuringBuilds` option in the `eslint` config:
```js
module.exports = {
eslint: {
// Warning: Dangerously allow production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
}
```
## Related
<div class="card">
<a href="/docs/api-reference/next.config.js/introduction.md">
<b>Introduction to next.config.js:</b>
<small>Learn more about the configuration file used by Next.js.</small>
</a>
</div>
<div class="card">
<a href="/docs/basic-features/eslint.md">
<b>ESLint:</b>
<small>Get started with ESLint in Next.js.</small>
</a>
</div>
...@@ -4,16 +4,24 @@ description: Next.js provides an integrated ESLint experience by default. These ...@@ -4,16 +4,24 @@ description: Next.js provides an integrated ESLint experience by default. These
# ESLint # ESLint
Since version **11.0.0**, Next.js provides an integrated [ESLint](https://eslint.org/) experience out of the box. To get started, run `next lint`: Since version **11.0.0**, Next.js provides an integrated [ESLint](https://eslint.org/) experience out of the box. Add `next lint` as a script to `package.json`:
```json
"scripts": {
"lint": "next lint"
}
```
Then run `npm run lint` or `yarn lint`:
```bash ```bash
next lint yarn lint
``` ```
If you don't already have ESLint configured in your application, you will be guided through the installation of the required packages. If you don't already have ESLint configured in your application, you will be guided through the installation of the required packages.
```bash ```bash
next lint yarn lint
# You'll see instructions like these: # You'll see instructions like these:
# #
...@@ -42,25 +50,46 @@ We recommend using an appropriate [integration](https://eslint.org/docs/user-gui ...@@ -42,25 +50,46 @@ We recommend using an appropriate [integration](https://eslint.org/docs/user-gui
Once ESLint has been set up, it will automatically run during every build (`next build`). Errors will fail the build, while warnings will not. Once ESLint has been set up, it will automatically run during every build (`next build`). Errors will fail the build, while warnings will not.
If you do not want ESLint to run as a build step, it can be disabled using the `--no-lint` flag: If you do not want ESLint to run as a build step, refer to the documentation for [Ignoring ESLint](/docs/api-reference/next.config.js/ignoring-eslint.md):
```bash ## Linting Custom Directories
next build --no-lint
```
**This is not recommended** unless you have configured ESLint to run in a separate part of your workflow (for example, in CI or a pre-commit hook). By default, Next.js will run ESLint for all files in the `pages/`, `components/`, and `lib/` directories. However, you can specify which directories using the `dirs` option in the `eslint` config in `next.config.js` for production builds:
## Linting Custom Directories ```js
module.exports = {
eslint: {
dirs: ['pages', 'utils'], // Only run ESLint on the 'pages' and 'utils' directories during production builds (next build)
},
}
```
By default, Next.js will only run ESLint for all files in the `pages/` directory. However, you can specify other custom directories to run by using the `--dir` flag in `next lint`: Similarly, the `--dir` flag can be used for `next lint`:
```bash ```bash
next lint --dir components --dir lib yarn lint --dir pages --dir utils
``` ```
## ESLint Plugin ## ESLint Plugin
Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next), making it easier to catch common issues and problems in a Next.js application. The full set of rules can be found in the [package repository](https://github.com/vercel/next.js/tree/master/packages/eslint-plugin-next/lib/rules). Next.js provides an ESLint plugin, [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next), making it easier to catch common issues and problems in a Next.js application. The full set of rules is as follows:
| | Rule | Description |
| :-: | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| ✔️ | [next/google-font-display](https://nextjs.org/docs/messages/google-font-display) | Enforce optional or swap font-display behavior with Google Fonts |
| ✔️ | [next/google-font-preconnect](https://nextjs.org/docs/messages/google-font-preconnect) | Enforce preconnect usage with Google Fonts |
| ✔️ | [next/link-passhref](https://nextjs.org/docs/messages/link-passhref) | Enforce passHref prop usage with custom Link components |
| ✔️ | [next/no-css-tags](https://nextjs.org/docs/messages/no-css-tags) | Prevent manual stylesheet tags |
| ✔️ | [next/no-document-import-in-page](https://nextjs.org/docs/messages/no-document-import-in-page) | Disallow importing next/document outside of pages/document.js |
| ✔️ | [next/no-head-import-in-document](https://nextjs.org/docs/messages/no-head-import-in-document) | Disallow importing next/head in pages/document.js |
| ✔️ | [next/no-html-link-for-pages](https://nextjs.org/docs/messages/no-html-link-for-pages) | Prohibit HTML anchor links to pages without a Link component |
| ✔️ | [next/no-img-element](https://nextjs.org/docs/messages/no-img-element) | Prohibit usage of HTML &lt;img&gt; element |
| ✔️ | [next/no-page-custom-font](https://nextjs.org/docs/messages/no-page-custom-font) | Prevent page-only custom fonts |
| ✔️ | [next/no-sync-scripts](https://nextjs.org/docs/messages/no-sync-scripts) | Forbid synchronous scripts |
| ✔️ | [next/no-title-in-document-head](https://nextjs.org/docs/messages/no-title-in-document-head) | Disallow using &lt;title&gt; with Head from next/document |
| ✔️ | [next/no-unwanted-polyfillio](https://nextjs.org/docs/messages/no-unwanted-polyfillio) | Prevent duplicate polyfills from Polyfill.io |
- ✔: Enabled in the recommended configuration
## Base Configuration ## Base Configuration
...@@ -82,14 +111,14 @@ You can see the full details of the shareable configuration in the [`eslint-conf ...@@ -82,14 +111,14 @@ You can see the full details of the shareable configuration in the [`eslint-conf
## Disabling Rules ## Disabling Rules
If you would like to modify any rules provided by the supported plugins (`react`, `react-hooks`, `next`), you can directly modify them using the `rules` property in your `.eslintrc`: If you would like to modify or disable any rules provided by the supported plugins (`react`, `react-hooks`, `next`), you can directly change them using the `rules` property in your `.eslintrc`:
```js ```js
{ {
"extends": "next", "extends": "next",
"rules": { "rules": {
"react/no-unescaped-entities": "off", "react/no-unescaped-entities": "off",
"@next/next/no-page-custom-font": "error", "@next/next/no-page-custom-font": "off",
} }
} }
``` ```
......
...@@ -344,6 +344,10 @@ ...@@ -344,6 +344,10 @@
"title": "Configuring onDemandEntries", "title": "Configuring onDemandEntries",
"path": "/docs/api-reference/next.config.js/configuring-onDemandEntries.md" "path": "/docs/api-reference/next.config.js/configuring-onDemandEntries.md"
}, },
{
"title": "Ignoring ESLint",
"path": "/docs/api-reference/next.config.js/ignoring-eslint.md"
},
{ {
"title": "Ignoring TypeScript Errors", "title": "Ignoring TypeScript Errors",
"path": "/docs/api-reference/next.config.js/ignoring-typescript-errors.md" "path": "/docs/api-reference/next.config.js/ignoring-typescript-errors.md"
......
...@@ -213,12 +213,15 @@ export default async function build( ...@@ -213,12 +213,15 @@ export default async function build(
typeCheckingSpinner.stopAndPersist() typeCheckingSpinner.stopAndPersist()
} }
if (runLint) { const ignoreESLint = Boolean(config.eslint?.ignoreDuringBuilds)
const lintDirs = config.eslint?.dirs
if (!ignoreESLint && runLint) {
await nextBuildSpan await nextBuildSpan
.traceChild('verify-and-lint') .traceChild('verify-and-lint')
.traceAsyncFn(async () => { .traceAsyncFn(async () => {
await verifyAndLint( await verifyAndLint(
dir, dir,
lintDirs,
config.experimental.cpus, config.experimental.cpus,
config.experimental.workerThreads config.experimental.workerThreads
) )
......
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
import { existsSync } from 'fs' import { existsSync } from 'fs'
import arg from 'next/dist/compiled/arg/index.js' import arg from 'next/dist/compiled/arg/index.js'
import { resolve, join } from 'path' import { resolve, join } from 'path'
import chalk from 'chalk'
import { cliCommand } from '../bin/next' import { cliCommand } from '../bin/next'
import { runLintCheck } from '../lib/eslint/runLintCheck' import { runLintCheck } from '../lib/eslint/runLintCheck'
import { printAndExit } from '../server/lib/utils' import { printAndExit } from '../server/lib/utils'
...@@ -55,18 +57,23 @@ const nextLint: cliCommand = (argv) => { ...@@ -55,18 +57,23 @@ const nextLint: cliCommand = (argv) => {
} }
const dirs: string[] = args['--dir'] const dirs: string[] = args['--dir']
const lintDirs = dirs const lintDirs = (dirs ?? ['pages', 'components', 'lib']).reduce(
? dirs.reduce((res: string[], d: string) => { (res: string[], d: string) => {
const currDir = join(baseDir, d) const currDir = join(baseDir, d)
if (!existsSync(currDir)) return res if (!existsSync(currDir)) return res
res.push(currDir) res.push(currDir)
return res return res
}, []) },
: null []
)
runLintCheck(baseDir, lintDirs) runLintCheck(baseDir, lintDirs)
.then((results) => { .then((results) => {
if (results) console.log(results) if (results) {
console.log(results)
} else {
console.log(chalk.green('✔ No ESLint warnings or errors'))
}
}) })
.catch((err) => { .catch((err) => {
printAndExit(err.message) printAndExit(err.message)
......
...@@ -70,12 +70,15 @@ function formatMessage( ...@@ -70,12 +70,15 @@ function formatMessage(
} }
export function formatResults(baseDir: string, results: LintResult[]): string { export function formatResults(baseDir: string, results: LintResult[]): string {
return ( const formattedResults = results
results .filter(({ messages }) => messages?.length)
.filter(({ messages }) => messages?.length) .map(({ messages, filePath }) => formatMessage(baseDir, messages, filePath))
.map(({ messages, filePath }) => .join('\n')
formatMessage(baseDir, messages, filePath)
) return formattedResults.length > 0
.join('\n') + '\n' ? formattedResults +
) `\n\n${chalk.bold(
'Need to disable some ESLint rules? Learn more here:'
)} https://nextjs.org/docs/basic-features/eslint#disabling-rules\n`
: ''
} }
...@@ -8,7 +8,6 @@ import * as CommentJson from 'next/dist/compiled/comment-json' ...@@ -8,7 +8,6 @@ import * as CommentJson from 'next/dist/compiled/comment-json'
import { formatResults } from './customFormatter' import { formatResults } from './customFormatter'
import { writeDefaultConfig } from './writeDefaultConfig' import { writeDefaultConfig } from './writeDefaultConfig'
import { findPagesDir } from '../find-pages-dir' import { findPagesDir } from '../find-pages-dir'
import { CompileError } from '../compile-error' import { CompileError } from '../compile-error'
import { import {
hasNecessaryDependencies, hasNecessaryDependencies,
...@@ -29,7 +28,7 @@ const linteableFiles = (dir: string) => { ...@@ -29,7 +28,7 @@ const linteableFiles = (dir: string) => {
async function lint( async function lint(
deps: NecessaryDependencies, deps: NecessaryDependencies,
baseDir: string, baseDir: string,
lintDirs: string[] | null, lintDirs: string[],
eslintrcFile: string | null, eslintrcFile: string | null,
pkgJsonPath: string | null pkgJsonPath: string | null
): Promise<string | null> { ): Promise<string | null> {
...@@ -103,13 +102,7 @@ async function lint( ...@@ -103,13 +102,7 @@ async function lint(
} }
} }
// If no directories to lint are provided, only the pages directory will be linted const results = await eslint.lintFiles(lintDirs.map(linteableFiles))
const filesToLint = lintDirs
? lintDirs.map(linteableFiles)
: linteableFiles(pagesDir)
const results = await eslint.lintFiles(filesToLint)
if (ESLint.getErrorResults(results)?.length > 0) { if (ESLint.getErrorResults(results)?.length > 0) {
throw new CompileError(await formatResults(baseDir, results)) throw new CompileError(await formatResults(baseDir, results))
} }
...@@ -118,7 +111,7 @@ async function lint( ...@@ -118,7 +111,7 @@ async function lint(
export async function runLintCheck( export async function runLintCheck(
baseDir: string, baseDir: string,
lintDirs: string[] | null, lintDirs: string[],
lintDuringBuild: boolean = false lintDuringBuild: boolean = false
): Promise<string | null> { ): Promise<string | null> {
try { try {
......
...@@ -70,18 +70,15 @@ export async function hasNecessaryDependencies( ...@@ -70,18 +70,15 @@ export async function hasNecessaryDependencies(
const removalLintMsg = const removalLintMsg =
`\n\n` + `\n\n` +
(lintDuringBuild (lintDuringBuild
? `If you do not want to run ESLint during builds, run ${chalk.bold.cyan( ? `If you do not want to run ESLint during builds, ` +
'next build --no-lint'
)}` +
(!!eslintrcFile (!!eslintrcFile
? ` or remove the ${chalk.bold( ? `remove the ${chalk.bold(
basename(eslintrcFile) basename(eslintrcFile)
)} file from your package root.` )} file from your package root`
: pkgJsonEslintConfig : pkgJsonEslintConfig
? ` or remove the ${chalk.bold( ? `remove the ${chalk.bold('eslintConfig')} field from package.json`
'eslintConfig' : '') +
)} field from package.json.` ' or disable it in next.config.js.\n\nSee https://nextjs.org/docs/api-reference/next.config.js/ignoring-eslint.'
: '')
: `Once installed, run ${chalk.bold.cyan('next lint')} again.`) : `Once installed, run ${chalk.bold.cyan('next lint')} again.`)
const removalMsg = checkTSDeps ? removalTSMsg : removalLintMsg const removalMsg = checkTSDeps ? removalTSMsg : removalLintMsg
......
import chalk from 'chalk' import chalk from 'chalk'
import { Worker } from 'jest-worker' import { Worker } from 'jest-worker'
import { existsSync } from 'fs'
import { join } from 'path'
export async function verifyAndLint( export async function verifyAndLint(
dir: string, dir: string,
configLintDirs: string[] | undefined,
numWorkers: number | undefined, numWorkers: number | undefined,
enableWorkerThreads: boolean | undefined enableWorkerThreads: boolean | undefined
): Promise<void> { ): Promise<void> {
...@@ -17,7 +20,17 @@ export async function verifyAndLint( ...@@ -17,7 +20,17 @@ export async function verifyAndLint(
lintWorkers.getStdout().pipe(process.stdout) lintWorkers.getStdout().pipe(process.stdout)
lintWorkers.getStderr().pipe(process.stderr) lintWorkers.getStderr().pipe(process.stderr)
const lintResults = await lintWorkers.runLintCheck(dir, null, true) const lintDirs = (configLintDirs ?? ['pages', 'components', 'lib']).reduce(
(res: string[], d: string) => {
const currDir = join(dir, d)
if (!existsSync(currDir)) return res
res.push(currDir)
return res
},
[]
)
const lintResults = await lintWorkers.runLintCheck(dir, lintDirs, true)
if (lintResults) { if (lintResults) {
console.log(lintResults) console.log(lintResults)
} }
......
{
"extends": "next",
"root": true,
"rules": {
"@next/next/no-html-link-for-pages": 0
}
}
const Custom = () => (
<div>
<script src="https://example.com" />
</div>
)
export default Custom
module.exports = {
eslint: {
dirs: ['utils', 'custom'],
},
}
const Home = () => (
<div>
<p>Home</p>
<a href="test">Test link</a>
</div>
)
export default Home
const Utils = () => <div>/* Badly formatted comment */</div>
export default Utils
{
"extends": "next",
"root": true,
"rules": {
"@next/next/no-html-link-for-pages": 0
}
}
module.exports = {
eslint: {
// !! WARN !!
// Dangerously allow production builds to successfully complete even if
// your project has ESLint errors.
// !! WARN !!
ignoreDuringBuilds: true,
},
}
const Home = () => (
<div>
<p>Home</p>
/* Badly formatted comment */
</div>
)
export default Home
...@@ -2,21 +2,12 @@ import { join } from 'path' ...@@ -2,21 +2,12 @@ import { join } from 'path'
import { nextBuild, nextLint } from 'next-test-utils' import { nextBuild, nextLint } from 'next-test-utils'
import { writeFile, readFile } from 'fs-extra' import { writeFile, readFile } from 'fs-extra'
import semver from 'next/dist/compiled/semver'
jest.setTimeout(1000 * 60 * 2) jest.setTimeout(1000 * 60 * 2)
const dirFirstTimeSetup = join(__dirname, '../first-time-setup') const dirFirstTimeSetup = join(__dirname, '../first-time-setup')
const dirCustomConfig = join(__dirname, '../custom-config') const dirCustomConfig = join(__dirname, '../custom-config')
const dirIgnoreDuringBuilds = join(__dirname, '../ignore-during-builds')
async function eslintVersion() { const dirCustomDirectories = join(__dirname, '../custom-directories')
const eslint = require.resolve('eslint')
const { ESLint, Linter } = await import(eslint)
if (!ESLint && !Linter) return null // A very old version (<v4) if both ESLint and Linter properties are not present
return ESLint ? ESLint.version : Linter.version
}
describe('ESLint', () => { describe('ESLint', () => {
describe('Next Build', () => { describe('Next Build', () => {
...@@ -46,18 +37,38 @@ describe('ESLint', () => { ...@@ -46,18 +37,38 @@ describe('ESLint', () => {
}) })
const output = stdout + stderr const output = stdout + stderr
const version = await eslintVersion() expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
if (!version || (version && semver.lt(version, '7.0.0'))) { )
expect(output).toContain( })
'Your project has an older version of ESLint installed'
) test('ignore during builds', async () => {
expect(output).toContain('Please upgrade to v7 or later') const { stdout, stderr } = await nextBuild(dirIgnoreDuringBuilds, [], {
} else { stdout: true,
expect(output).toContain( stderr: true,
'Error: Comments inside children section of tag should be placed inside braces' })
)
} const output = stdout + stderr
expect(output).not.toContain('Failed to compile')
expect(output).not.toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
})
test('custom directories', async () => {
const { stdout, stderr } = await nextBuild(dirCustomDirectories, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('Failed to compile')
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
expect(output).toContain(
'Warning: External synchronous scripts are forbidden'
)
}) })
}) })
...@@ -88,18 +99,19 @@ describe('ESLint', () => { ...@@ -88,18 +99,19 @@ describe('ESLint', () => {
}) })
const output = stdout + stderr const output = stdout + stderr
const version = await eslintVersion() expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
if (!version || (version && semver.lt(version, '7.0.0'))) { )
expect(output).toContain( })
'Your project has an older version of ESLint installed'
) test('success message when no warnings or errors', async () => {
expect(output).toContain('Please upgrade to v7 or later') const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], {
} else { stdout: true,
expect(output).toContain( stderr: true,
'Error: Comments inside children section of tag should be placed inside braces' })
)
} const output = stdout + stderr
expect(output).toContain('No ESLint warnings or errors')
}) })
}) })
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment