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 .
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.
......
......@@ -94,18 +94,13 @@ export default nextConfig
## 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.
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"
/** @type {import('next').NextConfig} */
const nextConfig = {
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
typescript: {
// !! WARN !!
// Dangerously allow production builds to successfully complete even if
......@@ -119,9 +114,8 @@ export default nextConfig
```
- [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.
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 = {
}
```
## 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
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 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"next": "latest",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@popperjs/core": "^2.10.2",
......
......@@ -6,7 +6,7 @@
"prebuild": "npm run typegen",
"build": "next build",
"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'",
"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'",
......
......@@ -4,7 +4,7 @@
"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",
"start": "next start",
"lint": "next lint",
"lint": "eslint .",
"codegen": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js"
},
"dependencies": {
......
......@@ -5,7 +5,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"next": "latest",
......
......@@ -4,7 +4,7 @@
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint",
"lint": "eslint .",
"postinstall": "prisma generate --no-engine"
},
"prisma": {
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@apollo/client": "^3.10.1",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@headlessui/react": "^1.7.4",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@elastic/elasticsearch": "^8.6.0",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"next": "latest",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"graphql-hooks": "^7.0.0",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"next": "latest",
......
......@@ -6,7 +6,7 @@
"prebuild": "npm run i18n:compile",
"build": "next build",
"start": "next start",
"lint": "next lint",
"lint": "eslint .",
"i18n:extract": "formatjs extract 'pages/**/*.ts*' 'components/**/*.ts*' --out-file lang/en.json",
"i18n:compile": "formatjs compile-folder lang compiled-lang"
},
......
......@@ -4,7 +4,7 @@
"dev": "next",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@sentry/nextjs": "^7.60.1",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"lint": "eslint .",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
......
......@@ -4,7 +4,7 @@
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@radix-ui/react-checkbox": "^1.3.1",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"jsonwebtoken": "^9.0.2",
......
......@@ -4,7 +4,7 @@
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@libsql/client": "0.4.0",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@gympass/yoga": "^7.61.0",
......
......@@ -4,7 +4,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "eslint ."
},
"dependencies": {
"@types/node": "18.14.6",
......
......@@ -16,7 +16,6 @@ import {
} from '../cli/next-test.js'
import type { NextTelemetryOptions } from '../cli/next-telemetry.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 { NextDevOptions } from '../cli/next-dev.js'
import type { NextBuildOptions } from '../cli/next-build.js'
......@@ -129,7 +128,6 @@ program
'--debug-prerender',
'Enables debug mode for prerendering. Not for production use!'
)
.option('--no-lint', 'Disables linting.')
.option('--no-mangling', 'Disables mangling.')
.option('--profile', 'Enables production profiling for React.')
.option('--experimental-app-only', 'Builds only App Router routes.')
......@@ -239,94 +237,6 @@ program
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
.command('start')
.description(
......
......@@ -901,7 +901,6 @@ export default async function build(
reactProductionProfiling = false,
debugOutput = false,
debugPrerender = false,
runLint = true,
noMangling = false,
appDirOnly = false,
bundler = Bundler.Turbopack,
......@@ -1125,16 +1124,10 @@ export default async function build(
logBundler: true,
})
const ignoreESLint = Boolean(config.eslint.ignoreDuringBuilds)
const shouldLint = !ignoreESLint && runLint
const typeCheckingOptions: Parameters<typeof startTypeChecking>[0] = {
dir,
appDir,
pagesDir,
runLint,
shouldLint,
ignoreESLint,
telemetry,
nextBuildSpan,
config,
......@@ -1149,15 +1142,6 @@ export default async function build(
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(
config.pageExtensions,
appDir
......
......@@ -2,10 +2,8 @@ import type { NextConfigComplete } from '../server/config-shared'
import type { Telemetry } from '../telemetry/storage'
import type { Span } from '../trace'
import path from 'path'
import * as Log from './output/log'
import { Worker } from '../lib/worker'
import { verifyAndLint } from '../lib/verifyAndLint'
import createSpinner from './spinner'
import { eventTypeCheckCompleted } from '../telemetry/events'
import isError from '../lib/is-error'
......@@ -72,64 +70,42 @@ export async function startTypeChecking({
cacheDir,
config,
dir,
ignoreESLint,
nextBuildSpan,
pagesDir,
runLint,
shouldLint,
telemetry,
appDir,
}: {
cacheDir: string
config: NextConfigComplete
dir: string
ignoreESLint: boolean
nextBuildSpan: Span
pagesDir?: string
runLint: boolean
shouldLint: boolean
telemetry: Telemetry
appDir?: string
}) {
const ignoreTypeScriptErrors = Boolean(config.typescript.ignoreBuildErrors)
const eslintCacheDir = path.join(cacheDir, 'eslint/')
if (ignoreTypeScriptErrors) {
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 typeCheckingAndLintingSpinner:
| ReturnType<typeof createSpinner>
| undefined
let typeCheckingSpinnerPrefixText: string | undefined
let typeCheckingSpinner: ReturnType<typeof createSpinner> | undefined
if (!ignoreTypeScriptErrors && shouldLint) {
typeCheckingAndLintingSpinnerPrefixText =
'Running ESLint and TypeScript concurrently'
} else if (!ignoreTypeScriptErrors) {
typeCheckingAndLintingSpinnerPrefixText = 'Running TypeScript'
} else if (shouldLint) {
typeCheckingAndLintingSpinnerPrefixText = 'Running ESLint'
if (!ignoreTypeScriptErrors) {
typeCheckingSpinnerPrefixText = 'Running TypeScript'
}
// we will not create a spinner if both ignoreTypeScriptErrors and ignoreESLint are
// enabled, but we will still verifying project's tsconfig and dependencies.
if (typeCheckingAndLintingSpinnerPrefixText) {
typeCheckingAndLintingSpinner = createSpinner(
typeCheckingAndLintingSpinnerPrefixText
)
if (typeCheckingSpinnerPrefixText) {
typeCheckingSpinner = createSpinner(typeCheckingSpinnerPrefixText)
}
const typeCheckAndLintStart = process.hrtime()
try {
const [[verifyResult, typeCheckEnd], lintCheckEnd] = await Promise.all([
nextBuildSpan.traceChild('run-typescript').traceAsyncFn(() =>
const [verifyResult, typeCheckEnd] = await nextBuildSpan
.traceChild('run-typescript')
.traceAsyncFn(() =>
verifyTypeScriptSetup(
dir,
config.distDir,
......@@ -145,32 +121,14 @@ export async function startTypeChecking({
const checkEnd = process.hrtime(typeCheckAndLintStart)
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) {
typeCheckingAndLintingSpinner.stop()
if (typeCheckingSpinner) {
typeCheckingSpinner.stop()
createSpinner(
`Finished TypeScript${ignoreTypeScriptErrors ? ' config validation' : ''} in ${hrtimeDurationToString(typeCheckEnd)}`
)?.stopAndPersist()
if (lintCheckEnd) {
createSpinner(
`Finished ESLint in ${hrtimeDurationToString(lintCheckEnd)}`
)?.stopAndPersist()
}
}
if (!ignoreTypeScriptErrors && verifyResult) {
......
......@@ -16,7 +16,6 @@ export type NextBuildOptions = {
debug?: boolean
debugPrerender?: boolean
profile?: boolean
lint: boolean
mangling: boolean
turbo?: boolean
turbopack?: boolean
......@@ -37,7 +36,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => {
debugPrerender,
experimentalDebugMemoryUsage,
profile,
lint,
mangling,
experimentalAppOnly,
experimentalBuildMode,
......@@ -49,10 +47,6 @@ const nextBuild = (options: NextBuildOptions, directory?: string) => {
traceUploadUrl = experimentalUploadTrace
}
if (!lint) {
warn('Linting is disabled.')
}
if (!mangling) {
warn(
`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) => {
profile,
debug || Boolean(process.env.NEXT_DEBUG_BUILD),
debugPrerender,
lint,
!mangling,
experimentalAppOnly,
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
}
import { promises as fs, existsSync } from 'fs'
import { bold, cyan, red, underline, yellow } from '../picocolors'
import path from 'path'
import findUp from 'next/dist/compiled/find-up'
import semver from 'next/dist/compiled/semver'
import * as CommentJson from 'next/dist/compiled/comment-json'
import { formatResults } from './customFormatter'
import type { LintResult } from './customFormatter'
import { writeDefaultConfig } from './writeDefaultConfig'
import { hasEslintConfiguration } from './hasEslintConfiguration'
import { writeOutputFile } from './writeOutputFile'
import { findPagesDir } from '../find-pages-dir'
import { installDependencies } from '../install-dependencies'
import { hasNecessaryDependencies } from '../has-necessary-dependencies'
import * as Log from '../../build/output/log'
import type { EventLintCheckCompleted } from '../../telemetry/events/build'
import isError, { getProperError } from '../is-error'
import { getPkgManager } from '../helpers/get-pkg-manager'
import {
getESLintStrictValue,
getESLintPromptValues,
} from './getESLintPromptValues'
type Config = {
plugins: string[]
rules: { [key: string]: Array<number | string> }
}
// 0 is off, 1 is warn, 2 is error. See https://eslint.org/docs/user-guide/configuring/rules#configuring-rules
const VALID_SEVERITY = ['off', 'warn', 'error'] as const
type Severity = (typeof VALID_SEVERITY)[number]
function isValidSeverity(severity: string): severity is Severity {
return VALID_SEVERITY.includes(severity as Severity)
}
const requiredPackages = [
{ file: 'eslint', pkg: 'eslint', exportsRestrict: false },
{
file: 'eslint-config-next',
pkg: 'eslint-config-next',
exportsRestrict: false,
},
]
async function cliPrompt(cwd: string): Promise<{ config?: any }> {
console.log(
bold(
`${cyan(
'?'
)} How would you like to configure ESLint? https://nextjs.org/docs/app/api-reference/config/eslint`
)
)
try {
const cliSelect = (
await Promise.resolve(
require('next/dist/compiled/cli-select') as typeof import('next/dist/compiled/cli-select')
)
).default
const { value } = await cliSelect({
values: await getESLintPromptValues(cwd),
valueRenderer: (
{
title,
recommended,
}: { title: string; recommended?: boolean; config: any },
selected: boolean
) => {
const name = selected ? bold(underline(cyan(title))) : title
return name + (recommended ? bold(yellow(' (recommended)')) : '')
},
selected: cyan('❯ '),
unselected: ' ',
})
return { config: value?.config ?? null }
} catch {
return { config: null }
}
}
async function lint(
baseDir: string,
lintDirs: string[],
eslintrcFile: string | null,
pkgJsonPath: string | null,
{
lintDuringBuild = false,
eslintOptions = null,
reportErrorsOnly = false,
maxWarnings = -1,
formatter = null,
outputFile = null,
}: {
lintDuringBuild: boolean
eslintOptions: any
reportErrorsOnly: boolean
maxWarnings: number
formatter: string | null
outputFile: string | null
}
): Promise<
| string
| null
| {
output: string | null
isError: boolean
eventInfo: EventLintCheckCompleted
}
> {
try {
// Load ESLint after we're sure it exists:
const deps = hasNecessaryDependencies(baseDir, requiredPackages)
const packageManager = getPkgManager(baseDir)
if (deps.missing.some((dep) => dep.pkg === 'eslint')) {
Log.error(
`ESLint must be installed${
lintDuringBuild ? ' in order to run during builds:' : ':'
} ${bold(
cyan(
(packageManager === 'yarn'
? 'yarn add --dev'
: packageManager === 'pnpm'
? 'pnpm install --save-dev'
: 'npm install --save-dev') + ' eslint'
)
)}`
)
return null
}
const mod = await Promise.resolve(require(deps.resolved.get('eslint')!))
// If V9 config was found, use flat config, or else use legacy.
const useFlatConfig = eslintrcFile
? // eslintrcFile is absolute path
path.basename(eslintrcFile).startsWith('eslint.config.')
: false
let ESLint
// loadESLint is >= 8.57.0
// PR https://github.com/eslint/eslint/pull/18098
// Release https://github.com/eslint/eslint/releases/tag/v8.57.0
if ('loadESLint' in mod) {
// By default, configType is `flat`. If `useFlatConfig` is false, the return value is `LegacyESLint`.
// https://github.com/eslint/eslint/blob/1def4cdfab1f067c5089df8b36242cdf912b0eb6/lib/types/index.d.ts#L1609-L1613
ESLint = await mod.loadESLint({
useFlatConfig,
})
} else {
// eslint < 8.57.0, use legacy ESLint
ESLint = mod.ESLint
}
let eslintVersion = ESLint?.version ?? mod.CLIEngine?.version
if (!eslintVersion || semver.lt(eslintVersion, '7.0.0')) {
return `${red(
'error'
)} - Your project has an older version of ESLint installed${
eslintVersion ? ' (' + eslintVersion + ')' : ''
}. Please upgrade to ESLint version 7 or above`
}
let options: any = {
useEslintrc: true,
baseConfig: {},
errorOnUnmatchedPattern: false,
extensions: ['.js', '.jsx', '.ts', '.tsx'],
cache: true,
...eslintOptions,
}
if (semver.gte(eslintVersion, '9.0.0') && useFlatConfig) {
for (const option of [
'useEslintrc',
'extensions',
'ignorePath',
'reportUnusedDisableDirectives',
'resolvePluginsRelativeTo',
'rulePaths',
'inlineConfig',
'maxWarnings',
]) {
if (option in options) {
delete options[option]
}
}
}
let eslint = new ESLint(options)
let nextEslintPluginIsEnabled = false
const nextRulesEnabled = new Map<string, Severity>()
for (const configFile of [eslintrcFile, pkgJsonPath]) {
if (!configFile) continue
const completeConfig: Config | undefined =
await eslint.calculateConfigForFile(configFile)
if (!completeConfig) continue
const plugins = completeConfig.plugins
const hasNextPlugin =
// in ESLint < 9, `plugins` value is string[]
Array.isArray(plugins)
? plugins.includes('@next/next')
: // in ESLint >= 9, `plugins` value is Record<string, unknown>
'@next/next' in plugins
if (hasNextPlugin) {
nextEslintPluginIsEnabled = true
for (const [name, [severity]] of Object.entries(completeConfig.rules)) {
if (!name.startsWith('@next/next/')) {
continue
}
if (
typeof severity === 'number' &&
severity >= 0 &&
severity < VALID_SEVERITY.length
) {
nextRulesEnabled.set(name, VALID_SEVERITY[severity])
} else if (
typeof severity === 'string' &&
isValidSeverity(severity)
) {
nextRulesEnabled.set(name, severity)
}
}
break
}
}
const pagesDir = findPagesDir(baseDir).pagesDir
const pagesDirRules = pagesDir ? ['@next/next/no-html-link-for-pages'] : []
if (nextEslintPluginIsEnabled) {
let updatedPagesDir = false
for (const rule of pagesDirRules) {
if (
!options.baseConfig!.rules?.[rule] &&
!options.baseConfig!.rules?.[
rule.replace('@next/next', '@next/babel-plugin-next')
]
) {
if (!options.baseConfig!.rules) {
options.baseConfig!.rules = {}
}
options.baseConfig!.rules[rule] = [1, pagesDir]
updatedPagesDir = true
}
}
if (updatedPagesDir) {
eslint = new ESLint(options)
}
} else {
Log.warn('')
Log.warn(
'The Next.js plugin was not detected in your ESLint configuration. See https://nextjs.org/docs/app/api-reference/config/eslint#migrating-existing-config'
)
}
const lintStart = process.hrtime()
let results = await eslint.lintFiles(lintDirs)
let selectedFormatter = null
if (options.fix) await ESLint.outputFixes(results)
if (reportErrorsOnly) results = await ESLint.getErrorResults(results) // Only return errors if --quiet flag is used
if (formatter) selectedFormatter = await eslint.loadFormatter(formatter)
const formattedResult = await formatResults(
baseDir,
results,
selectedFormatter?.format
)
const lintEnd = process.hrtime(lintStart)
const totalWarnings = results.reduce(
(sum: number, file: LintResult) => sum + file.warningCount,
0
)
if (outputFile) await writeOutputFile(outputFile, formattedResult.output)
return {
output: formattedResult.outputWithMessages,
isError:
ESLint.getErrorResults(results)?.length > 0 ||
(maxWarnings >= 0 && totalWarnings > maxWarnings),
eventInfo: {
durationInSeconds: lintEnd[0],
eslintVersion: eslintVersion,
lintedFilesCount: results.length,
lintFix: !!options.fix,
nextEslintPluginVersion:
nextEslintPluginIsEnabled && deps.resolved.has('eslint-config-next')
? require(
path.join(
path.dirname(deps.resolved.get('eslint-config-next')!),
'package.json'
)
).version
: null,
nextEslintPluginErrorsCount: formattedResult.totalNextPluginErrorCount,
nextEslintPluginWarningsCount:
formattedResult.totalNextPluginWarningCount,
nextRulesEnabled: Object.fromEntries(nextRulesEnabled),
},
}
} catch (err) {
if (lintDuringBuild) {
Log.error(
`ESLint: ${
isError(err) && err.message ? err.message.replace(/\n/g, ' ') : err
}`
)
return null
} else {
throw getProperError(err)
}
}
}
export async function runLintCheck(
baseDir: string,
lintDirs: string[],
opts: {
lintDuringBuild?: boolean
eslintOptions?: any
reportErrorsOnly?: boolean
maxWarnings?: number
formatter?: string | null
outputFile?: string | null
strict?: boolean
}
): ReturnType<typeof lint> {
const {
lintDuringBuild = false,
eslintOptions = null,
reportErrorsOnly = false,
maxWarnings = -1,
formatter = null,
outputFile = null,
strict = false,
} = opts
try {
// Find user's .eslintrc file
// See: https://eslint.org/docs/user-guide/configuring/configuration-files#configuration-file-formats
const eslintrcFile =
(await findUp(
[
// eslint v9
'eslint.config.js',
'eslint.config.mjs',
'eslint.config.cjs',
// TS extensions require to install a separate package `jiti`.
// https://eslint.org/docs/latest/use/configure/configuration-files#typescript-configuration-files
'eslint.config.ts',
'eslint.config.mts',
'eslint.config.cts',
// eslint <= v8
'.eslintrc.js',
'.eslintrc.cjs',
'.eslintrc.yaml',
'.eslintrc.yml',
'.eslintrc.json',
'.eslintrc',
],
{
cwd: baseDir,
}
)) ?? null
const pkgJsonPath = (await findUp('package.json', { cwd: baseDir })) ?? null
let packageJsonConfig = null
if (pkgJsonPath) {
const pkgJsonContent = await fs.readFile(pkgJsonPath, {
encoding: 'utf8',
})
packageJsonConfig = CommentJson.parse(pkgJsonContent)
}
const config = await hasEslintConfiguration(eslintrcFile, packageJsonConfig)
let deps
if (config.exists) {
// Run if ESLint config exists
return await lint(baseDir, lintDirs, eslintrcFile, pkgJsonPath, {
lintDuringBuild,
eslintOptions,
reportErrorsOnly,
maxWarnings,
formatter,
outputFile,
})
} else {
// Display warning if no ESLint configuration is present inside
// config file during "next build", no warning is shown when
// no eslintrc file is present
if (lintDuringBuild) {
if (config.emptyPkgJsonConfig || config.emptyEslintrc) {
Log.warn(
`No ESLint configuration detected. Run ${bold(
cyan('next lint')
)} to begin setup`
)
}
return null
} else {
// Ask user what config they would like to start with for first time "next lint" setup
const { config: selectedConfig } = strict
? await getESLintStrictValue(baseDir)
: await cliPrompt(baseDir)
if (selectedConfig == null) {
// Show a warning if no option is selected in prompt
Log.warn(
'If you set up ESLint yourself, we recommend adding the Next.js ESLint plugin. See https://nextjs.org/docs/app/api-reference/config/eslint#migrating-existing-config'
)
return null
} else {
// Check if necessary deps installed, and install any that are missing
deps = await hasNecessaryDependencies(baseDir, requiredPackages)
if (deps.missing.length > 0) {
deps.missing.forEach((dep) => {
if (dep.pkg === 'eslint') {
// pin to v9 to avoid breaking changes
dep.pkg = 'eslint@^9'
}
})
await installDependencies(baseDir, deps.missing, true)
}
// Write default ESLint config.
// Check for /pages and src/pages is to make sure this happens in Next.js folder
if (
['app', 'src/app', 'pages', 'src/pages'].some((dir) =>
existsSync(path.join(baseDir, dir))
)
) {
await writeDefaultConfig(
baseDir,
config,
selectedConfig,
eslintrcFile,
pkgJsonPath,
packageJsonConfig
)
}
}
Log.ready(
`ESLint has successfully been configured. Run ${bold(
cyan('next lint')
)} again to view warnings and errors.`
)
return null
}
}
} catch (err) {
throw err
}
}
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(() =>
.optional(),
distDir: z.string().min(1).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(),
experimental: z.strictObject(experimentalSchema).optional(),
exportPathMap: z
......
......@@ -43,13 +43,6 @@ export interface DomainLocale {
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 {
/** Do not run TypeScript during production builds (`next build`). */
ignoreBuildErrors?: boolean
......@@ -916,12 +909,6 @@ export interface NextConfig {
*/
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)
*/
......@@ -1340,9 +1327,6 @@ export interface NextConfig {
export const defaultConfig = Object.freeze({
env: {},
webpack: null,
eslint: {
ignoreDuringBuilds: false,
},
typescript: {
ignoreBuildErrors: false,
tsconfigPath: undefined,
......
......@@ -186,7 +186,6 @@ export type EventBuildFeatureUsage = {
| 'swcEmotion'
| `swc/target/${SWC_TARGET_TRIPLE}`
| 'turbotrace'
| 'build-lint'
| 'vercelImageGeneration'
| 'transpilePackages'
| '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 @@
"name": "next-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"internal-pkg": "link:./internal-pkg"
},
......
......@@ -140,7 +140,6 @@ describe('trace-build-file', () => {
expect([...foundEvents].sort()).toMatchInlineSnapshot(`
[
"next-build",
"run-eslint",
"run-turbopack",
"run-typescript",
"static-check",
......@@ -153,7 +152,6 @@ describe('trace-build-file', () => {
[
"collect-build-traces",
"next-build",
"run-eslint",
"run-typescript",
"run-webpack",
"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(
' '
)}`
},
buildCommand: `yarn next build --no-lint`,
buildCommand: `yarn next build`,
startCommand: (global as any).isNextDev
? `yarn next`
: `yarn next start`,
......
......@@ -14,9 +14,9 @@ const nextConfig = join(appDir, 'next.config.js')
let nextConfigContent
async function checkFileWrite(existsAfterBuild) {
await nextBuild(appDir, [], { lint: true })
await nextBuild(appDir, [])
fs.writeFileSync(customFile, 'this is a testing file')
await nextBuild(appDir, [], { lint: true })
await nextBuild(appDir, [])
expect(fs.existsSync(customFile)).toBe(existsAfterBuild)
// `.next/cache` should be preserved in all cases
expect(fs.existsSync(cacheDir)).toBe(true)
......
......@@ -26,7 +26,7 @@ describe('distDir', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
await fs.remove(join(appDir, 'dist'))
await nextBuild(appDir, [], { lint: true })
await nextBuild(appDir, [])
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
......@@ -87,7 +87,6 @@ describe('distDir', () => {
await fs.writeFile(nextConfig, `module.exports = { distDir: '' }`)
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
lint: true,
})
await fs.writeFile(nextConfig, origNextConfig)
......@@ -100,11 +99,10 @@ describe('distDir', () => {
const origNextConfig = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
`module.exports = { distDir: undefined, eslint: { ignoreDuringBuilds: true } }`
`module.exports = { distDir: undefined }`
)
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
lint: true,
})
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>
)
}
export default function Home() {
return (
<div>
<h1>Hello World!</h1>
</div>
)
}
export default class Test {
render() {
return (
<div>
<h1>Hello title</h1>
</div>
)
}
}
{
"root": true,
"extends": "eslint:recommended"
}
const Home = () => (
<div>
<p>Home</p>
</div>
)
export default Home
{
"extends": "plugin:@next/next/core-web-vitals-legacy",
"root": true,
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2015,
"ecmaFeatures": {
"jsx": true
}
}
}
const Home = () => (
<div>
<p>Home</p>
<script src="https://example.com" />
<img src="https://example.com/image.png" />
</div>
)
export default Home
{
"extends": "plugin:@next/next/recommended-legacy",
"root": true,
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2015,
"ecmaFeatures": {
"jsx": true
}
}
}
import Document from 'next/document'
const Home = () => (
<div>
<p>Home</p>
<script src="https://example.com" />
</div>
)
export default Home
import fs from 'fs-extra'
import { join } from 'path'
import { nextLint } from 'next-test-utils'
const dirEslintCache = join(__dirname, '../eslint-cache')
const dirEslintCacheCustomDir = join(__dirname, '../eslint-cache-custom-dir')
test('eslint caching is enabled by default', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextLint(dirEslintCache, [])
const files = await fs.readdir(join(cacheDir, 'eslint/'))
const cacheExists = files.some((f) => /\.cache/.test(f))
expect(cacheExists).toBe(true)
})
test('eslint caching is disabled with the --no-cache flag', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextLint(dirEslintCache, ['--no-cache'])
expect(fs.existsSync(join(cacheDir, 'eslint/'))).toBe(false)
})
test('the default eslint cache lives in the user defined build directory', async () => {
const oldCacheDir = join(dirEslintCacheCustomDir, '.next', 'cache')
const newCacheDir = join(dirEslintCacheCustomDir, 'build', 'cache')
await fs.remove(oldCacheDir)
await fs.remove(newCacheDir)
await nextLint(dirEslintCacheCustomDir, [])
expect(fs.existsSync(oldCacheDir)).toBe(false)
const files = await fs.readdir(join(newCacheDir, 'eslint/'))
const cacheExists = files.some((f) => /\.cache/.test(f))
expect(cacheExists).toBe(true)
})
test('the --cache-location flag allows the user to define a separate cache location', async () => {
const cacheFile = join(dirEslintCache, '.eslintcache')
await fs.remove(cacheFile)
await nextLint(dirEslintCache, ['--cache-location', cacheFile])
const hasCache = fs.existsSync(cacheFile)
await fs.remove(cacheFile) // remove after generate
expect(hasCache).toBe(true)
})
const getEslintCacheContent = async (cacheDir) => {
const eslintCacheDir = join(cacheDir, 'eslint/')
let files = await fs.readdir(eslintCacheDir)
let cacheFiles = files.filter((f) => /\.cache/.test(f))
expect(cacheFiles.length).toBe(1)
const cacheFile = join(eslintCacheDir, cacheFiles[0])
return await fs.readFile(cacheFile, 'utf8')
}
test('the default eslint caching strategy is metadata', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextLint(dirEslintCache)
const defaultStrategyCache = await getEslintCacheContent(cacheDir)
await fs.remove(cacheDir)
await nextLint(dirEslintCache, ['--cache-strategy', 'metadata'])
const metadataStrategyCache = await getEslintCacheContent(cacheDir)
expect(metadataStrategyCache).toBe(defaultStrategyCache)
})
test('cache with content strategy is different from the one with default strategy', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextLint(dirEslintCache)
const defaultStrategyCache = await getEslintCacheContent(cacheDir)
await fs.remove(cacheDir)
await nextLint(dirEslintCache, ['--cache-strategy', 'content'])
const contentStrategyCache = await getEslintCacheContent(cacheDir)
expect(contentStrategyCache).not.toBe(defaultStrategyCache)
})
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild } from 'next-test-utils'
const dirCustomConfig = join(__dirname, '../custom-config')
const dirIgnoreDuringBuilds = join(__dirname, '../ignore-during-builds')
const dirBaseDirectories = join(__dirname, '../base-directories')
const dirCustomDirectories = join(__dirname, '../custom-directories')
const dirInvalidOlderEslintVersion = join(
__dirname,
'../invalid-eslint-version'
)
const dirEmptyDirectory = join(__dirname, '../empty-directory')
const dirEslintIgnore = join(__dirname, '../eslint-ignore')
const dirNoEslintPlugin = join(__dirname, '../no-eslint-plugin')
const dirEslintCache = join(__dirname, '../eslint-cache')
const dirEslintCacheCustomDir = join(__dirname, '../eslint-cache-custom-dir')
describe('Next Build', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
test('shows warnings and errors', async () => {
const { stdout, stderr } = await nextBuild(dirCustomConfig, [], {
stdout: true,
stderr: true,
lint: true,
})
const output = stdout + stderr
expect(output).toContain(
'Warning: Synchronous scripts should not be used.'
)
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
})
test('ignore during builds', async () => {
const { stdout, stderr } = await nextBuild(dirIgnoreDuringBuilds, [], {
stdout: true,
stderr: true,
lint: true,
})
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('base directories are linted by default during builds', async () => {
const { stdout, stderr } = await nextBuild(dirBaseDirectories, [], {
stdout: true,
stderr: true,
lint: true,
})
const output = stdout + stderr
expect(output).toContain('Failed to compile')
expect(output).toContain(
'Error: `next/head` should not be imported in `pages/_document.js`. Use `<Head />` from `next/document` instead'
)
expect(output).toContain(
'Warning: 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.'
)
expect(output).toContain('Warning: Do not include stylesheets manually')
expect(output).toContain(
'Warning: Synchronous scripts should not be used'
)
expect(output).toContain(
'Warning: `rel="preconnect"` is missing from Google Font'
)
// Files in app, pages, components, lib, and src directories are linted
expect(output).toContain('pages/_document.js')
expect(output).toContain('components/bar.js')
expect(output).toContain('lib/foo.js')
expect(output).toContain('src/index.js')
expect(output).toContain('app/layout.js')
})
test('custom directories', async () => {
const { stdout, stderr } = await nextBuild(dirCustomDirectories, [], {
stdout: true,
stderr: true,
lint: 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: Synchronous scripts should not be used.'
)
})
test('invalid older eslint version', async () => {
const { stdout, stderr } = await nextBuild(
dirInvalidOlderEslintVersion,
[],
{
stdout: true,
stderr: true,
lint: true,
}
)
const output = stdout + stderr
expect(output).toContain(
'Your project has an older version of ESLint installed'
)
})
test('empty directories do not fail the build', async () => {
const { stdout, stderr } = await nextBuild(dirEmptyDirectory, [], {
stdout: true,
stderr: true,
lint: true,
})
const output = stdout + stderr
expect(output).not.toContain('Build error occurred')
expect(output).not.toContain('NoFilesFoundError')
expect(output).toContain(
'Warning: Synchronous scripts should not be used.'
)
expect(output).toContain('Compiled successfully')
})
test('eslint ignored directories do not fail the build', async () => {
const { stdout, stderr } = await nextBuild(dirEslintIgnore, [], {
stdout: true,
stderr: true,
lint: true,
})
const output = stdout + stderr
expect(output).not.toContain('Build error occurred')
expect(output).not.toContain('AllFilesIgnoredError')
expect(output).toContain(
'Warning: Synchronous scripts should not be used.'
)
expect(output).toContain('Compiled successfully')
})
test('missing Next.js plugin', async () => {
const { stdout, stderr } = await nextBuild(dirNoEslintPlugin, [], {
stdout: true,
stderr: true,
lint: true,
})
const output = stdout + stderr
expect(output).toContain(
'The Next.js plugin was not detected in your ESLint configuration'
)
})
test('eslint caching is enabled', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextBuild(dirEslintCache, [], {
lint: true,
})
const files = await fs.readdir(join(cacheDir, 'eslint/'))
const cacheExists = files.some((f) => /\.cache/.test(f))
expect(cacheExists).toBe(true)
})
test('eslint cache lives in the user defined build directory', async () => {
const oldCacheDir = join(dirEslintCacheCustomDir, '.next', 'cache')
const newCacheDir = join(dirEslintCacheCustomDir, 'build', 'cache')
await fs.remove(oldCacheDir)
await fs.remove(newCacheDir)
await nextBuild(dirEslintCacheCustomDir, [], {
lint: true,
})
expect(fs.existsSync(oldCacheDir)).toBe(false)
const files = await fs.readdir(join(newCacheDir, 'eslint/'))
const cacheExists = files.some((f) => /\.cache/.test(f))
expect(cacheExists).toBe(true)
})
}
)
})
import fs from 'fs-extra'
import os from 'os'
import { join } from 'path'
import findUp from 'next/dist/compiled/find-up'
import { nextLint } from 'next-test-utils'
const dirFirstTimeSetup = join(__dirname, '../first-time-setup')
const dirCustomConfig = join(__dirname, '../custom-config')
const dirWebVitalsConfig = join(__dirname, '../config-core-web-vitals')
const dirPluginRecommendedConfig = join(
__dirname,
'../plugin-recommended-config'
)
const dirPluginCoreWebVitalsConfig = join(
__dirname,
'../plugin-core-web-vitals-config'
)
const dirIgnoreDuringBuilds = join(__dirname, '../ignore-during-builds')
const dirBaseDirectories = join(__dirname, '../base-directories')
const dirCustomDirectories = join(__dirname, '../custom-directories')
const dirConfigInPackageJson = join(__dirname, '../config-in-package-json')
const dirMaxWarnings = join(__dirname, '../max-warnings')
const dirEmptyDirectory = join(__dirname, '../empty-directory')
const dirNoConfig = join(__dirname, '../no-config')
const dirFileLinting = join(__dirname, '../file-linting')
const mjsCjsLinting = join(__dirname, '../mjs-cjs-linting')
const dirTypescript = join(__dirname, '../with-typescript')
const formatterAsync = join(__dirname, '../formatter-async/format.js')
describe('Next Lint', () => {
describe('First Time Setup ', () => {
async function nextLintTemp(setupCallback, isApp = false) {
const folder = join(os.tmpdir(), Math.random().toString(36).substring(2))
await fs.mkdirp(folder)
await fs.copy(join(dirNoConfig, isApp ? 'app' : ''), folder)
await setupCallback?.(folder)
try {
const { stdout, stderr } = await nextLint(folder, ['--strict'], {
stderr: true,
stdout: true,
cwd: folder,
})
console.log({ stdout, stderr })
const pkgJson = JSON.parse(
await fs.readFile(join(folder, 'package.json'), 'utf8')
)
const eslintrcJson = JSON.parse(
await fs.readFile(join(folder, '.eslintrc.json'), 'utf8')
)
return { stdout, pkgJson, eslintrcJson }
} finally {
await fs.remove(folder)
}
}
test('show a prompt to set up ESLint if no configuration detected', async () => {
const eslintrcJson = join(dirFirstTimeSetup, '.eslintrc.json')
await fs.writeFile(eslintrcJson, '')
const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('How would you like to configure ESLint?')
// Different options that can be selected
expect(output).toContain('Strict (recommended)')
expect(output).toContain('Base')
expect(output).toContain('Cancel')
})
for (const { packageManger, lockFile } of [
{ packageManger: 'yarn', lockFile: 'yarn.lock' },
{ packageManger: 'pnpm', lockFile: 'pnpm-lock.yaml' },
{ packageManger: 'npm', lockFile: 'package-lock.json' },
]) {
test(`installs eslint and eslint-config-next as devDependencies if missing with ${packageManger}`, async () => {
const { stdout, pkgJson } = await nextLintTemp(async (folder) => {
await fs.writeFile(join(folder, lockFile), '')
})
expect(stdout).toContain(
`Installing devDependencies (${packageManger}):`
)
expect(stdout).toContain('eslint')
expect(stdout).toContain('eslint-config-next')
expect(stdout).toContain(packageManger)
expect(pkgJson.devDependencies).toHaveProperty('eslint')
expect(pkgJson.devDependencies).toHaveProperty('eslint-config-next')
// App Router
const { stdout: appStdout, pkgJson: appPkgJson } = await nextLintTemp(
async (folder) => {
await fs.writeFile(join(folder, lockFile), '')
},
true
)
expect(appStdout).toContain(
`Installing devDependencies (${packageManger}):`
)
expect(appStdout).toContain('eslint')
expect(appStdout).toContain('eslint-config-next')
expect(appStdout).toContain(packageManger)
expect(appPkgJson.devDependencies).toHaveProperty('eslint')
expect(appPkgJson.devDependencies).toHaveProperty('eslint-config-next')
})
}
test('creates .eslintrc.json file with a default configuration', async () => {
const { stdout, eslintrcJson } = await nextLintTemp()
expect(stdout).toContain(
'We created the .eslintrc.json file for you and included your selected configuration'
)
expect(eslintrcJson).toMatchObject({ extends: 'next/core-web-vitals' })
})
test('creates .eslintrc.json file with a default app router configuration', async () => {
// App Router
const { stdout: appStdout, eslintrcJson: appEslintrcJson } =
await nextLintTemp(null, true)
expect(appStdout).toContain(
'We created the .eslintrc.json file for you and included your selected configuration'
)
expect(appEslintrcJson).toMatchObject({ extends: 'next/core-web-vitals' })
})
test('shows a successful message when completed', async () => {
const { stdout } = await nextLintTemp()
expect(stdout).toContain(
'ESLint has successfully been configured. Run next lint again to view warnings and errors'
)
// App Router
const { stdout: appStdout } = await nextLintTemp(null, true)
expect(appStdout).toContain(
'ESLint has successfully been configured. Run next lint again to view warnings and errors'
)
})
})
test('should generate next-env.d.ts before lint command', async () => {
await nextLint(dirTypescript, [], {
stdout: true,
stderr: true,
})
const files = await fs.readdir(dirTypescript)
expect(files).toContain('next-env.d.ts')
})
for (const { dir } of [
{ dir: dirEmptyDirectory },
{ dir: dirIgnoreDuringBuilds },
{ dir: dirCustomDirectories },
{ dir: dirConfigInPackageJson },
]) {
test('should not generate next-env.d.ts without typescript', async () => {
await nextLint(dir, [], {
stdout: true,
stderr: true,
})
const files = await fs.readdir(dir)
expect(files).not.toContain('next-env.d.ts')
})
}
test('should add relative path for dist types in tsconfig.json when app dir exist', async () => {
await nextLint(dirTypescript, [], {
stdout: true,
stderr: true,
})
const tsConfigPath = join(dirTypescript, '../with-typescript/tsconfig.json')
const tsConfigContent = await fs.readFile(tsConfigPath, {
encoding: 'utf8',
})
const tsConfigJson = JSON.parse(tsConfigContent)
expect(tsConfigJson.include).toContain('.build/types/**/*.ts')
})
test('shows warnings and errors', async () => {
const { stdout, stderr } = await nextLint(dirCustomConfig, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('Warning: Synchronous scripts should not be used.')
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
})
test('verify options name and type with auto-generated help output', async () => {
const options = [
'-d, --dir, <dirs...>',
'--file, <files...>',
'--ext, [exts...]',
'-c, --config, <config>',
'--resolve-plugins-relative-to, <rprt>',
'--strict',
'--rulesdir, <rulesdir...>',
'--fix',
'--fix-type <fixType>',
'--ignore-path <path>',
'--no-ignore',
'--quiet',
'--max-warnings [maxWarnings]',
'-o, --output-file, <outputFile>',
'-f, --format, <format>',
'--no-inline-config',
'--report-unused-disable-directives-severity <level>',
'--no-cache',
'--cache-location, <cacheLocation>',
'--cache-strategy, [cacheStrategy]',
'--error-on-unmatched-pattern',
]
const { stdout, stderr } = await nextLint(dirNoConfig, ['-h'], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
for (let option of options) {
expect(output).toContain(option)
}
})
test('base directories are linted by default', async () => {
const { stdout, stderr } = await nextLint(dirBaseDirectories, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'Error: `next/head` should not be imported in `pages/_document.js`. Use `<Head />` from `next/document` instead'
)
expect(output).toContain(
'Warning: 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.'
)
expect(output).toContain('Warning: Do not include stylesheets manually')
expect(output).toContain('Warning: Synchronous scripts should not be used')
expect(output).toContain(
'Warning: `rel="preconnect"` is missing from Google Font'
)
// Files in app, pages, components, lib, and src directories are linted
expect(output).toContain('pages/_document.js')
expect(output).toContain('components/bar.js')
expect(output).toContain('lib/foo.js')
expect(output).toContain('src/index.js')
expect(output).toContain('app/layout.js')
})
test('shows warnings and errors with next/core-web-vitals config', async () => {
const { stdout, stderr } = await nextLint(dirWebVitalsConfig, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'Warning: 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.'
)
expect(output).toContain('Error: Synchronous scripts should not be used.')
})
test('shows warnings and errors when extending plugin recommended config', async () => {
const { stdout, stderr } = await nextLint(dirPluginRecommendedConfig, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('Warning: Synchronous scripts should not be used.')
expect(output).toContain(
'Error: `<Document />` from `next/document` should not be imported outside of `pages/_document.js`.'
)
})
test('shows warnings and errors when extending plugin core-web-vitals config', async () => {
const { stdout, stderr } = await nextLint(
dirPluginCoreWebVitalsConfig,
[],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain(
'Warning: 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.'
)
expect(output).toContain('Error: Synchronous scripts should not be used.')
})
test('success message when no warnings or errors', async () => {
const eslintrcJson = join(dirFirstTimeSetup, '.eslintrc.json')
await fs.writeFile(eslintrcJson, '{ "extends": "next", "root": true }\n')
const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('No ESLint warnings or errors')
})
test("don't create .eslintrc file if package.json has eslintConfig field", async () => {
const eslintrcFile =
(await findUp(
[
'.eslintrc.js',
'.eslintrc.cjs',
'.eslintrc.yaml',
'.eslintrc.yml',
'.eslintrc.json',
'.eslintrc',
],
{
cwd: '.',
}
)) ?? null
try {
// If we found a .eslintrc file, it's probably config from root Next.js directory. Rename it during the test
if (eslintrcFile) {
await fs.move(eslintrcFile, `${eslintrcFile}.original`)
}
const { stdout, stderr } = await nextLint(dirConfigInPackageJson, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).not.toContain(
'We created the .eslintrc file for you and included your selected configuration'
)
} finally {
// Restore original .eslintrc file
if (eslintrcFile) {
await fs.move(`${eslintrcFile}.original`, eslintrcFile)
}
}
})
test('quiet flag suppresses warnings and only reports errors', async () => {
const { stdout, stderr } = await nextLint(dirCustomConfig, ['--quiet'], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
expect(output).not.toContain(
'Warning: Synchronous scripts should not be used.'
)
})
test('custom directories', async () => {
const { stdout, stderr } = await nextLint(dirCustomDirectories, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
expect(output).toContain('Warning: Synchronous scripts should not be used.')
})
test('max warnings flag errors when warnings exceed threshold', async () => {
const { stdout, stderr } = await nextLint(
dirMaxWarnings,
['--max-warnings', 1],
{
stdout: true,
stderr: true,
}
)
expect(stderr).not.toEqual('')
expect(stderr).toContain('Warning: Synchronous scripts should not be used.')
expect(stdout).not.toContain(
'Warning: Synchronous scripts should not be used.'
)
})
test('max warnings flag does not error when warnings do not exceed threshold', async () => {
const { stdout, stderr } = await nextLint(
dirMaxWarnings,
['--max-warnings', 2],
{
stdout: true,
stderr: true,
}
)
expect(stderr).not.toContain(
'Warning: Synchronous scripts should not be used.'
)
expect(stdout).toContain('Warning: Synchronous scripts should not be used.')
})
test('format flag supports additional user-defined formats', async () => {
const { stdout, stderr } = await nextLint(
dirMaxWarnings,
['-f', 'codeframe'],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain('warning: Synchronous scripts should not be used.')
expect(stdout).toContain('<script src="https://example.com" />')
expect(stdout).toContain('2 warnings found')
})
test('format flag supports async formatters', async () => {
const { stdout, stderr } = await nextLint(
dirMaxWarnings,
['-f', formatterAsync],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain('Async results:')
expect(stdout).toContain('Synchronous scripts should not be used.')
})
test('file flag can selectively lint only a single file', async () => {
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--file', 'utils/math.js'],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain('utils/math.js')
expect(output).toContain(
'Comments inside children section of tag should be placed inside braces'
)
expect(output).not.toContain('pages/')
expect(output).not.toContain('Synchronous scripts should not be used.')
})
test('file flag can selectively lints multiple files', async () => {
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--file', 'utils/math.js', '--file', 'pages/bar.js'],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain('utils/math.js')
expect(output).toContain(
'Comments inside children section of tag should be placed inside braces'
)
expect(output).toContain('pages/bar.js')
expect(output).toContain(
'Warning: 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.'
)
expect(output).not.toContain('pages/index.js')
expect(output).not.toContain('Synchronous scripts should not be used.')
})
test('format flag "json" creates a file respecting the chosen format', async () => {
const filePath = `${__dirname}/output/output.json`
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--format', 'json', '--output-file', filePath],
{
stdout: true,
stderr: true,
}
)
const cliOutput = stdout + stderr
const fileOutput = await fs.readJSON(filePath)
expect(cliOutput).toContain(`The output file has been created: ${filePath}`)
if (fileOutput && fileOutput.length) {
fileOutput.forEach((file) => {
expect(file).toHaveProperty('filePath')
expect(file).toHaveProperty('messages')
expect(file).toHaveProperty('errorCount')
expect(file).toHaveProperty('warningCount')
expect(file).toHaveProperty('fixableErrorCount')
expect(file).toHaveProperty('fixableWarningCount')
expect(file).toHaveProperty('source')
expect(file).toHaveProperty('usedDeprecatedRules')
})
expect(fileOutput[0].messages).toEqual(
expect.arrayContaining([
expect.objectContaining({
message:
'img elements must have an alt prop, either with meaningful text, or an empty string for decorative images.',
}),
expect.objectContaining({
message:
'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[1].messages).toEqual(
expect.arrayContaining([
expect.objectContaining({
message:
'Synchronous scripts should not be used. See: https://nextjs.org/docs/messages/no-sync-scripts',
}),
])
)
}
})
test('lint files with cjs and mjs file extension', async () => {
const { stdout, stderr } = await nextLint(mjsCjsLinting, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('pages/bar.mjs')
expect(output).toContain(
'img elements must have an alt prop, either with meaningful text, or an empty string for decorative images.'
)
expect(output).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(output).toContain('pages/index.cjs')
expect(output).toContain(
'Synchronous scripts should not be used. See: https://nextjs.org/docs/messages/no-sync-scripts'
)
})
})
export default function Layout({ children }) {
return (
<html>
<head>
<title>Next.js lint test with TypeScript</title>
</head>
<body>
<main>{children}</main>
</body>
</html>
)
}
const Home = () => (
<div>
<p>Home</p>
</div>
)
export default Home
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true,
"target": "ES2017"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".build/types/**/*.ts"],
"exclude": ["node_modules"]
}
module.exports = {
eslint: {
ignoreDuringBuilds: true,
},
}
module.exports = {}
module.exports = {
eslint: {
ignoreDuringBuilds: true,
},
}
module.exports = {}
......@@ -5,7 +5,6 @@ import {
killApp,
launchApp,
nextBuild,
nextLint,
waitFor,
} from 'next-test-utils'
import fs from 'fs-extra'
......@@ -161,113 +160,6 @@ describe('config telemetry', () => {
}
})
it('emits telemetry for lint during build', async () => {
await fs.writeFile(
path.join(appDir, '.eslintrc'),
`{ "root": true, "extends": "next" }`
)
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 },
lint: true,
})
await fs.remove(path.join(appDir, '.eslintrc'))
try {
const event1 = /NEXT_LINT_CHECK_COMPLETED[\s\S]+?{([\s\S}]+?)^}/m
.exec(stderr)
.pop()
expect(event1).toMatch(/"durationInSeconds": [\d]{1,}/)
expect(event1).toMatch(/"eslintVersion": ".*?\..*?\..*?"/)
expect(event1).toMatch(/"lintedFilesCount": [\d]{1,}/)
expect(event1).toMatch(/"lintFix": false/)
expect(event1).toMatch(/"buildLint": true/)
expect(event1).toMatch(/"nextEslintPluginVersion": ".*?\..*?\..*?"/)
expect(event1).toMatch(/"nextEslintPluginErrorsCount": \d{1,}/)
expect(event1).toMatch(/"nextEslintPluginWarningsCount": \d{1,}/)
expect(event1).toMatch(`"nextRulesEnabled": {`)
expect(event1).toMatch(/"@next\/next\/.+?": "(off|warn|error)"/)
const featureUsageEvents = findAllTelemetryEvents(
stderr,
'NEXT_BUILD_FEATURE_USAGE'
)
expect(featureUsageEvents).toContainEqual({
featureName: 'build-lint',
invocationCount: 1,
})
} catch (err) {
require('console').error('failing stderr', stderr, err)
throw err
}
})
it(`emits telemetry for lint during build when '--no-lint' is specified`, async () => {
const { stderr } = await nextBuild(appDir, ['--no-lint'], {
stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 },
})
const events = findAllTelemetryEvents(
stderr,
'NEXT_BUILD_FEATURE_USAGE'
)
expect(events).toContainEqual({
featureName: 'build-lint',
invocationCount: 0,
})
})
it(`emits telemetry for lint during build when 'ignoreDuringBuilds' is specified`, async () => {
const nextConfig = path.join(appDir, 'next.config.js')
await fs.writeFile(
nextConfig,
`module.exports = { eslint: { ignoreDuringBuilds: true } }`
)
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 },
lint: true,
})
await fs.remove(nextConfig)
const events = findAllTelemetryEvents(
stderr,
'NEXT_BUILD_FEATURE_USAGE'
)
expect(events).toContainEqual({
featureName: 'build-lint',
invocationCount: 0,
})
})
it('emits telemetry for `next lint`', async () => {
await fs.writeFile(
path.join(appDir, '.eslintrc'),
`{ "root": true, "extends": "next" }`
)
const { stderr } = await nextLint(appDir, [], {
stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 },
})
await fs.remove(path.join(appDir, '.eslintrc'))
const event1 = /NEXT_LINT_CHECK_COMPLETED[\s\S]+?{([\s\S]+?)^}/m
.exec(stderr)
.pop()
expect(event1).toMatch(/"durationInSeconds": [\d]{1,}/)
expect(event1).toMatch(/"eslintVersion": ".*?\..*?\..*?"/)
expect(event1).toMatch(/"lintedFilesCount": [\d]{1,}/)
expect(event1).toMatch(/"lintFix": false/)
expect(event1).toMatch(/"buildLint": false/)
expect(event1).toMatch(/"nextEslintPluginVersion": ".*?\..*?\..*?"/)
expect(event1).toMatch(/"nextEslintPluginErrorsCount": \d{1,}/)
expect(event1).toMatch(/"nextEslintPluginWarningsCount": \d{1,}/)
expect(event1).toMatch(`"nextRulesEnabled": {`)
expect(event1).toMatch(/"@next\/next\/.+?": "(off|warn|error)"/)
})
// Turbopack intentionally does not support these events
;(process.env.IS_TURBOPACK_TEST ? it.skip : it)(
'emits telemery for usage of image, script & dynamic',
......@@ -275,7 +167,6 @@ describe('config telemetry', () => {
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 },
lint: true,
})
const featureUsageEvents = findAllTelemetryEvents(
stderr,
......
module.exports = {
eslint: {
ignoreDuringBuilds: true,
},
webpack(config) {
console.log('Initialized config')
if (
......
......@@ -232,12 +232,6 @@ export interface NextOptions {
stdout?: true | 'log'
ignoreFail?: boolean
/**
* If true, this enables the linting step in the build process. If false or
* undefined, it adds a `--no-lint` flag to the build command.
*/
lint?: boolean
onStdout?: (data: any) => void
onStderr?: (data: any) => void
}
......@@ -489,23 +483,9 @@ export function nextBuild(
args: string[] = [],
opts: NextOptions = {}
) {
// If the build hasn't requested it to be linted explicitly, disable linting
// if it's not already disabled.
if (!opts.lint && !args.includes('--no-lint')) {
args.push('--no-lint')
}
return runNextCommand(['build', dir, ...args], opts)
}
export function nextLint(
dir: string,
args: string[] = [],
opts: NextOptions = {}
) {
return runNextCommand(['lint', dir, ...args], opts)
}
export function nextTest(
dir: string,
args: string[] = [],
......
......@@ -23,9 +23,7 @@ describe('production - app dir - build output', () => {
const indexOfStartCompiling = output.indexOf(
'Creating an optimized production build'
)
const indexOfLinting = output.indexOf(
'Running ESLint and TypeScript concurrently'
)
const indexOfLinting = output.indexOf('Running TypeScript')
expect(indexOfVersion).toBeLessThan(indexOfLinting)
expect(indexOfStartCompiling).toBeLessThan(indexOfLinting)
})
......
import { createNext } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { renderViaHTTP } from 'next-test-utils'
describe('eslint plugin deps', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'pages/index.tsx': `export default function Page() {
return <p>hello world</p>;
}
`,
'.eslintrc': `
{
"parser": "@typescript-eslint/parser",
"plugins": ["react", "@typescript-eslint"],
"extends": [
"eslint:recommended",
"next/core-web-vitals",
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:import/typescript",
"plugin:import/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"prettier"
],
"env": {
"es2021": true,
"browser": true
},
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module",
"project": ["./tsconfig.json"],
"ecmaFeatures": { "jsx": true }
},
"settings": {
"react": { "version": "detect" },
"import/resolver": { "typescript": {} }
},
"rules": {
"no-else-return": "error",
"semi": ["error", "always"],
"no-useless-rename": "error",
"quotes": ["error", "double"],
"eol-last": ["error", "always"],
"no-console": [2, { "allow": ["warn", "error"] }],
"no-multiple-empty-lines": ["error", { "max": 1 }],
"no-unused-expressions": ["error", { "allowShortCircuit": true, "allowTernary": true, "enforceForJSX": true }],
"import/named": 0,
"import/order": [
"error",
{
"warnOnUnassignedImports": true,
"newlines-between": "always",
"groups": ["builtin", "external", "internal", "parent", ["sibling", "index"], "object", "type"]
}
],
"react/display-name": 0,
"react/prop-types": 0,
"react/react-in-jsx-scope": 0,
"react/self-closing-comp": ["error", { "component": true }],
"react-hooks/exhaustive-deps": ["warn", { "additionalHooks": "useIsomorphicLayoutEffect" }],
"@typescript-eslint/indent": 0,
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-var-requires": 0,
"@typescript-eslint/no-use-before-define": 0,
"@typescript-eslint/member-delimiter-style": 0,
"@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/explicit-member-accessibility": 0,
"@typescript-eslint/no-unused-vars": [2, { "argsIgnorePattern": "^_" }],
"@typescript-eslint/array-type": ["error", { "default": "array-simple" }],
"@typescript-eslint/no-unnecessary-boolean-literal-compare": [
"error",
{ "allowComparingNullableBooleansToTrue": false }
]
}
}
`,
'tsconfig.json': `{
"compilerOptions": {
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
// The rule @typescript-eslint/no-unnecessary-boolean-literal-compare requires the \`strictNullChecks\` compiler option to be turned on to function correctly.
"strictNullChecks": true,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"plugins": [
{
"name": "next"
}
]
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules",
]
}
`,
},
dependencies: {
// Manually installed @typescript-eslint/eslint-plugin, expect to be deduped
'@typescript-eslint/eslint-plugin': 'latest',
'@typescript-eslint/parser': 'latest',
'eslint-config-prettier': 'latest',
'eslint-plugin-import': 'latest',
'eslint-plugin-react': 'latest',
'@types/node': 'latest',
'@types/react': 'latest',
'@types/react-dom': 'latest',
// Use minimum peer dep version instead of v9 of eslint to avoid breaking changes
eslint: '8.56.0',
'eslint-config-next': 'latest',
typescript: 'latest',
},
packageJson: {
scripts: {
build: 'next build --no-lint && next lint',
},
},
buildCommand: 'pnpm build',
})
})
afterAll(() => next.destroy())
it('should work', async () => {
const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('hello world')
})
})
export default function Test() {
return (
<div>
<h1>Hello title</h1>
</div>
)
}
export default function Test() {
return (
<div>
<h1>Hello title</h1>
</div>
)
}
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Next Build production mode first time setup - ESLint v8 1`] = `
{
"env": {
"browser": true,
"node": true,
},
"globals": {},
"ignorePatterns": [],
"parserOptions": {
"allowImportExportEverywhere": true,
"babelOptions": {
"caller": {
"supportsTopLevelAwait": true,
},
"presets": [
"next/babel",
],
},
"ecmaFeatures": {
"jsx": true,
},
"requireConfigFile": false,
"sourceType": "module",
},
"plugins": [
"react-hooks",
"jsx-a11y",
"react",
"import",
"@next/next",
],
"rules": {
"@next/next/google-font-display": [
"warn",
],
"@next/next/google-font-preconnect": [
"warn",
],
"@next/next/inline-script-id": [
"error",
],
"@next/next/next-script-for-ga": [
"warn",
],
"@next/next/no-assign-module-variable": [
"error",
],
"@next/next/no-async-client-component": [
"warn",
],
"@next/next/no-before-interactive-script-outside-document": [
"warn",
],
"@next/next/no-css-tags": [
"warn",
],
"@next/next/no-document-import-in-page": [
"error",
],
"@next/next/no-duplicate-head": [
"error",
],
"@next/next/no-head-element": [
"warn",
],
"@next/next/no-head-import-in-document": [
"error",
],
"@next/next/no-html-link-for-pages": [
"error",
],
"@next/next/no-img-element": [
"warn",
],
"@next/next/no-page-custom-font": [
"warn",
],
"@next/next/no-script-component-in-head": [
"error",
],
"@next/next/no-styled-jsx-in-document": [
"warn",
],
"@next/next/no-sync-scripts": [
"error",
],
"@next/next/no-title-in-document-head": [
"warn",
],
"@next/next/no-typos": [
"warn",
],
"@next/next/no-unwanted-polyfillio": [
"warn",
],
"import/no-anonymous-default-export": [
"warn",
],
"jsx-a11y/alt-text": [
"warn",
{
"elements": [
"img",
],
"img": [
"Image",
],
},
],
"jsx-a11y/aria-props": [
"warn",
],
"jsx-a11y/aria-proptypes": [
"warn",
],
"jsx-a11y/aria-unsupported-elements": [
"warn",
],
"jsx-a11y/role-has-required-aria-props": [
"warn",
],
"jsx-a11y/role-supports-aria-props": [
"warn",
],
"react-hooks/exhaustive-deps": [
"warn",
],
"react-hooks/rules-of-hooks": [
"error",
],
"react/display-name": [
2,
],
"react/jsx-key": [
2,
],
"react/jsx-no-comment-textnodes": [
2,
],
"react/jsx-no-duplicate-props": [
2,
],
"react/jsx-no-undef": [
2,
],
"react/jsx-uses-react": [
2,
],
"react/jsx-uses-vars": [
2,
],
"react/no-children-prop": [
2,
],
"react/no-danger-with-children": [
2,
],
"react/no-deprecated": [
2,
],
"react/no-direct-mutation-state": [
2,
],
"react/no-find-dom-node": [
2,
],
"react/no-is-mounted": [
2,
],
"react/no-render-return-value": [
2,
],
"react/no-string-refs": [
2,
],
"react/no-unescaped-entities": [
2,
],
"react/require-render-return": [
2,
],
},
}
`;
exports[`Next Build production mode first time setup - ESLint v9 1`] = `
{
"env": {
"browser": true,
"node": true,
},
"globals": {},
"ignorePatterns": [],
"parserOptions": {
"allowImportExportEverywhere": true,
"babelOptions": {
"caller": {
"supportsTopLevelAwait": true,
},
"presets": [
"next/babel",
],
},
"ecmaFeatures": {
"jsx": true,
},
"requireConfigFile": false,
"sourceType": "module",
},
"plugins": [
"react-hooks",
"jsx-a11y",
"react",
"import",
"@next/next",
],
"rules": {
"@next/next/google-font-display": [
"warn",
],
"@next/next/google-font-preconnect": [
"warn",
],
"@next/next/inline-script-id": [
"error",
],
"@next/next/next-script-for-ga": [
"warn",
],
"@next/next/no-assign-module-variable": [
"error",
],
"@next/next/no-async-client-component": [
"warn",
],
"@next/next/no-before-interactive-script-outside-document": [
"warn",
],
"@next/next/no-css-tags": [
"warn",
],
"@next/next/no-document-import-in-page": [
"error",
],
"@next/next/no-duplicate-head": [
"error",
],
"@next/next/no-head-element": [
"warn",
],
"@next/next/no-head-import-in-document": [
"error",
],
"@next/next/no-html-link-for-pages": [
"error",
],
"@next/next/no-img-element": [
"warn",
],
"@next/next/no-page-custom-font": [
"warn",
],
"@next/next/no-script-component-in-head": [
"error",
],
"@next/next/no-styled-jsx-in-document": [
"warn",
],
"@next/next/no-sync-scripts": [
"error",
],
"@next/next/no-title-in-document-head": [
"warn",
],
"@next/next/no-typos": [
"warn",
],
"@next/next/no-unwanted-polyfillio": [
"warn",
],
"import/no-anonymous-default-export": [
"warn",
],
"jsx-a11y/alt-text": [
"warn",
{
"elements": [
"img",
],
"img": [
"Image",
],
},
],
"jsx-a11y/aria-props": [
"warn",
],
"jsx-a11y/aria-proptypes": [
"warn",
],
"jsx-a11y/aria-unsupported-elements": [
"warn",
],
"jsx-a11y/role-has-required-aria-props": [
"warn",
],
"jsx-a11y/role-supports-aria-props": [
"warn",
],
"react-hooks/exhaustive-deps": [
"warn",
],
"react-hooks/rules-of-hooks": [
"error",
],
"react/display-name": [
2,
],
"react/jsx-key": [
2,
],
"react/jsx-no-comment-textnodes": [
2,
],
"react/jsx-no-duplicate-props": [
2,
],
"react/jsx-no-undef": [
2,
],
"react/jsx-uses-react": [
2,
],
"react/jsx-uses-vars": [
2,
],
"react/no-children-prop": [
2,
],
"react/no-danger-with-children": [
2,
],
"react/no-deprecated": [
2,
],
"react/no-direct-mutation-state": [
2,
],
"react/no-find-dom-node": [
2,
],
"react/no-is-mounted": [
2,
],
"react/no-render-return-value": [
2,
],
"react/no-string-refs": [
2,
],
"react/no-unescaped-entities": [
2,
],
"react/require-render-return": [
2,
],
},
}
`;
exports[`Next Build production mode first time setup with TypeScript - ESLint v8 1`] = `
{
"env": {
"browser": true,
"node": true,
},
"globals": {},
"ignorePatterns": [],
"parserOptions": {
"allowImportExportEverywhere": true,
"babelOptions": {
"caller": {
"supportsTopLevelAwait": true,
},
"presets": [
"next/babel",
],
},
"ecmaFeatures": {
"jsx": true,
},
"requireConfigFile": false,
"sourceType": "module",
},
"plugins": [
"react-hooks",
"jsx-a11y",
"react",
"import",
"@next/next",
"@typescript-eslint",
],
"rules": {
"@next/next/google-font-display": [
"warn",
],
"@next/next/google-font-preconnect": [
"warn",
],
"@next/next/inline-script-id": [
"error",
],
"@next/next/next-script-for-ga": [
"warn",
],
"@next/next/no-assign-module-variable": [
"error",
],
"@next/next/no-async-client-component": [
"warn",
],
"@next/next/no-before-interactive-script-outside-document": [
"warn",
],
"@next/next/no-css-tags": [
"warn",
],
"@next/next/no-document-import-in-page": [
"error",
],
"@next/next/no-duplicate-head": [
"error",
],
"@next/next/no-head-element": [
"warn",
],
"@next/next/no-head-import-in-document": [
"error",
],
"@next/next/no-html-link-for-pages": [
"error",
],
"@next/next/no-img-element": [
"warn",
],
"@next/next/no-page-custom-font": [
"warn",
],
"@next/next/no-script-component-in-head": [
"error",
],
"@next/next/no-styled-jsx-in-document": [
"warn",
],
"@next/next/no-sync-scripts": [
"error",
],
"@next/next/no-title-in-document-head": [
"warn",
],
"@next/next/no-typos": [
"warn",
],
"@next/next/no-unwanted-polyfillio": [
"warn",
],
"@typescript-eslint/ban-ts-comment": [
"error",
],
"@typescript-eslint/no-array-constructor": [
"error",
],
"@typescript-eslint/no-duplicate-enum-values": [
"error",
],
"@typescript-eslint/no-empty-object-type": [
"error",
],
"@typescript-eslint/no-explicit-any": [
"error",
],
"@typescript-eslint/no-extra-non-null-assertion": [
"error",
],
"@typescript-eslint/no-misused-new": [
"error",
],
"@typescript-eslint/no-namespace": [
"error",
],
"@typescript-eslint/no-non-null-asserted-optional-chain": [
"error",
],
"@typescript-eslint/no-require-imports": [
"error",
],
"@typescript-eslint/no-this-alias": [
"error",
],
"@typescript-eslint/no-unnecessary-type-constraint": [
"error",
],
"@typescript-eslint/no-unsafe-declaration-merging": [
"error",
],
"@typescript-eslint/no-unsafe-function-type": [
"error",
],
"@typescript-eslint/no-unused-expressions": [
1,
],
"@typescript-eslint/no-unused-vars": [
1,
],
"@typescript-eslint/no-wrapper-object-types": [
"error",
],
"@typescript-eslint/prefer-as-const": [
"error",
],
"@typescript-eslint/prefer-namespace-keyword": [
"error",
],
"@typescript-eslint/triple-slash-reference": [
"error",
],
"import/no-anonymous-default-export": [
"warn",
],
"jsx-a11y/alt-text": [
"warn",
{
"elements": [
"img",
],
"img": [
"Image",
],
},
],
"jsx-a11y/aria-props": [
"warn",
],
"jsx-a11y/aria-proptypes": [
"warn",
],
"jsx-a11y/aria-unsupported-elements": [
"warn",
],
"jsx-a11y/role-has-required-aria-props": [
"warn",
],
"jsx-a11y/role-supports-aria-props": [
"warn",
],
"no-var": [
"error",
],
"prefer-const": [
"error",
],
"prefer-rest-params": [
"error",
],
"prefer-spread": [
"error",
],
"react-hooks/exhaustive-deps": [
"warn",
],
"react-hooks/rules-of-hooks": [
"error",
],
"react/display-name": [
2,
],
"react/jsx-key": [
2,
],
"react/jsx-no-comment-textnodes": [
2,
],
"react/jsx-no-duplicate-props": [
2,
],
"react/jsx-no-undef": [
2,
],
"react/jsx-uses-react": [
2,
],
"react/jsx-uses-vars": [
2,
],
"react/no-children-prop": [
2,
],
"react/no-danger-with-children": [
2,
],
"react/no-deprecated": [
2,
],
"react/no-direct-mutation-state": [
2,
],
"react/no-find-dom-node": [
2,
],
"react/no-is-mounted": [
2,
],
"react/no-render-return-value": [
2,
],
"react/no-string-refs": [
2,
],
"react/no-unescaped-entities": [
2,
],
"react/require-render-return": [
2,
],
},
}
`;
exports[`Next Build production mode first time setup with TypeScript - ESLint v9 1`] = `
{
"env": {
"browser": true,
"node": true,
},
"globals": {},
"ignorePatterns": [],
"parserOptions": {
"allowImportExportEverywhere": true,
"babelOptions": {
"caller": {
"supportsTopLevelAwait": true,
},
"presets": [
"next/babel",
],
},
"ecmaFeatures": {
"jsx": true,
},
"requireConfigFile": false,
"sourceType": "module",
},
"plugins": [
"react-hooks",
"jsx-a11y",
"react",
"import",
"@next/next",
"@typescript-eslint",
],
"rules": {
"@next/next/google-font-display": [
"warn",
],
"@next/next/google-font-preconnect": [
"warn",
],
"@next/next/inline-script-id": [
"error",
],
"@next/next/next-script-for-ga": [
"warn",
],
"@next/next/no-assign-module-variable": [
"error",
],
"@next/next/no-async-client-component": [
"warn",
],
"@next/next/no-before-interactive-script-outside-document": [
"warn",
],
"@next/next/no-css-tags": [
"warn",
],
"@next/next/no-document-import-in-page": [
"error",
],
"@next/next/no-duplicate-head": [
"error",
],
"@next/next/no-head-element": [
"warn",
],
"@next/next/no-head-import-in-document": [
"error",
],
"@next/next/no-html-link-for-pages": [
"error",
],
"@next/next/no-img-element": [
"warn",
],
"@next/next/no-page-custom-font": [
"warn",
],
"@next/next/no-script-component-in-head": [
"error",
],
"@next/next/no-styled-jsx-in-document": [
"warn",
],
"@next/next/no-sync-scripts": [
"error",
],
"@next/next/no-title-in-document-head": [
"warn",
],
"@next/next/no-typos": [
"warn",
],
"@next/next/no-unwanted-polyfillio": [
"warn",
],
"@typescript-eslint/ban-ts-comment": [
"error",
],
"@typescript-eslint/no-array-constructor": [
"error",
],
"@typescript-eslint/no-duplicate-enum-values": [
"error",
],
"@typescript-eslint/no-empty-object-type": [
"error",
],
"@typescript-eslint/no-explicit-any": [
"error",
],
"@typescript-eslint/no-extra-non-null-assertion": [
"error",
],
"@typescript-eslint/no-misused-new": [
"error",
],
"@typescript-eslint/no-namespace": [
"error",
],
"@typescript-eslint/no-non-null-asserted-optional-chain": [
"error",
],
"@typescript-eslint/no-require-imports": [
"error",
],
"@typescript-eslint/no-this-alias": [
"error",
],
"@typescript-eslint/no-unnecessary-type-constraint": [
"error",
],
"@typescript-eslint/no-unsafe-declaration-merging": [
"error",
],
"@typescript-eslint/no-unsafe-function-type": [
"error",
],
"@typescript-eslint/no-unused-expressions": [
1,
],
"@typescript-eslint/no-unused-vars": [
1,
],
"@typescript-eslint/no-wrapper-object-types": [
"error",
],
"@typescript-eslint/prefer-as-const": [
"error",
],
"@typescript-eslint/prefer-namespace-keyword": [
"error",
],
"@typescript-eslint/triple-slash-reference": [
"error",
],
"import/no-anonymous-default-export": [
"warn",
],
"jsx-a11y/alt-text": [
"warn",
{
"elements": [
"img",
],
"img": [
"Image",
],
},
],
"jsx-a11y/aria-props": [
"warn",
],
"jsx-a11y/aria-proptypes": [
"warn",
],
"jsx-a11y/aria-unsupported-elements": [
"warn",
],
"jsx-a11y/role-has-required-aria-props": [
"warn",
],
"jsx-a11y/role-supports-aria-props": [
"warn",
],
"no-var": [
"error",
],
"prefer-const": [
"error",
],
"prefer-rest-params": [
"error",
],
"prefer-spread": [
"error",
],
"react-hooks/exhaustive-deps": [
"warn",
],
"react-hooks/rules-of-hooks": [
"error",
],
"react/display-name": [
2,
],
"react/jsx-key": [
2,
],
"react/jsx-no-comment-textnodes": [
2,
],
"react/jsx-no-duplicate-props": [
2,
],
"react/jsx-no-undef": [
2,
],
"react/jsx-uses-react": [
2,
],
"react/jsx-uses-vars": [
2,
],
"react/no-children-prop": [
2,
],
"react/no-danger-with-children": [
2,
],
"react/no-deprecated": [
2,
],
"react/no-direct-mutation-state": [
2,
],
"react/no-find-dom-node": [
2,
],
"react/no-is-mounted": [
2,
],
"react/no-render-return-value": [
2,
],
"react/no-string-refs": [
2,
],
"react/no-unescaped-entities": [
2,
],
"react/require-render-return": [
2,
],
},
}
`;
import fs from 'fs-extra'
import { join } from 'path'
import { execSync } from 'child_process'
import { FileRef, createNext } from 'e2e-utils'
const dirFirstTimeSetup = join(__dirname, '../first-time-setup')
const dirFirstTimeSetupTS = join(__dirname, '../first-time-setup-ts')
describe('Next Build', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
test('first time setup - ESLint v8', async () => {
const next = await createNext({
files: new FileRef(dirFirstTimeSetup),
dependencies: {
// create-next-install will replace this with a version built from the local source
'eslint-config-next': 'canary',
eslint: '^8',
},
skipStart: true,
})
try {
const eslintrcJsonPath = join(next.testDir, '.eslintrc.json')
await fs.writeFile(eslintrcJsonPath, '')
const nextBuildCommand = await next.build()
const buildOutput = nextBuildCommand.cliOutput
expect(buildOutput).toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
// TODO: Should we exit non-zero here if the config was created? Should we maybe even directly start linting?
expect(() => {
execSync(`pnpm next lint --strict`, {
cwd: next.testDir,
encoding: 'utf8',
stdio: 'inherit',
})
}).toThrow('Command failed: pnpm next lint --strict')
const eslintConfigAfterSetupJSON = execSync(
`pnpm eslint --print-config pages/index.js`,
{
cwd: next.testDir,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'inherit'],
}
)
const { parser, settings, ...eslintConfigAfterSetup } = JSON.parse(
eslintConfigAfterSetupJSON
)
expect(
getEslintConfigSnapshot(eslintConfigAfterSetup)
).toMatchSnapshot()
expect({
parser,
settings,
}).toEqual({
// parser: require.resolve('eslint-config-next')
parser: expect.stringContaining('eslint-config-next'),
settings: {
'import/parsers': expect.any(Object),
'import/resolver': expect.any(Object),
react: {
version: 'detect',
},
},
})
expect(Object.entries(settings['import/parsers'])).toEqual([
[
// require.resolve('@typescript-eslint/parser')
expect.stringContaining('@typescript-eslint/parser'),
['.ts', '.mts', '.cts', '.tsx', '.d.ts'],
],
])
expect(Object.entries(settings['import/resolver'])).toEqual([
[
// require.resolve('eslint-import-resolver-node')
expect.stringContaining('eslint-import-resolver-node'),
{ extensions: ['.js', '.jsx', '.ts', '.tsx'] },
],
[
// require.resolve('eslint-import-resolver-typescript')
expect.stringContaining('eslint-import-resolver-typescript'),
{ alwaysTryTypes: true },
],
])
} finally {
await next.destroy()
}
})
test('first time setup - ESLint v9', async () => {
const next = await createNext({
files: new FileRef(dirFirstTimeSetup),
dependencies: {
// create-next-install will replace this with a version built from the local source
'eslint-config-next': 'canary',
eslint: '^9',
},
skipStart: true,
})
try {
const eslintrcJsonPath = join(next.testDir, '.eslintrc.json')
await fs.writeFile(eslintrcJsonPath, '')
const nextBuildCommand = await next.build()
const buildOutput = nextBuildCommand.cliOutput
expect(buildOutput).toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
// TODO: Should we exit non-zero here if the config was created? Should we maybe even directly start linting?
expect(() => {
execSync(`pnpm next lint --strict`, {
cwd: next.testDir,
encoding: 'utf8',
stdio: 'inherit',
})
}).toThrow('Command failed: pnpm next lint --strict')
const eslintConfigAfterSetupJSON = execSync(
// TODO(jiwon): remove `ESLINT_USE_FLAT_CONFIG=false` when we create the config for ESLint 9.
// https://eslint.org/docs/latest/use/migrate-to-9.0.0#-new-default-config-format-eslintconfigjs
`ESLINT_USE_FLAT_CONFIG=false pnpm eslint --print-config pages/index.js`,
{
cwd: next.testDir,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'inherit'],
}
)
const { parser, settings, ...eslintConfigAfterSetup } = JSON.parse(
eslintConfigAfterSetupJSON
)
expect(
getEslintConfigSnapshot(eslintConfigAfterSetup)
).toMatchSnapshot()
expect({
parser,
settings,
}).toEqual({
// parser: require.resolve('eslint-config-next')
parser: expect.stringContaining('eslint-config-next'),
settings: {
'import/parsers': expect.any(Object),
'import/resolver': expect.any(Object),
react: {
version: 'detect',
},
},
})
expect(Object.entries(settings['import/parsers'])).toEqual([
[
// require.resolve('@typescript-eslint/parser')
expect.stringContaining('@typescript-eslint/parser'),
['.ts', '.mts', '.cts', '.tsx', '.d.ts'],
],
])
expect(Object.entries(settings['import/resolver'])).toEqual([
[
// require.resolve('eslint-import-resolver-node')
expect.stringContaining('eslint-import-resolver-node'),
{ extensions: ['.js', '.jsx', '.ts', '.tsx'] },
],
[
// require.resolve('eslint-import-resolver-typescript')
expect.stringContaining('eslint-import-resolver-typescript'),
{ alwaysTryTypes: true },
],
])
} finally {
await next.destroy()
}
})
test('first time setup with TypeScript - ESLint v8', async () => {
const next = await createNext({
files: new FileRef(dirFirstTimeSetupTS),
dependencies: {
// create-next-install will replace this with a version built from the local source
'eslint-config-next': 'canary',
eslint: '^8',
},
skipStart: true,
})
try {
const eslintrcJsonPath = join(next.testDir, '.eslintrc.json')
await fs.writeFile(eslintrcJsonPath, '')
const nextBuildCommand = await next.build()
const buildOutput = nextBuildCommand.cliOutput
expect(buildOutput).toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
// TODO: Should we exit non-zero here if the config was created? Should we maybe even directly start linting?
expect(() => {
execSync(`pnpm next lint --strict`, {
cwd: next.testDir,
encoding: 'utf8',
stdio: 'inherit',
})
}).toThrow('Command failed: pnpm next lint --strict')
const eslintConfigAfterSetupJSON = execSync(
`pnpm eslint --print-config pages/index.tsx`,
{
cwd: next.testDir,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'inherit'],
}
)
const { parser, settings, ...eslintConfigAfterSetup } = JSON.parse(
eslintConfigAfterSetupJSON
)
expect(
getEslintConfigSnapshot(eslintConfigAfterSetup)
).toMatchSnapshot()
expect({
parser,
settings,
}).toEqual({
// parser: require.resolve('@typescript-eslint/parser')
parser: expect.stringContaining('@typescript-eslint/parser'),
settings: {
'import/parsers': expect.any(Object),
'import/resolver': expect.any(Object),
react: {
version: 'detect',
},
},
})
expect(Object.entries(settings['import/parsers'])).toEqual([
[
// require.resolve('@typescript-eslint/parser')
expect.stringContaining('@typescript-eslint/parser'),
['.ts', '.mts', '.cts', '.tsx', '.d.ts'],
],
])
expect(Object.entries(settings['import/resolver'])).toEqual([
[
// require.resolve('eslint-import-resolver-node')
expect.stringContaining('eslint-import-resolver-node'),
{ extensions: ['.js', '.jsx', '.ts', '.tsx'] },
],
[
// require.resolve('eslint-import-resolver-typescript')
expect.stringContaining('eslint-import-resolver-typescript'),
{ alwaysTryTypes: true },
],
])
} finally {
await next.destroy()
}
})
test('first time setup with TypeScript - ESLint v9', async () => {
const next = await createNext({
files: new FileRef(dirFirstTimeSetupTS),
dependencies: {
// create-next-install will replace this with a version built from the local source
'eslint-config-next': 'canary',
eslint: '^9',
},
skipStart: true,
})
try {
const eslintrcJsonPath = join(next.testDir, '.eslintrc.json')
await fs.writeFile(eslintrcJsonPath, '')
const nextBuildCommand = await next.build()
const buildOutput = nextBuildCommand.cliOutput
expect(buildOutput).toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
// TODO: Should we exit non-zero here if the config was created? Should we maybe even directly start linting?
expect(() => {
execSync(`pnpm next lint --strict`, {
cwd: next.testDir,
encoding: 'utf8',
stdio: 'inherit',
})
}).toThrow('Command failed: pnpm next lint --strict')
const eslintConfigAfterSetupJSON = execSync(
// TODO(jiwon): remove `ESLINT_USE_FLAT_CONFIG=false` when we create the config for ESLint 9.
// https://eslint.org/docs/latest/use/migrate-to-9.0.0#-new-default-config-format-eslintconfigjs
`ESLINT_USE_FLAT_CONFIG=false pnpm eslint --print-config pages/index.tsx`,
{
cwd: next.testDir,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'inherit'],
}
)
const { parser, settings, ...eslintConfigAfterSetup } = JSON.parse(
eslintConfigAfterSetupJSON
)
expect(
getEslintConfigSnapshot(eslintConfigAfterSetup)
).toMatchSnapshot()
expect({
parser,
settings,
}).toEqual({
// parser: require.resolve('@typescript-eslint/parser')
parser: expect.stringContaining('@typescript-eslint/parser'),
settings: {
'import/parsers': expect.any(Object),
'import/resolver': expect.any(Object),
react: {
version: 'detect',
},
},
})
expect(Object.entries(settings['import/parsers'])).toEqual([
[
// require.resolve('@typescript-eslint/parser')
expect.stringContaining('@typescript-eslint/parser'),
['.ts', '.mts', '.cts', '.tsx', '.d.ts'],
],
])
expect(Object.entries(settings['import/resolver'])).toEqual([
[
// require.resolve('eslint-import-resolver-node')
expect.stringContaining('eslint-import-resolver-node'),
{ extensions: ['.js', '.jsx', '.ts', '.tsx'] },
],
[
// require.resolve('eslint-import-resolver-typescript')
expect.stringContaining('eslint-import-resolver-typescript'),
{ alwaysTryTypes: true },
],
])
} finally {
await next.destroy()
}
})
}
)
})
/**
* Rules being turned off (i.e. remove from snapshot) would be breaking change (requires removal of eslint-disable directive)
* Rules being added that are turned off would not be a breaking change (no eslint-disable directive required)
* Rules being added with a severity would be a breaking change (requires addition of eslint-disable directive)
*/
function getEslintConfigSnapshot(eslintConfig: any) {
return {
...eslintConfig,
rules: Object.fromEntries(
Object.entries(eslintConfig.rules).filter(
([, config]: [ruleName: string, config: [severity: unknown]]) => {
const [severity] = config
return severity !== 0 && severity !== 'off'
}
)
),
}
}
......@@ -43,9 +43,6 @@ describe('required server files app router', () => {
nextConfig: {
cacheHandler: './cache-handler.js',
cacheMaxMemorySize: 0,
eslint: {
ignoreDuringBuilds: true,
},
output: 'standalone',
},
})
......
......@@ -62,9 +62,6 @@ describe('required server files i18n', () => {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
eslint: {
ignoreDuringBuilds: true,
},
output: 'standalone',
async rewrites() {
return [
......
......@@ -59,9 +59,6 @@ describe('required server files app router', () => {
clientSegmentCache: true,
clientParamParsing: true,
},
eslint: {
ignoreDuringBuilds: true,
},
output: 'standalone',
},
})
......
......@@ -53,9 +53,6 @@ describe('required server files', () => {
nextConfig: {
cacheHandler: './cache-handler.js',
cacheMaxMemorySize: 0,
eslint: {
ignoreDuringBuilds: true,
},
output: 'standalone',
async rewrites() {
return {
......
......@@ -6,7 +6,4 @@ module.exports = createNodeFileTrace({
path: join(__dirname, '..', '..', '..', '..', 'target', 'debug'),
})({
reactStrictMode: true,
eslint: {
ignoreDuringBuilds: true,
},
})
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