Commit 0c092d11 authored by Ben Gubler's avatar Ben Gubler

feat [Next 16]: remove 'next lint' command

parent 0a90014c
......@@ -26,15 +26,14 @@ The following options are available:
The following commands are available:
| Command | Description |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`dev`](#next-dev-options) | Starts Next.js in development mode with Hot Module Reloading, error reporting, and more. |
| [`build`](#next-build-options) | Creates an optimized production build of your application. Displaying information about each route. |
| [`start`](#next-start-options) | Starts Next.js in production mode. The application should be compiled with `next build` first. |
| [`info`](#next-info-options) | Prints relevant details about the current system which can be used to report Next.js bugs. |
| [`lint`](#next-lint-options) | 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 it is not already configured in your application. |
| [`telemetry`](#next-telemetry-options) | Allows you to enable or disable Next.js' completely anonymous telemetry collection. |
| [`typegen`](#next-typegen-options) | Generates TypeScript definitions for routes, pages, layouts, and route handlers without running a full build. |
| Command | Description |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| [`dev`](#next-dev-options) | Starts Next.js in development mode with Hot Module Reloading, error reporting, and more. |
| [`build`](#next-build-options) | Creates an optimized production build of your application. Displaying information about each route. |
| [`start`](#next-start-options) | Starts Next.js in production mode. The application should be compiled with `next build` first. |
| [`info`](#next-info-options) | Prints relevant details about the current system which can be used to report Next.js bugs. |
| [`telemetry`](#next-telemetry-options) | Allows you to enable or disable Next.js' completely anonymous telemetry collection. |
| [`typegen`](#next-typegen-options) | Generates TypeScript definitions for routes, pages, layouts, and route handlers without running a full build. |
> **Good to know**: Running `next` without a command is an alias for `next dev`.
......
......@@ -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'
......@@ -237,94 +236,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(
......
#!/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 = await 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)
}
}
}
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