Unverified Commit 41e39426 authored by Ben Gubler's avatar Ben Gubler Committed by GitHub

Remove automatic linting from build (#83136)

### What?
This PR removes the automatic ESLint linting that previously ran during `next build`. The documentation has been updated to reflect this change.

### Why?
As part of Next.js 16, we're removing the automatic build-time linting that was previously included in the build process. This gives developers more control over when linting runs by explicitly invoking their linter via npm scripts.

### How?
- Updated documentation to clarify that automatic build-time linting has been removed in Next.js 16
- Removed the `runLint` parameter and related linting code from the build process
- Removed the `verifyAndLint.ts` file which is no longer needed
- Simplified type checking code by removing lint-related functionality
- Removed ESLint telemetry during builds
parent 5bb25f9b
...@@ -346,7 +346,7 @@ npx @next/codemod@canary next-lint-to-eslint-cli . ...@@ -346,7 +346,7 @@ npx @next/codemod@canary next-lint-to-eslint-cli .
If you use ESLint, create an explicit config (recommended `eslint.config.mjs`). ESLint supports both [the legacy `.eslintrc.*` and the newer `eslint.config.mjs` formats](https://eslint.org/docs/latest/use/configure/configuration-files#configuring-eslint). See the [ESLint API reference](/docs/app/api-reference/config/eslint#with-core-web-vitals) for a recommended setup. If you use ESLint, create an explicit config (recommended `eslint.config.mjs`). ESLint supports both [the legacy `.eslintrc.*` and the newer `eslint.config.mjs` formats](https://eslint.org/docs/latest/use/configure/configuration-files#configuring-eslint). See the [ESLint API reference](/docs/app/api-reference/config/eslint#with-core-web-vitals) for a recommended setup.
> **Good to know**: If an ESLint config is present, `next build` will still run linting in Next.js 15, but this automatic build-time linting will be removed in Next.js 16. Control when linting runs by invoking your linter via npm scripts. > **Good to know**: Prior to Next.js 16, `next build` ran linting automatically. Now, this automatic build-time linting has been removed. Control when linting runs by invoking your linter via npm scripts.
See the [ESLint Plugin](/docs/app/api-reference/config/next-config-js/eslint) page for more information. See the [ESLint Plugin](/docs/app/api-reference/config/next-config-js/eslint) page for more information.
......
...@@ -94,18 +94,13 @@ export default nextConfig ...@@ -94,18 +94,13 @@ export default nextConfig
## Disable static analysis ## Disable static analysis
Typechecking and linting may require a lot of memory, especially in large projects. Typechecking may require a lot of memory, especially in large projects.
However, most projects have a dedicated CI runner that already handles these tasks. However, most projects have a dedicated CI runner that already handles these tasks.
When the build produces out-of-memory issues during the "Linting and checking validity of types" step, you can disable these task during builds: When the build produces out-of-memory issues during the "Running TypeScript" step, you can disable this task during builds:
```js filename="next.config.mjs" ```js filename="next.config.mjs"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
typescript: { typescript: {
// !! WARN !! // !! WARN !!
// Dangerously allow production builds to successfully complete even if // Dangerously allow production builds to successfully complete even if
...@@ -119,9 +114,8 @@ export default nextConfig ...@@ -119,9 +114,8 @@ export default nextConfig
``` ```
- [Ignoring TypeScript Errors](/docs/app/api-reference/config/typescript#disabling-typescript-errors-in-production) - [Ignoring TypeScript Errors](/docs/app/api-reference/config/typescript#disabling-typescript-errors-in-production)
- [ESLint in Next.js config](/docs/pages/api-reference/config/next-config-js/eslint)
Keep in mind that this may produce faulty deploys due to type errors or linting issues. Keep in mind that this may produce faulty deploys due to type errors.
We strongly recommend only promoting builds to production after static analysis has completed. We strongly recommend only promoting builds to production after static analysis has completed.
If you deploy to Vercel, you can check out the [guide for staging deployments](https://vercel.com/docs/deployments/managing-deployments#staging-and-promoting-a-production-deployment) to learn how to promote builds to production after custom tasks have succeeded. If you deploy to Vercel, you can check out the [guide for staging deployments](https://vercel.com/docs/deployments/managing-deployments#staging-and-promoting-a-production-deployment) to learn how to promote builds to production after custom tasks have succeeded.
......
...@@ -230,36 +230,6 @@ module.exports = { ...@@ -230,36 +230,6 @@ module.exports = {
} }
``` ```
## Disabling linting during production builds
If you do not want ESLint to run during `next build`, you can set the `eslint.ignoreDuringBuilds` option in `next.config.js` to `true`:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
const nextConfig = {
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
}
export default nextConfig
```
### Migrating existing config ### Migrating existing config
If you already have ESLint configured in your application, we recommend extending from this plugin directly instead of including `eslint-config-next` unless a few conditions are met. If you already have ESLint configured in your application, we recommend extending from this plugin directly instead of including `eslint-config-next` unless a few conditions are met.
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"next": "latest", "next": "latest",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@popperjs/core": "^2.10.2", "@popperjs/core": "^2.10.2",
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
"prebuild": "npm run typegen", "prebuild": "npm run typegen",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "eslint .",
"presetup": "echo 'about to setup env variables, follow the guide here: https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#using-the-sanity-cli'", "presetup": "echo 'about to setup env variables, follow the guide here: https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#using-the-sanity-cli'",
"setup": "npx sanity@latest init --env .env.local", "setup": "npx sanity@latest init --env .env.local",
"postsetup": "echo 'create the read token by following the rest of the guide: https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#creating-a-read-token'", "postsetup": "echo 'create the read token by following the rest of the guide: https://github.com/vercel/next.js/tree/canary/examples/cms-sanity#creating-a-read-token'",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js && next dev", "dev": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js && next dev",
"build": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js && next build", "build": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js && next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "eslint .",
"codegen": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js" "codegen": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js"
}, },
"dependencies": { "dependencies": {
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"next": "latest", "next": "latest",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev --turbopack", "dev": "next dev --turbopack",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "eslint .",
"postinstall": "prisma generate --no-engine" "postinstall": "prisma generate --no-engine"
}, },
"prisma": { "prisma": {
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@apollo/client": "^3.10.1", "@apollo/client": "^3.10.1",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@headlessui/react": "^1.7.4", "@headlessui/react": "^1.7.4",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@elastic/elasticsearch": "^8.6.0", "@elastic/elasticsearch": "^8.6.0",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"next": "latest", "next": "latest",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"graphql-hooks": "^7.0.0", "graphql-hooks": "^7.0.0",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"next": "latest", "next": "latest",
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
"prebuild": "npm run i18n:compile", "prebuild": "npm run i18n:compile",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "eslint .",
"i18n:extract": "formatjs extract 'pages/**/*.ts*' 'components/**/*.ts*' --out-file lang/en.json", "i18n:extract": "formatjs extract 'pages/**/*.ts*' 'components/**/*.ts*' --out-file lang/en.json",
"i18n:compile": "formatjs compile-folder lang compiled-lang" "i18n:compile": "formatjs compile-folder lang compiled-lang"
}, },
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next", "dev": "next",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@sentry/nextjs": "^7.60.1", "@sentry/nextjs": "^7.60.1",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "eslint .",
"storybook": "storybook dev -p 6006", "storybook": "storybook dev -p 6006",
"build-storybook": "storybook build" "build-storybook": "storybook build"
}, },
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev --turbopack", "dev": "next dev --turbopack",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-checkbox": "^1.3.1", "@radix-ui/react-checkbox": "^1.3.1",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev --turbopack", "dev": "next dev --turbopack",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@libsql/client": "0.4.0", "@libsql/client": "0.4.0",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@gympass/yoga": "^7.61.0", "@gympass/yoga": "^7.61.0",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@types/node": "18.14.6", "@types/node": "18.14.6",
......
...@@ -16,7 +16,6 @@ import { ...@@ -16,7 +16,6 @@ import {
} from '../cli/next-test.js' } from '../cli/next-test.js'
import type { NextTelemetryOptions } from '../cli/next-telemetry.js' import type { NextTelemetryOptions } from '../cli/next-telemetry.js'
import type { NextStartOptions } from '../cli/next-start.js' import type { NextStartOptions } from '../cli/next-start.js'
import type { NextLintOptions } from '../cli/next-lint.js'
import type { NextInfoOptions } from '../cli/next-info.js' import type { NextInfoOptions } from '../cli/next-info.js'
import type { NextDevOptions } from '../cli/next-dev.js' import type { NextDevOptions } from '../cli/next-dev.js'
import type { NextBuildOptions } from '../cli/next-build.js' import type { NextBuildOptions } from '../cli/next-build.js'
...@@ -129,7 +128,6 @@ program ...@@ -129,7 +128,6 @@ program
'--debug-prerender', '--debug-prerender',
'Enables debug mode for prerendering. Not for production use!' 'Enables debug mode for prerendering. Not for production use!'
) )
.option('--no-lint', 'Disables linting.')
.option('--no-mangling', 'Disables mangling.') .option('--no-mangling', 'Disables mangling.')
.option('--profile', 'Enables production profiling for React.') .option('--profile', 'Enables production profiling for React.')
.option('--experimental-app-only', 'Builds only App Router routes.') .option('--experimental-app-only', 'Builds only App Router routes.')
...@@ -239,94 +237,6 @@ program ...@@ -239,94 +237,6 @@ program
import('../cli/next-info.js').then((mod) => mod.nextInfo(options)) import('../cli/next-info.js').then((mod) => mod.nextInfo(options))
) )
program
.command('lint')
.description(
'Runs ESLint for all files in the `/src`, `/app`, `/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.'
)
.argument(
'[directory]',
`A base directory on which to lint the application. ${italic(
'If no directory is provided, the current directory will be used.'
)}`
)
.option(
'-d, --dir, <dirs...>',
'Include directory, or directories, to run ESLint.'
)
.option('--file, <files...>', 'Include file, or files, to run ESLint.')
.addOption(
new Option(
'--ext, [exts...]',
'Specify JavaScript file extensions.'
).default(['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx'])
)
.option(
'-c, --config, <config>',
'Uses this configuration file, overriding all other configuration options.'
)
.option(
'--resolve-plugins-relative-to, <rprt>',
'Specify a directory where plugins should be resolved from.'
)
.option(
'--strict',
'Creates a `.eslintrc.json` file using the Next.js strict configuration.'
)
.option(
'--rulesdir, <rulesdir...>',
'Uses additional rules from this directory(s).'
)
.option('--fix', 'Automatically fix linting issues.')
.option(
'--fix-type <fixType>',
'Specify the types of fixes to apply (e.g., problem, suggestion, layout).'
)
.option('--ignore-path <path>', 'Specify a file to ignore.')
.option('--no-ignore', 'Disables the `--ignore-path` option.')
.option('--quiet', 'Reports errors only.')
.addOption(
new Option(
'--max-warnings [maxWarnings]',
'Specify the number of warnings before triggering a non-zero exit code.'
)
.argParser(parseValidPositiveInteger)
.default(-1)
)
.option(
'-o, --output-file, <outputFile>',
'Specify a file to write report to.'
)
.option('-f, --format, <format>', 'Uses a specific output format.')
.option(
'--no-inline-config',
'Prevents comments from changing config or rules.'
)
.addOption(
new Option(
'--report-unused-disable-directives-severity <level>',
'Specify severity level for unused eslint-disable directives.'
).choices(['error', 'off', 'warn'])
)
.option('--no-cache', 'Disables caching.')
.option('--cache-location, <cacheLocation>', 'Specify a location for cache.')
.addOption(
new Option(
'--cache-strategy, [cacheStrategy]',
'Specify a strategy to use for detecting changed files in the cache.'
).default('metadata')
)
.option(
'--error-on-unmatched-pattern',
'Reports errors when any file patterns are unmatched.'
)
.action((directory: string, options: NextLintOptions) =>
import('../cli/next-lint.js').then((mod) =>
mod.nextLint(options, directory)
)
)
.usage('[directory] [options]')
program program
.command('start') .command('start')
.description( .description(
......
...@@ -901,7 +901,6 @@ export default async function build( ...@@ -901,7 +901,6 @@ export default async function build(
reactProductionProfiling = false, reactProductionProfiling = false,
debugOutput = false, debugOutput = false,
debugPrerender = false, debugPrerender = false,
runLint = true,
noMangling = false, noMangling = false,
appDirOnly = false, appDirOnly = false,
bundler = Bundler.Turbopack, bundler = Bundler.Turbopack,
...@@ -1125,16 +1124,10 @@ export default async function build( ...@@ -1125,16 +1124,10 @@ export default async function build(
logBundler: true, logBundler: true,
}) })
const ignoreESLint = Boolean(config.eslint.ignoreDuringBuilds)
const shouldLint = !ignoreESLint && runLint
const typeCheckingOptions: Parameters<typeof startTypeChecking>[0] = { const typeCheckingOptions: Parameters<typeof startTypeChecking>[0] = {
dir, dir,
appDir, appDir,
pagesDir, pagesDir,
runLint,
shouldLint,
ignoreESLint,
telemetry, telemetry,
nextBuildSpan, nextBuildSpan,
config, config,
...@@ -1149,15 +1142,6 @@ export default async function build( ...@@ -1149,15 +1142,6 @@ export default async function build(
process.exit(1) process.exit(1)
} }
const buildLintEvent: EventBuildFeatureUsage = {
featureName: 'build-lint',
invocationCount: shouldLint ? 1 : 0,
}
telemetry.record({
eventName: EVENT_BUILD_FEATURE_USAGE,
payload: buildLintEvent,
})
const validFileMatcher = createValidFileMatcher( const validFileMatcher = createValidFileMatcher(
config.pageExtensions, config.pageExtensions,
appDir appDir
......
...@@ -2,10 +2,8 @@ import type { NextConfigComplete } from '../server/config-shared' ...@@ -2,10 +2,8 @@ import type { NextConfigComplete } from '../server/config-shared'
import type { Telemetry } from '../telemetry/storage' import type { Telemetry } from '../telemetry/storage'
import type { Span } from '../trace' import type { Span } from '../trace'
import path from 'path'
import * as Log from './output/log' import * as Log from './output/log'
import { Worker } from '../lib/worker' import { Worker } from '../lib/worker'
import { verifyAndLint } from '../lib/verifyAndLint'
import createSpinner from './spinner' import createSpinner from './spinner'
import { eventTypeCheckCompleted } from '../telemetry/events' import { eventTypeCheckCompleted } from '../telemetry/events'
import isError from '../lib/is-error' import isError from '../lib/is-error'
...@@ -72,64 +70,42 @@ export async function startTypeChecking({ ...@@ -72,64 +70,42 @@ export async function startTypeChecking({
cacheDir, cacheDir,
config, config,
dir, dir,
ignoreESLint,
nextBuildSpan, nextBuildSpan,
pagesDir, pagesDir,
runLint,
shouldLint,
telemetry, telemetry,
appDir, appDir,
}: { }: {
cacheDir: string cacheDir: string
config: NextConfigComplete config: NextConfigComplete
dir: string dir: string
ignoreESLint: boolean
nextBuildSpan: Span nextBuildSpan: Span
pagesDir?: string pagesDir?: string
runLint: boolean
shouldLint: boolean
telemetry: Telemetry telemetry: Telemetry
appDir?: string appDir?: string
}) { }) {
const ignoreTypeScriptErrors = Boolean(config.typescript.ignoreBuildErrors) const ignoreTypeScriptErrors = Boolean(config.typescript.ignoreBuildErrors)
const eslintCacheDir = path.join(cacheDir, 'eslint/')
if (ignoreTypeScriptErrors) { if (ignoreTypeScriptErrors) {
Log.info('Skipping validation of types') Log.info('Skipping validation of types')
} }
if (runLint && ignoreESLint) {
// only print log when build require lint while ignoreESLint is enabled
Log.info('Skipping linting')
}
let typeCheckingAndLintingSpinnerPrefixText: string | undefined let typeCheckingSpinnerPrefixText: string | undefined
let typeCheckingAndLintingSpinner: let typeCheckingSpinner: ReturnType<typeof createSpinner> | undefined
| ReturnType<typeof createSpinner>
| undefined
if (!ignoreTypeScriptErrors && shouldLint) { if (!ignoreTypeScriptErrors) {
typeCheckingAndLintingSpinnerPrefixText = typeCheckingSpinnerPrefixText = 'Running TypeScript'
'Running ESLint and TypeScript concurrently'
} else if (!ignoreTypeScriptErrors) {
typeCheckingAndLintingSpinnerPrefixText = 'Running TypeScript'
} else if (shouldLint) {
typeCheckingAndLintingSpinnerPrefixText = 'Running ESLint'
} }
// we will not create a spinner if both ignoreTypeScriptErrors and ignoreESLint are if (typeCheckingSpinnerPrefixText) {
// enabled, but we will still verifying project's tsconfig and dependencies. typeCheckingSpinner = createSpinner(typeCheckingSpinnerPrefixText)
if (typeCheckingAndLintingSpinnerPrefixText) {
typeCheckingAndLintingSpinner = createSpinner(
typeCheckingAndLintingSpinnerPrefixText
)
} }
const typeCheckAndLintStart = process.hrtime() const typeCheckAndLintStart = process.hrtime()
try { try {
const [[verifyResult, typeCheckEnd], lintCheckEnd] = await Promise.all([ const [verifyResult, typeCheckEnd] = await nextBuildSpan
nextBuildSpan.traceChild('run-typescript').traceAsyncFn(() => .traceChild('run-typescript')
.traceAsyncFn(() =>
verifyTypeScriptSetup( verifyTypeScriptSetup(
dir, dir,
config.distDir, config.distDir,
...@@ -145,32 +121,14 @@ export async function startTypeChecking({ ...@@ -145,32 +121,14 @@ export async function startTypeChecking({
const checkEnd = process.hrtime(typeCheckAndLintStart) const checkEnd = process.hrtime(typeCheckAndLintStart)
return [resolved, checkEnd] as const return [resolved, checkEnd] as const
}) })
), )
shouldLint &&
nextBuildSpan.traceChild('run-eslint').traceAsyncFn(async () => {
await verifyAndLint(
dir,
eslintCacheDir,
config.eslint?.dirs,
config.experimental.workerThreads,
telemetry
)
const checkEnd = process.hrtime(typeCheckAndLintStart)
return checkEnd
}),
])
if (typeCheckingAndLintingSpinner) { if (typeCheckingSpinner) {
typeCheckingAndLintingSpinner.stop() typeCheckingSpinner.stop()
createSpinner( createSpinner(
`Finished TypeScript${ignoreTypeScriptErrors ? ' config validation' : ''} in ${hrtimeDurationToString(typeCheckEnd)}` `Finished TypeScript${ignoreTypeScriptErrors ? ' config validation' : ''} in ${hrtimeDurationToString(typeCheckEnd)}`
)?.stopAndPersist() )?.stopAndPersist()
if (lintCheckEnd) {
createSpinner(
`Finished ESLint in ${hrtimeDurationToString(lintCheckEnd)}`
)?.stopAndPersist()
}
} }
if (!ignoreTypeScriptErrors && verifyResult) { if (!ignoreTypeScriptErrors && verifyResult) {
......
...@@ -16,7 +16,6 @@ export type NextBuildOptions = { ...@@ -16,7 +16,6 @@ export type NextBuildOptions = {
debug?: boolean debug?: boolean
debugPrerender?: boolean debugPrerender?: boolean
profile?: boolean profile?: boolean
lint: boolean
mangling: boolean mangling: boolean
turbo?: boolean turbo?: boolean
turbopack?: boolean turbopack?: boolean
...@@ -37,7 +36,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => { ...@@ -37,7 +36,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => {
debugPrerender, debugPrerender,
experimentalDebugMemoryUsage, experimentalDebugMemoryUsage,
profile, profile,
lint,
mangling, mangling,
experimentalAppOnly, experimentalAppOnly,
experimentalBuildMode, experimentalBuildMode,
...@@ -49,10 +47,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => { ...@@ -49,10 +47,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => {
traceUploadUrl = experimentalUploadTrace traceUploadUrl = experimentalUploadTrace
} }
if (!lint) {
warn('Linting is disabled.')
}
if (!mangling) { if (!mangling) {
warn( warn(
`Mangling is disabled. ${italic('Note: This may affect performance and should only be used for debugging purposes.')}` `Mangling is disabled. ${italic('Note: This may affect performance and should only be used for debugging purposes.')}`
...@@ -91,7 +85,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => { ...@@ -91,7 +85,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => {
profile, profile,
debug || Boolean(process.env.NEXT_DEBUG_BUILD), debug || Boolean(process.env.NEXT_DEBUG_BUILD),
debugPrerender, debugPrerender,
lint,
!mangling, !mangling,
experimentalAppOnly, experimentalAppOnly,
bundler, bundler,
......
#!/usr/bin/env node
import { existsSync } from 'fs'
import { isAbsolute, join } from 'path'
import loadConfig from '../server/config'
import { printAndExit } from '../server/lib/utils'
import { Telemetry } from '../telemetry/storage'
import { green, yellow, bold } from '../lib/picocolors'
import { ESLINT_DEFAULT_DIRS } from '../lib/constants'
import { runLintCheck } from '../lib/eslint/runLintCheck'
import { CompileError } from '../lib/compile-error'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { eventLintCheckCompleted } from '../telemetry/events'
import { getProjectDir } from '../lib/get-project-dir'
import { findPagesDir } from '../lib/find-pages-dir'
import { verifyTypeScriptSetup } from '../lib/verify-typescript-setup'
export type NextLintOptions = {
cache: boolean
cacheLocation?: string
cacheStrategy: string
config?: string
dir?: string[]
errorOnUnmatchedPattern?: boolean
file?: string[]
fix?: boolean
fixType?: string
format?: string
ignore: boolean
outputFile?: string
quiet?: boolean
strict?: boolean
// TODO(jiwon): ESLint v9 unsupported options
// we currently delete them at `runLintCheck` when used in v9
ext: string[]
ignorePath?: string
reportUnusedDisableDirectivesSeverity: 'error' | 'off' | 'warn'
resolvePluginsRelativeTo?: string
rulesdir?: string
inlineConfig: boolean
maxWarnings: number
}
const eslintOptions = (
options: NextLintOptions,
defaultCacheLocation: string
) => ({
overrideConfigFile: options.config || null,
extensions: options.ext ?? [],
resolvePluginsRelativeTo: options.resolvePluginsRelativeTo || null,
rulePaths: options.rulesdir ?? [],
fix: options.fix ?? false,
fixTypes: options.fixType ?? null,
ignorePath: options.ignorePath || null,
ignore: options.ignore,
allowInlineConfig: options.inlineConfig,
reportUnusedDisableDirectives:
options.reportUnusedDisableDirectivesSeverity || null,
cache: options.cache,
cacheLocation: options.cacheLocation || defaultCacheLocation,
cacheStrategy: options.cacheStrategy,
errorOnUnmatchedPattern: options.errorOnUnmatchedPattern ?? false,
})
const nextLint = async (options: NextLintOptions, directory?: string) => {
// Show deprecation warning
console.warn(
yellow('`next lint` is deprecated and will be removed in Next.js 16.\n') +
'For new projects, use ' +
bold('create-next-app') +
' to choose your preferred linter.\n' +
'For existing projects, migrate to the ESLint CLI:\n' +
bold('npx @next/codemod@canary next-lint-to-eslint-cli .') +
'\n'
)
const baseDir = getProjectDir(directory)
// Check if the provided directory exists
if (!existsSync(baseDir)) {
printAndExit(`> No such directory exists as the project root: ${baseDir}`)
}
const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir)
const files = options.file ?? []
const dirs = options.dir ?? nextConfig.eslint?.dirs
const filesToLint = [...(dirs ?? []), ...files]
const pathsToLint = (
filesToLint.length ? filesToLint : ESLINT_DEFAULT_DIRS
).reduce((res: string[], d: string) => {
const currDir = isAbsolute(d) ? d : join(baseDir, d)
if (!existsSync(currDir)) {
return res
}
res.push(currDir)
return res
}, [])
const reportErrorsOnly = Boolean(options.quiet)
const maxWarnings = options.maxWarnings
const formatter = options.format || null
const strict = Boolean(options.strict)
const outputFile = options.outputFile || null
const distDir = join(baseDir, nextConfig.distDir)
const defaultCacheLocation = join(distDir, 'cache', 'eslint/')
const { pagesDir, appDir } = findPagesDir(baseDir)
await verifyTypeScriptSetup({
dir: baseDir,
distDir: nextConfig.distDir,
intentDirs: [pagesDir, appDir].filter(Boolean) as string[],
typeCheckPreflight: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
})
runLintCheck(baseDir, pathsToLint, {
lintDuringBuild: false,
eslintOptions: eslintOptions(options, defaultCacheLocation),
reportErrorsOnly,
maxWarnings,
formatter,
outputFile,
strict,
})
.then(async (lintResults) => {
const lintOutput =
typeof lintResults === 'string' ? lintResults : lintResults?.output
if (typeof lintResults !== 'string' && lintResults?.eventInfo) {
const telemetry = new Telemetry({
distDir,
})
telemetry.record(
eventLintCheckCompleted({
...lintResults.eventInfo,
buildLint: false,
})
)
await telemetry.flush()
}
if (
typeof lintResults !== 'string' &&
lintResults?.isError &&
lintOutput
) {
throw new CompileError(lintOutput)
}
if (lintOutput) {
printAndExit(lintOutput, 0)
} else if (lintResults && !lintOutput) {
printAndExit(green('✔ No ESLint warnings or errors'), 0)
} else {
// this makes sure we exit 1 after the error from line 116
// in packages/next/src/lib/eslint/runLintCheck
process.exit(1)
}
})
.catch((err) => {
printAndExit(err.message)
})
}
export { nextLint }
import { bold, cyan, gray, red, yellow } from '../picocolors'
import path from 'path'
// eslint-disable-next-line no-shadow
export enum MessageSeverity {
Warning = 1,
Error = 2,
}
interface LintMessage {
ruleId: string | null
severity: 1 | 2
message: string
line: number
column: number
}
export interface LintResult {
filePath: string
messages: LintMessage[]
errorCount: number
warningCount: number
output?: string
source?: string
}
function pluginCount(messages: LintMessage[]): {
nextPluginErrorCount: number
nextPluginWarningCount: number
} {
let nextPluginWarningCount = 0
let nextPluginErrorCount = 0
for (let i = 0; i < messages.length; i++) {
const { severity, ruleId } = messages[i]
if (ruleId?.includes('@next/next')) {
if (severity === MessageSeverity.Warning) {
nextPluginWarningCount += 1
} else {
nextPluginErrorCount += 1
}
}
}
return {
nextPluginErrorCount,
nextPluginWarningCount,
}
}
function formatMessage(
dir: string,
messages: LintMessage[],
filePath: string
): string {
let fileName = path.posix.normalize(
path.relative(dir, filePath).replace(/\\/g, '/')
)
if (!fileName.startsWith('.')) {
fileName = './' + fileName
}
let output = '\n' + cyan(fileName)
for (let i = 0; i < messages.length; i++) {
const { message, severity, line, column, ruleId } = messages[i]
output = output + '\n'
if (line && column) {
output =
output +
yellow(line.toString()) +
':' +
yellow(column.toString()) +
' '
}
if (severity === MessageSeverity.Warning) {
output += yellow(bold('Warning')) + ': '
} else {
output += red(bold('Error')) + ': '
}
output += message
if (ruleId) {
output += ' ' + gray(bold(ruleId))
}
}
return output
}
export async function formatResults(
baseDir: string,
results: LintResult[],
format: (r: LintResult[]) => string | Promise<string>
): Promise<{
output: string
outputWithMessages: string
totalNextPluginErrorCount: number
totalNextPluginWarningCount: number
}> {
let totalNextPluginErrorCount = 0
let totalNextPluginWarningCount = 0
let resultsWithMessages = results.filter(({ messages }) => messages?.length)
// Track number of Next.js plugin errors and warnings
resultsWithMessages.forEach(({ messages }) => {
const res = pluginCount(messages)
totalNextPluginErrorCount += res.nextPluginErrorCount
totalNextPluginWarningCount += res.nextPluginWarningCount
})
// Use user defined formatter or Next.js's built-in custom formatter
const output = format
? await format(resultsWithMessages)
: resultsWithMessages
.map(({ messages, filePath }) =>
formatMessage(baseDir, messages, filePath)
)
.join('\n')
return {
output: output,
outputWithMessages:
resultsWithMessages.length > 0
? output +
`\n\n${cyan(
'info'
)} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/app/api-reference/config/eslint#disabling-rules`
: '',
totalNextPluginErrorCount,
totalNextPluginWarningCount,
}
}
import findUp from 'next/dist/compiled/find-up'
export const getESLintStrictValue = async (cwd: string) => {
const tsConfigLocation = await findUp('tsconfig.json', { cwd })
const hasTSConfig = tsConfigLocation !== undefined
return {
title: 'Strict',
recommended: true,
config: {
extends: hasTSConfig
? ['next/core-web-vitals', 'next/typescript']
: 'next/core-web-vitals',
},
}
}
export const getESLintPromptValues = async (cwd: string) => {
return [
await getESLintStrictValue(cwd),
{
title: 'Base',
config: {
extends: 'next',
},
},
{
title: 'Cancel',
config: null,
},
]
}
import { promises as fs } from 'fs'
export type ConfigAvailable = {
exists: boolean
emptyEslintrc?: boolean
emptyPkgJsonConfig?: boolean
firstTimeSetup?: true
}
export async function hasEslintConfiguration(
eslintrcFile: string | null,
packageJsonConfig: { eslintConfig: any } | null
): Promise<ConfigAvailable> {
const configObject = {
exists: false,
emptyEslintrc: false,
emptyPkgJsonConfig: false,
}
if (eslintrcFile) {
const content = await fs.readFile(eslintrcFile, { encoding: 'utf8' }).then(
(txt) => txt.trim().replace(/\n/g, ''),
() => null
)
if (
content === '' ||
content === '{}' ||
content === '---' ||
content === 'module.exports = {}'
) {
configObject.emptyEslintrc = true
} else {
configObject.exists = true
}
} else if (packageJsonConfig?.eslintConfig) {
if (Object.keys(packageJsonConfig.eslintConfig).length) {
configObject.exists = true
} else {
configObject.emptyPkgJsonConfig = true
}
}
return configObject
}
This diff is collapsed.
import { promises as fs } from 'fs'
import { bold, green } from '../picocolors'
import os from 'os'
import path from 'path'
import * as CommentJson from 'next/dist/compiled/comment-json'
import type { ConfigAvailable } from './hasEslintConfiguration'
import * as Log from '../../build/output/log'
export async function writeDefaultConfig(
baseDir: string,
{ exists, emptyEslintrc, emptyPkgJsonConfig }: ConfigAvailable,
selectedConfig: any,
eslintrcFile: string | null,
pkgJsonPath: string | null,
packageJsonConfig: { eslintConfig: any } | null
) {
if (!exists && emptyEslintrc && eslintrcFile) {
const ext = path.extname(eslintrcFile)
let newFileContent
if (ext === '.yaml' || ext === '.yml') {
newFileContent = "extends: 'next'"
} else {
newFileContent = CommentJson.stringify(selectedConfig, null, 2)
if (ext === '.js') {
newFileContent = 'module.exports = ' + newFileContent
}
}
await fs.writeFile(eslintrcFile, newFileContent + os.EOL)
Log.info(
`We detected an empty ESLint configuration file (${bold(
path.basename(eslintrcFile)
)}) and updated it for you!`
)
} else if (!exists && emptyPkgJsonConfig && packageJsonConfig) {
packageJsonConfig.eslintConfig = selectedConfig
if (pkgJsonPath)
await fs.writeFile(
pkgJsonPath,
CommentJson.stringify(packageJsonConfig, null, 2) + os.EOL
)
Log.info(
`We detected an empty ${bold(
'eslintConfig'
)} field in package.json and updated it for you!`
)
} else if (!exists) {
await fs.writeFile(
path.join(baseDir, '.eslintrc.json'),
CommentJson.stringify(selectedConfig, null, 2) + os.EOL
)
console.log(
green(
`We created the ${bold(
'.eslintrc.json'
)} file for you and included your selected configuration.`
)
)
}
}
import { promises as fs } from 'fs'
import path from 'path'
import * as Log from '../../build/output/log'
import isError from '../../lib/is-error'
/**
* Check if a given file path is a directory or not.
* Returns `true` if the path is a directory.
*/
function isDirectory(
/** The path to a file to check. */
filePath: string
): Promise<boolean> {
return fs
.stat(filePath)
.then((stat) => stat.isDirectory())
.catch((error) => {
if (
isError(error) &&
(error.code === 'ENOENT' || error.code === 'ENOTDIR')
) {
return false
}
throw error
})
}
/**
* Create a file with eslint output data
*/
export async function writeOutputFile(
/** The name file that needs to be created */
outputFile: string,
/** The data that needs to be inserted into the file */
outputData: string
): Promise<void> {
const filePath = path.resolve(process.cwd(), outputFile)
if (await isDirectory(filePath)) {
Log.error(
`Cannot write to output file path, it is a directory: ${filePath}`
)
} else {
try {
await fs.mkdir(path.dirname(filePath), { recursive: true })
await fs.writeFile(filePath, outputData)
Log.info(`The output file has been created: ${filePath}`)
} catch (err) {
Log.error(`There was a problem writing the output file: ${filePath}`)
console.error(err)
}
}
}
import { red } from './picocolors'
import { Worker } from './worker'
import { existsSync } from 'fs'
import { join } from 'path'
import { ESLINT_DEFAULT_DIRS } from './constants'
import type { Telemetry } from '../telemetry/storage'
import { eventLintCheckCompleted } from '../telemetry/events'
import { CompileError } from './compile-error'
import isError from './is-error'
export async function verifyAndLint(
dir: string,
cacheLocation: string,
configLintDirs: string[] | undefined,
enableWorkerThreads: boolean | undefined,
telemetry: Telemetry
): Promise<void> {
let lintWorkers:
| (Worker & {
runLintCheck: typeof import('./eslint/runLintCheck').runLintCheck
})
| undefined
try {
lintWorkers = new Worker(require.resolve('./eslint/runLintCheck'), {
exposedMethods: ['runLintCheck'],
debuggerPortOffset: -1,
isolatedMemory: false,
numWorkers: 1,
enableWorkerThreads,
maxRetries: 0,
}) as Worker & {
runLintCheck: typeof import('./eslint/runLintCheck').runLintCheck
}
const lintDirs = (configLintDirs ?? ESLINT_DEFAULT_DIRS).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, {
lintDuringBuild: true,
eslintOptions: {
cacheLocation,
},
})
const lintOutput =
typeof lintResults === 'string' ? lintResults : lintResults?.output
if (typeof lintResults !== 'string' && lintResults?.eventInfo) {
telemetry.record(
eventLintCheckCompleted({
...lintResults.eventInfo,
buildLint: true,
})
)
}
if (typeof lintResults !== 'string' && lintResults?.isError && lintOutput) {
await telemetry.flush()
throw new CompileError(lintOutput)
}
if (lintOutput) {
console.log(lintOutput)
}
} catch (err) {
if (isError(err)) {
if (err.type === 'CompileError' || err instanceof CompileError) {
console.error(red('\nFailed to compile.'))
console.error(err.message)
process.exit(1)
} else if (err.type === 'FatalError') {
console.error(err.message)
process.exit(1)
}
}
throw err
} finally {
try {
lintWorkers?.end()
} catch {}
}
}
...@@ -466,12 +466,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -466,12 +466,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
distDir: z.string().min(1).optional(), distDir: z.string().min(1).optional(),
env: z.record(z.string(), z.union([z.string(), z.undefined()])).optional(), env: z.record(z.string(), z.union([z.string(), z.undefined()])).optional(),
eslint: z
.strictObject({
dirs: z.array(z.string().min(1)).optional(),
ignoreDuringBuilds: z.boolean().optional(),
})
.optional(),
excludeDefaultMomentLocales: z.boolean().optional(), excludeDefaultMomentLocales: z.boolean().optional(),
experimental: z.strictObject(experimentalSchema).optional(), experimental: z.strictObject(experimentalSchema).optional(),
exportPathMap: z exportPathMap: z
......
...@@ -43,13 +43,6 @@ export interface DomainLocale { ...@@ -43,13 +43,6 @@ export interface DomainLocale {
locales?: readonly string[] locales?: readonly string[]
} }
export interface ESLintConfig {
/** Only run ESLint on these directories with `next lint` and `next build`. */
dirs?: string[]
/** Do not run ESLint during production builds (`next build`). */
ignoreDuringBuilds?: boolean
}
export interface TypeScriptConfig { export interface TypeScriptConfig {
/** Do not run TypeScript during production builds (`next build`). */ /** Do not run TypeScript during production builds (`next build`). */
ignoreBuildErrors?: boolean ignoreBuildErrors?: boolean
...@@ -916,12 +909,6 @@ export interface NextConfig { ...@@ -916,12 +909,6 @@ export interface NextConfig {
*/ */
i18n?: I18NConfig | null i18n?: I18NConfig | null
/**
* @since version 11
* @see [ESLint configuration](https://nextjs.org/docs/app/api-reference/config/eslint)
*/
eslint?: ESLintConfig
/** /**
* @see [Next.js TypeScript documentation](https://nextjs.org/docs/app/api-reference/config/typescript) * @see [Next.js TypeScript documentation](https://nextjs.org/docs/app/api-reference/config/typescript)
*/ */
...@@ -1340,9 +1327,6 @@ export interface NextConfig { ...@@ -1340,9 +1327,6 @@ export interface NextConfig {
export const defaultConfig = Object.freeze({ export const defaultConfig = Object.freeze({
env: {}, env: {},
webpack: null, webpack: null,
eslint: {
ignoreDuringBuilds: false,
},
typescript: { typescript: {
ignoreBuildErrors: false, ignoreBuildErrors: false,
tsconfigPath: undefined, tsconfigPath: undefined,
......
...@@ -186,7 +186,6 @@ export type EventBuildFeatureUsage = { ...@@ -186,7 +186,6 @@ export type EventBuildFeatureUsage = {
| 'swcEmotion' | 'swcEmotion'
| `swc/target/${SWC_TARGET_TRIPLE}` | `swc/target/${SWC_TARGET_TRIPLE}`
| 'turbotrace' | 'turbotrace'
| 'build-lint'
| 'vercelImageGeneration' | 'vercelImageGeneration'
| 'transpilePackages' | 'transpilePackages'
| 'skipMiddlewareUrlNormalize' | 'skipMiddlewareUrlNormalize'
......
import { nextTestSetup } from 'e2e-utils'
import { readFileSync } from 'fs'
import { nextLint } from 'next-test-utils'
describe('next-lint-eslint-formatter-compact', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: { eslint: '^8', 'eslint-config-next': 'canary' },
})
it('should format flag "compact" creates a file respecting the chosen format', async () => {
const filePath = `${next.testDir}/output/output.txt`
const { stdout, stderr } = await nextLint(
next.testDir,
['--format', 'compact', '--output-file', filePath],
{
stdout: true,
stderr: true,
}
)
const cliOutput = stdout + stderr
const fileOutput = readFileSync(filePath, 'utf8')
expect(cliOutput).toContain(`The output file has been created: ${filePath}`)
expect(fileOutput).toContain(`${next.testDir}/pages/bar.js`)
expect(fileOutput).toContain(
'img elements must have an alt prop, either with meaningful text, or an empty string for decorative images.'
)
expect(fileOutput).toContain(
'Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` or a custom image loader to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element'
)
expect(fileOutput).toContain(`${next.testDir}/pages/index.js`)
expect(fileOutput).toContain(
'Synchronous scripts should not be used. See: https://nextjs.org/docs/messages/no-sync-scripts'
)
})
it('should show error message when the file path is a directory', async () => {
const filePath = next.testDir
const { stdout, stderr } = await nextLint(
next.testDir,
['--format', 'compact', '--output-file', filePath],
{
stdout: true,
stderr: true,
}
)
const cliOutput = stdout + stderr
console.log({ cliOutput })
expect(cliOutput).toContain(
`Cannot write to output file path, it is a directory: ${filePath}`
)
})
})
export default class Bar {
render() {
return (
<div>
<h1>Hello title</h1>
<img src="img" />
</div>
)
}
}
export default class Home {
render() {
return (
<div>
<h1>Hello title</h1>
<script src="test"></script>
</div>
)
}
}
export default class Test {
render() {
return (
<div>
<h1>Hello title</h1>
/* Badly formatted comment */
</div>
)
}
}
...@@ -2,12 +2,6 @@ ...@@ -2,12 +2,6 @@
"name": "next-app", "name": "next-app",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": { "dependencies": {
"internal-pkg": "link:./internal-pkg" "internal-pkg": "link:./internal-pkg"
}, },
......
...@@ -140,7 +140,6 @@ describe('trace-build-file', () => { ...@@ -140,7 +140,6 @@ describe('trace-build-file', () => {
expect([...foundEvents].sort()).toMatchInlineSnapshot(` expect([...foundEvents].sort()).toMatchInlineSnapshot(`
[ [
"next-build", "next-build",
"run-eslint",
"run-turbopack", "run-turbopack",
"run-typescript", "run-typescript",
"static-check", "static-check",
...@@ -153,7 +152,6 @@ describe('trace-build-file', () => { ...@@ -153,7 +152,6 @@ describe('trace-build-file', () => {
[ [
"collect-build-traces", "collect-build-traces",
"next-build", "next-build",
"run-eslint",
"run-typescript", "run-typescript",
"run-webpack", "run-webpack",
"static-check", "static-check",
......
import { createNext } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { renderViaHTTP } from 'next-test-utils'
describe('no-eslint-warn-with-no-eslint-config', () => {
let next: NextInstance
if ((global as any).isNextDeploy) {
it('should skip for deploy', () => {})
return
}
beforeAll(async () => {
next = await createNext({
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
`,
},
dependencies: {},
})
})
afterAll(() => next.destroy())
it('should render', async () => {
const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('hello world')
})
it('should not have eslint warnings when no eslint config', async () => {
expect(next.cliOutput).not.toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
expect(next.cliOutput).not.toBe('warn')
})
if (!(global as any).isNextDev) {
it('should warn with empty eslintrc', async () => {
await next.stop()
await next.patchFile('.eslintrc.json', '{}')
await next.start()
expect(next.cliOutput).toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
})
it('should warn with empty eslint config in package.json', async () => {
await next.stop()
await next.deleteFile('.eslintrc.json')
const origPkgJson = await next.readFile('package.json')
const pkgJson = JSON.parse(origPkgJson)
pkgJson.eslintConfig = {}
try {
await next.patchFile('package.json', JSON.stringify(pkgJson))
await next.start()
expect(next.cliOutput).toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
} finally {
await next.patchFile('package.json', origPkgJson)
}
})
it('should not warn with eslint config in package.json', async () => {
await next.stop()
const origPkgJson = await next.readFile('package.json')
const pkgJson = JSON.parse(origPkgJson)
pkgJson.eslintConfig = { rules: { semi: 'off' } }
try {
await next.patchFile('package.json', JSON.stringify(pkgJson))
await next.start()
expect(next.cliOutput).not.toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
} finally {
await next.patchFile('package.json', origPkgJson)
}
})
}
})
...@@ -58,7 +58,7 @@ export function runTests( ...@@ -58,7 +58,7 @@ export function runTests(
' ' ' '
)}` )}`
}, },
buildCommand: `yarn next build --no-lint`, buildCommand: `yarn next build`,
startCommand: (global as any).isNextDev startCommand: (global as any).isNextDev
? `yarn next` ? `yarn next`
: `yarn next start`, : `yarn next start`,
......
...@@ -14,9 +14,9 @@ const nextConfig = join(appDir, 'next.config.js') ...@@ -14,9 +14,9 @@ const nextConfig = join(appDir, 'next.config.js')
let nextConfigContent let nextConfigContent
async function checkFileWrite(existsAfterBuild) { async function checkFileWrite(existsAfterBuild) {
await nextBuild(appDir, [], { lint: true }) await nextBuild(appDir, [])
fs.writeFileSync(customFile, 'this is a testing file') fs.writeFileSync(customFile, 'this is a testing file')
await nextBuild(appDir, [], { lint: true }) await nextBuild(appDir, [])
expect(fs.existsSync(customFile)).toBe(existsAfterBuild) expect(fs.existsSync(customFile)).toBe(existsAfterBuild)
// `.next/cache` should be preserved in all cases // `.next/cache` should be preserved in all cases
expect(fs.existsSync(cacheDir)).toBe(true) expect(fs.existsSync(cacheDir)).toBe(true)
......
...@@ -26,7 +26,7 @@ describe('distDir', () => { ...@@ -26,7 +26,7 @@ describe('distDir', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
await fs.remove(join(appDir, 'dist')) await fs.remove(join(appDir, 'dist'))
await nextBuild(appDir, [], { lint: true }) await nextBuild(appDir, [])
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
}) })
...@@ -87,7 +87,6 @@ describe('distDir', () => { ...@@ -87,7 +87,6 @@ describe('distDir', () => {
await fs.writeFile(nextConfig, `module.exports = { distDir: '' }`) await fs.writeFile(nextConfig, `module.exports = { distDir: '' }`)
const { stderr } = await nextBuild(appDir, [], { const { stderr } = await nextBuild(appDir, [], {
stderr: true, stderr: true,
lint: true,
}) })
await fs.writeFile(nextConfig, origNextConfig) await fs.writeFile(nextConfig, origNextConfig)
...@@ -100,11 +99,10 @@ describe('distDir', () => { ...@@ -100,11 +99,10 @@ describe('distDir', () => {
const origNextConfig = await fs.readFile(nextConfig, 'utf8') const origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
`module.exports = { distDir: undefined, eslint: { ignoreDuringBuilds: true } }` `module.exports = { distDir: undefined }`
) )
const { stderr } = await nextBuild(appDir, [], { const { stderr } = await nextBuild(appDir, [], {
stderr: true, stderr: true,
lint: true,
}) })
await fs.writeFile(nextConfig, origNextConfig) await fs.writeFile(nextConfig, origNextConfig)
......
const RootLayout = () => (
<div>
<h1>Hello title</h1>
<link href="https://fonts.gstatic.com" />
</div>
)
export default RootLayout
export default class Bar {
render() {
return (
<div>
<h1>Hello title</h1>
<img src="img" />
</div>
)
}
}
export default class Foo {
render() {
return (
<div>
<h1>Hello title</h1>
<link href="/example.css" rel="stylesheet" />
</div>
)
}
}
import { Html, Main, NextScript } from 'next/document'
import Head from 'next/head'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
const Custom = () => (
<div>
<script src="https://example.com" />
</div>
)
export default Custom
{
"extends": "next/core-web-vitals",
"root": true
}
const Home = () => (
<div>
<p>Home</p>
<script src="https://example.com" />
<img src="https://example.com/image.png" />
</div>
)
export default Home
{
"eslintConfig": {
"extends": "next",
"root": true
}
}
export default class Test {
render() {
return (
<div>
<h1>Hello title</h1>
</div>
)
}
}
{
"extends": "next",
"root": true,
"rules": {
"@next/next/no-html-link-for-pages": 0,
"@next/next/no-sync-scripts": 1
}
}
const Home = () => (
<div>
<p>Home</p>
<script src="https://example.com" />
/* Badly formatted comment */
</div>
)
export default Home
{
"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,
"@next/next/no-sync-scripts": 1
}
}
const Home = () => (
<div>
<p>Home</p>
<script src="https://example.com" />
</div>
)
export default Home
const Home = () => (
<div>
<p>Home</p>
</div>
)
export default Home
const Home = () => (
<div>
<p>Home</p>
</div>
)
export default Home
{
"extends": "next",
"root": true,
"rules": {
"@next/next/no-html-link-for-pages": 0,
"@next/next/no-sync-scripts": 1
},
"ignorePatterns": ["**/components/**"]
}
const A = () => (
<div>
<p>A Component</p>
/* Test */
</div>
)
export default A
const Home = () => (
<div>
<p>Home</p>
<script src="https://example.com" />
</div>
)
export default Home
export default class Bar {
render() {
return (
<div>
<h1>Hello title</h1>
<img src="img" />
</div>
)
}
}
export default class Home {
render() {
return (
<div>
<h1>Hello title</h1>
<script src="test"></script>
</div>
)
}
}
export default class Test {
render() {
return (
<div>
<h1>Hello title</h1>
/* Badly formatted comment */
</div>
)
}
}
export default class Test {
render() {
return (
<div>
<h1>Hello title</h1>
</div>
)
}
}
module.exports = async function (results) {
// wait 1ms
await new Promise((resolve) => setTimeout(resolve, 1))
// return results as JSON
return 'Async results:\n' + JSON.stringify(results)
}
{
"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
{
"name": "eslint",
"main": "./index.js",
"version": "6.0.1"
}
const Home = () => (
<div>
<p>Home</p>
/* Badly formatted comment */
</div>
)
export default Home
{
"extends": "next",
"root": true,
"rules": {
"@next/next/no-html-link-for-pages": 0,
"@next/next/no-sync-scripts": 1
}
}
const About = () => (
<div>
<p>About</p>
<script src="https://example.com" />
</div>
)
export default About
const Home = () => (
<div>
<p>Home</p>
<script src="https://example.com" />
</div>
)
export default Home
export default class Bar {
render() {
return (
<div>
<h1>Hello title</h1>
<img src="img" />
</div>
)
}
}
export default class Home {
render() {
return (
<div>
<h1>Hello title</h1>
<script src="test"></script>
</div>
)
}
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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