Unverified Commit 300bfe52 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

[BREAKING] Support ESLint v9 in plugin, config and `next lint` (#71218)

> [!WARNING]
> **Breaking Change:** Now uses `eslint-plugin-react-hooks@5.0.0` which
has a new violation disallowing Component names starting with anything
but an uppercase letter. See
https://github.com/facebook/react/releases/tag/eslint-plugin-react-hooks%405.0.0
for more details.

Adds support of ESLint v9 to `eslint-plugin-next`, `eslint-config-next`
and `next lint`.

Does not require using the new flat config format. `next lint` will
automatically ensure the old config format can be used.

### Why?

As `eslint-plugin-react-hooks` has been updated for ESLint v9 support
and is a helpful package for Next v15 upgrade, unblock the restrictions
to upgrade to ESLint v9.

Also, ESLint v8 is [End of
Life](https://eslint.org/blog/2024/09/eslint-v8-eol-version-support/#:~:text=ESLint%20v8.-,x%20end%20of%20life%20is%20October%205%2C%202024,x%20on%20October%205%2C%202024.)
support since Oct 5th, so is good to unblock v9 now.

Plugins bumped:
- [x]
[@rushstack/eslint-patch](https://github.com/microsoft/rushstack/pull/4719)
([v1.10.3](https://www.npmjs.com/package/@rushstack/eslint-patch/v/1.10.3?activeTab=versions)
no release post, confirmed on NPM)
- [x]
[@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/pull/9002)
([v8.0.0](https://github.com/typescript-eslint/typescript-eslint/pull/9002#issuecomment-2106424400))
- [x]
[eslint-plugin-import](https://github.com/import-js/eslint-plugin-import/pull/2996)
([v2.31.0](https://github.com/import-js/eslint-plugin-import/releases/tag/v2.31.0))
- [x]
[eslint-plugin-jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/pull/1009)
([v6.10.0](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/releases/tag/v6.10.0))
- [x]
[eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react/pull/3759)
([v7.35.0](https://github.com/jsx-eslint/eslint-plugin-react/releases/tag/v7.35.0))
- [x]
[eslint-plugin-react-hooks](https://github.com/facebook/react/pull/28773)
([v5.0.0](https://github.com/facebook/react/releases/tag/eslint-plugin-react-hooks%405.0.0))

We have to switch to ESLint v9 in our repo due to a pnpm bug where it
automatically uses ESLint v9 even though we only installed it via
`eslint-v9: npm:eslint@9.0.0`. This is a pnpm bug that wouldn't happen
with Yarn v1, v4 nor NPM.

Closes https://github.com/vercel/next.js/issues/64409
Closes https://github.com/vercel/next.js/issues/64114
Closes https://github.com/vercel/next.js/issues/64453

Closes NEXT-3293

---------
Co-authored-by: 's avatarSebastian "Sebbie" Silbermann <sebastian.silbermann@vercel.com>
parent 863168d4
...@@ -45,6 +45,7 @@ packages/next-swc/docs/assets/**/* ...@@ -45,6 +45,7 @@ packages/next-swc/docs/assets/**/*
test/lib/amp-validator-wasm.js test/lib/amp-validator-wasm.js
test/production/pages-dir/production/fixture/amp-validator-wasm.js test/production/pages-dir/production/fixture/amp-validator-wasm.js
test/e2e/async-modules/amp-validator-wasm.js test/e2e/async-modules/amp-validator-wasm.js
test/development/next-lint-eslint-formatter-compact/**/*.js
# turbopack crates # turbopack crates
turbopack/crates/*/tests/** turbopack/crates/*/tests/**
......
...@@ -66,7 +66,10 @@ ...@@ -66,7 +66,10 @@
"@typescript-eslint/array-type": "off", "@typescript-eslint/array-type": "off",
"@typescript-eslint/ban-ts-comment": "off", "@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/ban-tslint-comment": "off", "@typescript-eslint/ban-tslint-comment": "off",
"@typescript-eslint/ban-types": "off", "@typescript-eslint/no-empty-object-type": "off",
"@typescript-eslint/no-restricted-types": "off",
"@typescript-eslint/no-unsafe-function-type": "off",
"@typescript-eslint/no-wrapper-object-types": "off",
"@typescript-eslint/class-literal-property-style": "off", "@typescript-eslint/class-literal-property-style": "off",
"@typescript-eslint/consistent-generic-constructors": "off", "@typescript-eslint/consistent-generic-constructors": "off",
"@typescript-eslint/consistent-indexed-object-style": "off", "@typescript-eslint/consistent-indexed-object-style": "off",
...@@ -77,6 +80,7 @@ ...@@ -77,6 +80,7 @@
"@typescript-eslint/no-empty-interface": "off", "@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-inferrable-types": "off", "@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-require-imports": "off",
"@typescript-eslint/no-var-requires": "off", "@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/prefer-for-of": "off", "@typescript-eslint/prefer-for-of": "off",
"@typescript-eslint/prefer-function-type": "off", "@typescript-eslint/prefer-function-type": "off",
...@@ -104,6 +108,7 @@ ...@@ -104,6 +108,7 @@
"args": "none", "args": "none",
"ignoreRestSiblings": true, "ignoreRestSiblings": true,
"argsIgnorePattern": "^_", "argsIgnorePattern": "^_",
"caughtErrors": "none",
"caughtErrorsIgnorePattern": "^_", "caughtErrorsIgnorePattern": "^_",
"destructuredArrayIgnorePattern": "^_", "destructuredArrayIgnorePattern": "^_",
"varsIgnorePattern": "^_" "varsIgnorePattern": "^_"
...@@ -178,6 +183,7 @@ ...@@ -178,6 +183,7 @@
{ {
"args": "all", "args": "all",
"argsIgnorePattern": "^_", "argsIgnorePattern": "^_",
"caughtErrors": "none",
"ignoreRestSiblings": true "ignoreRestSiblings": true
} }
] ]
...@@ -308,6 +314,7 @@ ...@@ -308,6 +314,7 @@
"error", "error",
{ {
"args": "none", "args": "none",
"caughtErrors": "none",
"ignoreRestSiblings": true "ignoreRestSiblings": true
} }
], ],
......
...@@ -5,7 +5,7 @@ dist ...@@ -5,7 +5,7 @@ dist
target target
packages/next/wasm/@next packages/next/wasm/@next
tarballs/ tarballs/
packages/next/*.tgz packages/**/*.tgz
# dependencies # dependencies
node_modules node_modules
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
"typescript", "typescript",
"typescriptreact" "typescriptreact"
], ],
"eslint.useFlatConfig": false,
// Set Jest runMode to on-demand as otherwise it will start running all tests the first time. // Set Jest runMode to on-demand as otherwise it will start running all tests the first time.
// Equivalent to deprecated option "jest.autoRun": "off" // Equivalent to deprecated option "jest.autoRun": "off"
"jest.runMode": "on-demand", "jest.runMode": "on-demand",
......
...@@ -2,7 +2,7 @@ import ThirdPartyReact from "supertokens-auth-react/recipe/thirdparty"; ...@@ -2,7 +2,7 @@ import ThirdPartyReact from "supertokens-auth-react/recipe/thirdparty";
import EmailPasswordReact from "supertokens-auth-react/recipe/emailpassword"; import EmailPasswordReact from "supertokens-auth-react/recipe/emailpassword";
import Session from "supertokens-auth-react/recipe/session"; import Session from "supertokens-auth-react/recipe/session";
import { appInfo } from "./appInfo"; import { appInfo } from "./appInfo";
import { useRouter } from "next/navigation"; import { type useRouter } from "next/navigation";
import { SuperTokensConfig } from "supertokens-auth-react/lib/build/types"; import { SuperTokensConfig } from "supertokens-auth-react/lib/build/types";
import { ThirdPartyPreBuiltUI } from "supertokens-auth-react/recipe/thirdparty/prebuiltui"; import { ThirdPartyPreBuiltUI } from "supertokens-auth-react/recipe/thirdparty/prebuiltui";
import { EmailPasswordPreBuiltUI } from "supertokens-auth-react/recipe/emailpassword/prebuiltui"; import { EmailPasswordPreBuiltUI } from "supertokens-auth-react/recipe/emailpassword/prebuiltui";
......
module.exports = { module.exports = {
'*.{js,jsx,mjs,ts,tsx,mts}': [ '*.{js,jsx,mjs,ts,tsx,mts}': [
'prettier --with-node-modules --ignore-path .prettierignore --write', 'prettier --with-node-modules --ignore-path .prettierignore --write',
'eslint --fix', 'cross-env ESLINT_USE_FLAT_CONFIG=false eslint --config .eslintrc.json --fix',
], ],
'*.{json,md,mdx,css,html,yml,yaml,scss}': [ '*.{json,md,mdx,css,html,yml,yaml,scss}': [
'prettier --with-node-modules --ignore-path .prettierignore --write', 'prettier --with-node-modules --ignore-path .prettierignore --write',
......
...@@ -34,7 +34,7 @@ ...@@ -34,7 +34,7 @@
"git-clean": "git clean -d -x -e node_modules -e packages -f", "git-clean": "git clean -d -x -e node_modules -e packages -f",
"typescript": "tsc --noEmit", "typescript": "tsc --noEmit",
"lint-typescript": "turbo run typescript", "lint-typescript": "turbo run typescript",
"lint-eslint": "eslint . --ext js,jsx,ts,tsx --config .eslintrc.cli.json --no-eslintrc", "lint-eslint": "cross-env ESLINT_USE_FLAT_CONFIG=false eslint . --ext js,jsx,ts,tsx --config .eslintrc.cli.json --no-eslintrc",
"lint-ast-grep": "ast-grep scan", "lint-ast-grep": "ast-grep scan",
"lint-no-typescript": "run-p prettier-check lint-eslint lint-language", "lint-no-typescript": "run-p prettier-check lint-eslint lint-language",
"types-and-precompiled": "run-p lint-typescript check-precompiled validate-externals-doc", "types-and-precompiled": "run-p lint-typescript check-precompiled validate-externals-doc",
...@@ -121,8 +121,8 @@ ...@@ -121,8 +121,8 @@
"@types/relay-runtime": "14.1.13", "@types/relay-runtime": "14.1.13",
"@types/string-hash": "1.1.1", "@types/string-hash": "1.1.1",
"@types/trusted-types": "2.0.3", "@types/trusted-types": "2.0.3",
"@typescript-eslint/eslint-plugin": "7.16.0", "@typescript-eslint/eslint-plugin": "8.0.0",
"@typescript-eslint/parser": "7.16.0", "@typescript-eslint/parser": "8.0.0",
"@vercel/devlow-bench": "workspace:*", "@vercel/devlow-bench": "workspace:*",
"@vercel/fetch": "6.1.1", "@vercel/fetch": "6.1.1",
"@vercel/og": "0.6.3", "@vercel/og": "0.6.3",
...@@ -144,15 +144,16 @@ ...@@ -144,15 +144,16 @@
"dd-trace": "4.12.0", "dd-trace": "4.12.0",
"es5-ext": "0.10.53", "es5-ext": "0.10.53",
"escape-string-regexp": "2.0.0", "escape-string-regexp": "2.0.0",
"eslint": "8.56.0", "eslint": "9.12.0",
"eslint-config-next": "workspace:*", "eslint-config-next": "workspace:*",
"eslint-formatter-codeframe": "7.32.1", "eslint-formatter-codeframe": "7.32.1",
"eslint-plugin-eslint-plugin": "5.2.1", "eslint-plugin-eslint-plugin": "5.2.1",
"eslint-plugin-import": "2.29.1", "eslint-plugin-import": "2.31.0",
"eslint-plugin-jest": "27.6.3", "eslint-plugin-jest": "27.6.3",
"eslint-plugin-jsdoc": "48.0.4", "eslint-plugin-jsdoc": "48.0.4",
"eslint-plugin-react": "7.33.2", "eslint-plugin-react": "7.35.0",
"eslint-plugin-react-hooks": "4.6.0", "eslint-plugin-react-hooks": "5.0.0",
"eslint-v8": "npm:eslint@^8.57.0",
"event-stream": "4.0.1", "event-stream": "4.0.1",
"execa": "2.0.3", "execa": "2.0.3",
"expect-type": "0.14.2", "expect-type": "0.14.2",
......
...@@ -11,18 +11,18 @@ ...@@ -11,18 +11,18 @@
"homepage": "https://nextjs.org/docs/app/building-your-application/configuring/eslint#eslint-config", "homepage": "https://nextjs.org/docs/app/building-your-application/configuring/eslint#eslint-config",
"dependencies": { "dependencies": {
"@next/eslint-plugin-next": "15.0.0-canary.190", "@next/eslint-plugin-next": "15.0.0-canary.190",
"@rushstack/eslint-patch": "^1.3.3", "@rushstack/eslint-patch": "^1.10.3",
"@typescript-eslint/eslint-plugin": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0", "@typescript-eslint/eslint-plugin": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0",
"@typescript-eslint/parser": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0", "@typescript-eslint/parser": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0",
"eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2", "eslint-import-resolver-typescript": "^3.5.2",
"eslint-plugin-import": "^2.28.1", "eslint-plugin-import": "^2.31.0",
"eslint-plugin-jsx-a11y": "^6.7.1", "eslint-plugin-jsx-a11y": "^6.10.0",
"eslint-plugin-react": "^7.33.2", "eslint-plugin-react": "^7.35.0",
"eslint-plugin-react-hooks": "^4.5.0 || 5.0.0-canary-7118f5dd7-20230705" "eslint-plugin-react-hooks": "^5.0.0"
}, },
"peerDependencies": { "peerDependencies": {
"eslint": "^7.23.0 || ^8.0.0", "eslint": "^7.23.0 || ^8.0.0 || ^9.0.0",
"typescript": ">=3.3.1" "typescript": ">=3.3.1"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
......
...@@ -23,21 +23,23 @@ export type NextLintOptions = { ...@@ -23,21 +23,23 @@ export type NextLintOptions = {
config?: string config?: string
dir?: string[] dir?: string[]
errorOnUnmatchedPattern?: boolean errorOnUnmatchedPattern?: boolean
ext: string[]
file?: string[] file?: string[]
fix?: boolean fix?: boolean
fixType?: string fixType?: string
format?: string format?: string
ignore: boolean ignore: boolean
ignorePath?: string
inlineConfig: boolean
maxWarnings: number
outputFile?: string outputFile?: string
quiet?: boolean 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' reportUnusedDisableDirectivesSeverity: 'error' | 'off' | 'warn'
resolvePluginsRelativeTo?: string resolvePluginsRelativeTo?: string
rulesdir?: string rulesdir?: string
strict?: boolean inlineConfig: boolean
maxWarnings: number
} }
const eslintOptions = ( const eslintOptions = (
......
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
...@@ -77,6 +77,7 @@ export async function applyNextFixture( ...@@ -77,6 +77,7 @@ export async function applyNextFixture(
const fixture = new NextFixtureImpl(testInfo, nextOptions, nextWorker, page) const fixture = new NextFixtureImpl(testInfo, nextOptions, nextWorker, page)
await fixture.setup() await fixture.setup()
// eslint-disable-next-line react-hooks/rules-of-hooks -- not React.use()
await use(fixture) await use(fixture)
fixture.teardown() fixture.teardown()
......
...@@ -54,6 +54,7 @@ export async function applyNextWorkerFixture( ...@@ -54,6 +54,7 @@ export async function applyNextWorkerFixture(
): Promise<void> { ): Promise<void> {
const fixture = new NextWorkerFixtureImpl() const fixture = new NextWorkerFixtureImpl()
await fixture.setup() await fixture.setup()
// eslint-disable-next-line react-hooks/rules-of-hooks -- not React.use()
await use(fixture) await use(fixture)
fixture.teardown() fixture.teardown()
} }
...@@ -135,7 +135,25 @@ async function lint( ...@@ -135,7 +135,25 @@ async function lint(
const mod = await Promise.resolve(require(deps.resolved.get('eslint')!)) const mod = await Promise.resolve(require(deps.resolved.get('eslint')!))
const { ESLint } = mod const useFlatConfig =
// If V9 config was found, use flat config, or else use legacy.
eslintrcFile?.startsWith('eslint.config.')
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 let eslintVersion = ESLint?.version ?? mod.CLIEngine?.version
if (!eslintVersion || semver.lt(eslintVersion, '7.0.0')) { if (!eslintVersion || semver.lt(eslintVersion, '7.0.0')) {
...@@ -155,6 +173,23 @@ async function lint( ...@@ -155,6 +173,23 @@ async function lint(
...eslintOptions, ...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 eslint = new ESLint(options)
let nextEslintPluginIsEnabled = false let nextEslintPluginIsEnabled = false
...@@ -163,10 +198,20 @@ async function lint( ...@@ -163,10 +198,20 @@ async function lint(
for (const configFile of [eslintrcFile, pkgJsonPath]) { for (const configFile of [eslintrcFile, pkgJsonPath]) {
if (!configFile) continue if (!configFile) continue
const completeConfig: Config = const completeConfig: Config | undefined =
await eslint.calculateConfigForFile(configFile) 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 (completeConfig.plugins?.includes('@next/next')) { if (hasNextPlugin) {
nextEslintPluginIsEnabled = true nextEslintPluginIsEnabled = true
for (const [name, [severity]] of Object.entries(completeConfig.rules)) { for (const [name, [severity]] of Object.entries(completeConfig.rules)) {
if (!name.startsWith('@next/next/')) { if (!name.startsWith('@next/next/')) {
...@@ -309,6 +354,17 @@ export async function runLintCheck( ...@@ -309,6 +354,17 @@ export async function runLintCheck(
const eslintrcFile = const eslintrcFile =
(await findUp( (await findUp(
[ [
// eslint v9
'eslint.config.js',
'eslint.config.mjs',
'eslint.config.cjs',
// TODO(jiwon): Support when it's stable.
// TS extensions are experimental and requires to install another 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.js',
'.eslintrc.cjs', '.eslintrc.cjs',
'.eslintrc.yaml', '.eslintrc.yaml',
......
...@@ -603,6 +603,7 @@ function inheritFromMetadata( ...@@ -603,6 +603,7 @@ function inheritFromMetadata(
} }
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const commonOgKeys = ['title', 'description', 'images'] as const const commonOgKeys = ['title', 'description', 'images'] as const
function postProcessMetadata( function postProcessMetadata(
metadata: ResolvedMetadata, metadata: ResolvedMetadata,
......
...@@ -5,6 +5,7 @@ import path from 'path' ...@@ -5,6 +5,7 @@ import path from 'path'
import { PHASE_DEVELOPMENT_SERVER } from '../../shared/lib/constants' import { PHASE_DEVELOPMENT_SERVER } from '../../shared/lib/constants'
import type { TraceEvent } from '../types' import type { TraceEvent } from '../types'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const localEndpoint = { const localEndpoint = {
serviceName: 'nextjs', serviceName: 'nextjs',
ipv4: '127.0.0.1', ipv4: '127.0.0.1',
......
This diff is collapsed.
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` 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>
)
}
}
...@@ -7,7 +7,7 @@ async function getData() { ...@@ -7,7 +7,7 @@ async function getData() {
} }
} }
export default function gspLayout(props) { export default function GspLayout(props) {
const data = use(getData()) const data = use(getData())
return ( return (
......
...@@ -9,7 +9,7 @@ async function getData() { ...@@ -9,7 +9,7 @@ async function getData() {
} }
} }
export default function nestedPage(props) { export default function NestedPage(props) {
const data = use(getData()) const data = use(getData())
return ( return (
......
...@@ -7,7 +7,7 @@ async function getData() { ...@@ -7,7 +7,7 @@ async function getData() {
} }
} }
export default function gspLayout(props) { export default function GspLayout(props) {
const data = use(getData()) const data = use(getData())
return ( return (
......
...@@ -7,7 +7,7 @@ async function getData() { ...@@ -7,7 +7,7 @@ async function getData() {
} }
} }
export default function nestedPage(props) { export default function NestedPage(props) {
const data = use(getData()) const data = use(getData())
return ( return (
......
...@@ -8,7 +8,7 @@ async function getData() { ...@@ -8,7 +8,7 @@ async function getData() {
} }
} }
export default function gspLayout(props) { export default function GspLayout(props) {
const data = use(getData()) const data = use(getData())
return ( return (
<> <>
......
...@@ -8,7 +8,7 @@ async function getData() { ...@@ -8,7 +8,7 @@ async function getData() {
} }
} }
export default function nestedPage(props) { export default function NestedPage(props) {
const data = use(getData()) const data = use(getData())
return ( return (
<> <>
......
...@@ -8,7 +8,7 @@ async function getData() { ...@@ -8,7 +8,7 @@ async function getData() {
} }
} }
export default function gsspLayout(props) { export default function GsspLayout(props) {
const data = use(getData()) const data = use(getData())
return ( return (
......
...@@ -6,7 +6,7 @@ async function getData() { ...@@ -6,7 +6,7 @@ async function getData() {
} }
} }
export default function nestedPage(props) { export default function NestedPage(props) {
const data = use(getData()) const data = use(getData())
return ( return (
......
...@@ -9,7 +9,7 @@ async function getData() { ...@@ -9,7 +9,7 @@ async function getData() {
} }
} }
export default function gsspLayout(props) { export default function GsspLayout(props) {
// TODO-APP: refactor this test page to `async function` instead. // TODO-APP: refactor this test page to `async function` instead.
if (!i) { if (!i) {
i = getData() i = getData()
......
...@@ -8,7 +8,7 @@ async function getData() { ...@@ -8,7 +8,7 @@ async function getData() {
} }
} }
export default function nestedPage(props) { export default function NestedPage(props) {
// TODO-APP: refactor this test page to `async function` instead. // TODO-APP: refactor this test page to `async function` instead.
if (!i) { if (!i) {
i = getData() i = getData()
......
...@@ -6,7 +6,7 @@ async function getData() { ...@@ -6,7 +6,7 @@ async function getData() {
} }
} }
export default function gspLayout(props) { export default function GspLayout(props) {
const data = use(getData()) const data = use(getData())
return ( return (
......
...@@ -8,7 +8,7 @@ async function getData() { ...@@ -8,7 +8,7 @@ async function getData() {
} }
} }
export default function nestedPage(props) { export default function NestedPage(props) {
const data = use(getData()) const data = use(getData())
return ( return (
<> <>
......
...@@ -7,7 +7,7 @@ async function getData() { ...@@ -7,7 +7,7 @@ async function getData() {
} }
} }
export default function gspLayout(props) { export default function GspLayout(props) {
const data = use(getData()) const data = use(getData())
return ( return (
......
...@@ -9,7 +9,7 @@ async function getData() { ...@@ -9,7 +9,7 @@ async function getData() {
} }
} }
export default function nestedPage(props) { export default function NestedPage(props) {
const data = use(getData()) const data = use(getData())
return ( return (
<> <>
......
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
const $comment = ({ gipQuery }) => { const Comment = ({ gipQuery }) => {
const router = useRouter() const router = useRouter()
const { query } = router const { query } = router
...@@ -14,8 +14,8 @@ const $comment = ({ gipQuery }) => { ...@@ -14,8 +14,8 @@ const $comment = ({ gipQuery }) => {
) )
} }
$comment.getInitialProps = async ({ query }) => { Comment.getInitialProps = async ({ query }) => {
return { gipQuery: query } return { gipQuery: query }
} }
export default $comment export default Comment
...@@ -556,54 +556,6 @@ describe('Next Lint', () => { ...@@ -556,54 +556,6 @@ describe('Next Lint', () => {
} }
}) })
test('format flag "compact" creates a file respecting the chosen format', async () => {
const filePath = `${__dirname}/output/output.txt`
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--format', 'compact', '--output-file', filePath],
{
stdout: true,
stderr: true,
}
)
const cliOutput = stdout + stderr
const fileOutput = fs.readFileSync(filePath, 'utf8')
expect(cliOutput).toContain(`The output file has been created: ${filePath}`)
expect(fileOutput).toContain('file-linting/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` 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('file-linting/pages/index.js')
expect(fileOutput).toContain(
'Synchronous scripts should not be used. See: https://nextjs.org/docs/messages/no-sync-scripts'
)
})
test('show error message when the file path is a directory', async () => {
const filePath = `${__dirname}`
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--format', 'compact', '--output-file', filePath],
{
stdout: true,
stderr: true,
}
)
const cliOutput = stdout + stderr
expect(cliOutput).toContain(
`Cannot write to output file path, it is a directory: ${filePath}`
)
})
test('lint files with cjs and mjs file extension', async () => { test('lint files with cjs and mjs file extension', async () => {
const { stdout, stderr } = await nextLint(mjsCjsLinting, [], { const { stdout, stderr } = await nextLint(mjsCjsLinting, [], {
stdout: true, stdout: true,
......
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
const $comment = ({ gipQuery }) => { const Comment = ({ gipQuery }) => {
const router = useRouter() const router = useRouter()
const { query } = router const { query } = router
...@@ -14,8 +14,8 @@ const $comment = ({ gipQuery }) => { ...@@ -14,8 +14,8 @@ const $comment = ({ gipQuery }) => {
) )
} }
$comment.getInitialProps = async ({ query }) => { Comment.getInitialProps = async ({ query }) => {
return { gipQuery: query } return { gipQuery: query }
} }
export default $comment export default Comment
...@@ -10,7 +10,7 @@ import { promisify } from 'util' ...@@ -10,7 +10,7 @@ import { promisify } from 'util'
import http from 'http' import http from 'http'
import path from 'path' import path from 'path'
import cheerio from 'cheerio' import type cheerio from 'cheerio'
import spawn from 'cross-spawn' import spawn from 'cross-spawn'
import { writeFile } from 'fs-extra' import { writeFile } from 'fs-extra'
import getPort from 'get-port' import getPort from 'get-port'
......
...@@ -12,12 +12,13 @@ describe('Next Build', () => { ...@@ -12,12 +12,13 @@ describe('Next Build', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
test('first time setup', async () => { test('first time setup - ESLint v8', async () => {
const next = await createNext({ const next = await createNext({
files: new FileRef(dirFirstTimeSetup), files: new FileRef(dirFirstTimeSetup),
dependencies: { dependencies: {
// create-next-install will replace this with a version built from the local source // create-next-install will replace this with a version built from the local source
'eslint-config-next': 'canary', 'eslint-config-next': 'canary',
eslint: '^8',
}, },
skipStart: true, skipStart: true,
}) })
...@@ -92,12 +93,96 @@ describe('Next Build', () => { ...@@ -92,12 +93,96 @@ describe('Next Build', () => {
} }
}) })
test('first time setup with TypeScript', async () => { 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(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({ const next = await createNext({
files: new FileRef(dirFirstTimeSetupTS), files: new FileRef(dirFirstTimeSetupTS),
dependencies: { dependencies: {
// create-next-install will replace this with a version built from the local source // create-next-install will replace this with a version built from the local source
'eslint-config-next': 'canary', 'eslint-config-next': 'canary',
eslint: '^8',
}, },
skipStart: true, skipStart: true,
}) })
...@@ -171,6 +256,89 @@ describe('Next Build', () => { ...@@ -171,6 +256,89 @@ describe('Next Build', () => {
await next.destroy() 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(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()
}
})
} }
) )
}) })
import rule from '@next/eslint-plugin-next/dist/rules/google-font-display' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('google-font-display', rule, { const NextESLintRule = rules['google-font-display']
const tests = {
valid: [ valid: [
`import Head from "next/head"; `import Head from "next/head";
...@@ -169,4 +161,30 @@ ruleTester.run('google-font-display', rule, { ...@@ -169,4 +161,30 @@ ruleTester.run('google-font-display', rule, {
], ],
}, },
], ],
}
describe('google-font-display', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2020,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/google-font-preconnect' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('google-font-preconnect', rule, { const NextESLintRule = rules['google-font-preconnect']
const tests = {
valid: [ valid: [
`export const Test = () => ( `export const Test = () => (
<div> <div>
...@@ -64,4 +56,30 @@ ruleTester.run('google-font-preconnect', rule, { ...@@ -64,4 +56,30 @@ ruleTester.run('google-font-preconnect', rule, {
], ],
}, },
], ],
}
describe('google-font-preconnect', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2020,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/inline-script-id' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['inline-script-id']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const errorMessage = const errorMessage =
'`next/script` components with inline content must specify an `id` attribute. See: https://nextjs.org/docs/messages/inline-script-id' '`next/script` components with inline content must specify an `id` attribute. See: https://nextjs.org/docs/messages/inline-script-id'
const ruleTester = new RuleTester() const tests = {
ruleTester.run('inline-script-id', rule, {
valid: [ valid: [
{ {
code: `import Script from 'next/script'; code: `import Script from 'next/script';
...@@ -184,4 +176,30 @@ ruleTester.run('inline-script-id', rule, { ...@@ -184,4 +176,30 @@ ruleTester.run('inline-script-id', rule, {
], ],
}, },
], ],
}
describe('inline-script-id', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/next-script-for-ga' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['next-script-for-ga']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ERROR_MSG = const ERROR_MSG =
'Prefer `next/script` component when using the inline script for Google Analytics. See: https://nextjs.org/docs/messages/next-script-for-ga' 'Prefer `next/script` component when using the inline script for Google Analytics. See: https://nextjs.org/docs/messages/next-script-for-ga'
const ruleTester = new RuleTester() const tests = {
ruleTester.run('sync-scripts', rule, {
valid: [ valid: [
`import Script from 'next/script' `import Script from 'next/script'
...@@ -238,4 +229,30 @@ ruleTester.run('sync-scripts', rule, { ...@@ -238,4 +229,30 @@ ruleTester.run('sync-scripts', rule, {
], ],
}, },
], ],
}
describe('next-script-for-ga', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-assign-module-variable' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-assign-module-variable', rule, { const NextESLintRule = rules['no-assign-module-variable']
const tests = {
valid: [ valid: [
` `
let myModule = {}; let myModule = {};
...@@ -39,4 +31,30 @@ ruleTester.run('no-assign-module-variable', rule, { ...@@ -39,4 +31,30 @@ ruleTester.run('no-assign-module-variable', rule, {
], ],
}, },
], ],
}
describe('no-assign-module-variable', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-async-client-component' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-async-client-component']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
const message = const message =
'Prevent client components from being async functions. See: https://nextjs.org/docs/messages/no-async-client-component' 'Prevent client components from being async functions. See: https://nextjs.org/docs/messages/no-async-client-component'
ruleTester.run('no-async-client-component single line', rule, { const tests = {
valid: [ valid: [
` `
// single line
export default async function MyComponent() { export default async function MyComponent() {
return <></> return <></>
} }
`, `,
`
// single line capitalization
"use client"
export default async function myFunction() {
return ''
}
`,
`
// multiple line
async function MyComponent() {
return <></>
}
export default MyComponent
`,
`
// multiple line capitalization
"use client"
async function myFunction() {
return ''
}
export default myFunction
`,
`
// arrow function
"use client"
const myFunction = () => {
return ''
}
export default myFunction
`,
], ],
invalid: [ invalid: [
{ {
code: ` code: `
// single line
"use client" "use client"
export default async function MyComponent() { export default async function MyComponent() {
return <></> return <></>
} }
`, `,
errors: [ errors: [{ message }],
{
message,
},
],
}, },
],
})
ruleTester.run('no-async-client-component single line capitalization', rule, {
valid: [
`
"use client"
export default async function myFunction() {
return ''
}
`,
],
invalid: [
{ {
code: ` code: `
// single line capitalization
"use client" "use client"
export default async function MyFunction() { export default async function MyFunction() {
return '' return ''
} }
`, `,
errors: [ errors: [{ message }],
{
message,
},
],
}, },
],
})
ruleTester.run('no-async-client-component multiple line', rule, {
valid: [
`
async function MyComponent() {
return <></>
}
export default MyComponent
`,
],
invalid: [
{ {
code: ` code: `
// multiple line
"use client" "use client"
async function MyComponent() { async function MyComponent() {
...@@ -90,30 +86,11 @@ ruleTester.run('no-async-client-component multiple line', rule, { ...@@ -90,30 +86,11 @@ ruleTester.run('no-async-client-component multiple line', rule, {
export default MyComponent export default MyComponent
`, `,
errors: [ errors: [{ message }],
{
message,
},
],
}, },
],
})
ruleTester.run('no-async-client-component multiple line capitalization', rule, {
valid: [
`
"use client"
async function myFunction() {
return ''
}
export default myFunction
`,
],
invalid: [
{ {
code: ` code: `
// multiple line capitalization
"use client" "use client"
async function MyFunction() { async function MyFunction() {
...@@ -122,30 +99,11 @@ ruleTester.run('no-async-client-component multiple line capitalization', rule, { ...@@ -122,30 +99,11 @@ ruleTester.run('no-async-client-component multiple line capitalization', rule, {
export default MyFunction export default MyFunction
`, `,
errors: [ errors: [{ message }],
{
message,
},
],
}, },
],
})
ruleTester.run('no-async-client-component arrow function', rule, {
valid: [
`
"use client"
const myFunction = () => {
return ''
}
export default myFunction
`,
],
invalid: [
{ {
code: ` code: `
// arrow function
"use client" "use client"
const MyFunction = async () => { const MyFunction = async () => {
...@@ -154,11 +112,33 @@ ruleTester.run('no-async-client-component arrow function', rule, { ...@@ -154,11 +112,33 @@ ruleTester.run('no-async-client-component arrow function', rule, {
export default MyFunction export default MyFunction
`, `,
errors: [ errors: [{ message }],
{
message,
},
],
}, },
], ],
}
describe('no-async-client-component', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-before-interactive-script-outside-document' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-before-interactive-script-outside-document']
sourceType: 'module',
ecmaFeatures: { const message =
modules: true, "`next/script`'s `beforeInteractive` strategy should not be used outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document"
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-before-interactive-script-outside-document', rule, { const tests = {
valid: [ valid: [
{ {
code: ` code: `
...@@ -172,13 +167,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, { ...@@ -172,13 +167,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, {
filename: filename:
'C:\\Users\\username\\projects\\project-name\\src\\app\\layout.tsx', 'C:\\Users\\username\\projects\\project-name\\src\\app\\layout.tsx',
}, },
].map((obj, idx) => ({ ],
...obj,
code: `// valid-${idx}
${obj.code}
`,
})),
invalid: [ invalid: [
{ {
code: ` code: `
...@@ -195,12 +184,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, { ...@@ -195,12 +184,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, {
); );
}`, }`,
filename: 'pages/index.js', filename: 'pages/index.js',
errors: [ errors: [{ message }],
{
message:
"`next/script`'s `beforeInteractive` strategy should not be used outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document",
},
],
}, },
{ {
code: ` code: `
...@@ -217,12 +201,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, { ...@@ -217,12 +201,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, {
); );
}`, }`,
filename: 'components/outside-known-dirs.js', filename: 'components/outside-known-dirs.js',
errors: [ errors: [{ message }],
{
message:
"`next/script`'s `beforeInteractive` strategy should not be used outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document",
},
],
}, },
{ {
code: ` code: `
...@@ -240,12 +219,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, { ...@@ -240,12 +219,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, {
); );
}`, }`,
filename: '/Users/user_name/projects/project-name/pages/layout.tsx', filename: '/Users/user_name/projects/project-name/pages/layout.tsx',
errors: [ errors: [{ message }],
{
message:
"`next/script`'s `beforeInteractive` strategy should not be used outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document",
},
],
}, },
{ {
code: ` code: `
...@@ -264,12 +238,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, { ...@@ -264,12 +238,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, {
}`, }`,
filename: filename:
'C:\\Users\\username\\projects\\project-name\\pages\\layout.tsx', 'C:\\Users\\username\\projects\\project-name\\pages\\layout.tsx',
errors: [ errors: [{ message }],
{
message:
"`next/script`'s `beforeInteractive` strategy should not be used outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document",
},
],
}, },
{ {
code: ` code: `
...@@ -287,12 +256,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, { ...@@ -287,12 +256,7 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, {
); );
}`, }`,
filename: '/Users/user_name/projects/project-name/src/pages/layout.tsx', filename: '/Users/user_name/projects/project-name/src/pages/layout.tsx',
errors: [ errors: [{ message }],
{
message:
"`next/script`'s `beforeInteractive` strategy should not be used outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document",
},
],
}, },
{ {
code: ` code: `
...@@ -311,17 +275,33 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, { ...@@ -311,17 +275,33 @@ ruleTester.run('no-before-interactive-script-outside-document', rule, {
}`, }`,
filename: filename:
'C:\\Users\\username\\projects\\project-name\\src\\pages\\layout.tsx', 'C:\\Users\\username\\projects\\project-name\\src\\pages\\layout.tsx',
errors: [ errors: [{ message }],
{ },
message: ],
"`next/script`'s `beforeInteractive` strategy should not be used outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document", }
describe('no-before-interactive-script-outside-document', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
}, },
], },
}, },
].map((obj, idx) => ({ }).run('eslint-v9', NextESLintRule, tests)
...obj,
code: `// invalid-${idx}
${obj.code}
`,
})),
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-css-tags' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-css-tags']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-css-tags', rule, { const message =
'Do not include stylesheets manually. See: https://nextjs.org/docs/messages/no-css-tags'
const tests = {
valid: [ valid: [
`import {Head} from 'next/document'; `import {Head} from 'next/document';
...@@ -80,8 +75,7 @@ ruleTester.run('no-css-tags', rule, { ...@@ -80,8 +75,7 @@ ruleTester.run('no-css-tags', rule, {
}`, }`,
errors: [ errors: [
{ {
message: message,
'Do not include stylesheets manually. See: https://nextjs.org/docs/messages/no-css-tags',
type: 'JSXOpeningElement', type: 'JSXOpeningElement',
}, },
], ],
...@@ -93,11 +87,36 @@ ruleTester.run('no-css-tags', rule, { ...@@ -93,11 +87,36 @@ ruleTester.run('no-css-tags', rule, {
</div>`, </div>`,
errors: [ errors: [
{ {
message: message,
'Do not include stylesheets manually. See: https://nextjs.org/docs/messages/no-css-tags',
type: 'JSXOpeningElement', type: 'JSXOpeningElement',
}, },
], ],
}, },
], ],
}
describe('no-css-tags', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import path from 'path' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester as ESLintTesterV9 } from 'eslint'
import { rules } from '@next/eslint-plugin-next'
import rule from '@next/eslint-plugin-next/dist/rules/no-document-import-in-page' const NextESLintRule = rules['no-document-import-in-page']
import { RuleTester } from 'eslint'
;(RuleTester as any).setDefaultConfig({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-document-import-in-page', rule, { const tests = {
valid: [ valid: [
{ {
code: `import Document from "next/document" code: `import Document from "next/document"
...@@ -33,34 +23,6 @@ ruleTester.run('no-document-import-in-page', rule, { ...@@ -33,34 +23,6 @@ ruleTester.run('no-document-import-in-page', rule, {
{ {
code: `import Document from "next/document" code: `import Document from "next/document"
export default class MyDocument extends Document {
render() {
return (
<Html>
</Html>
);
}
}
`,
filename: `pages${path.sep}_document.js`,
},
{
code: `import NextDocument from "next/document"
export default class MyDocument extends NextDocument {
render() {
return (
<Html>
</Html>
);
}
}
`,
filename: `pages${path.posix.sep}_document.tsx`,
},
{
code: `import Document from "next/document"
export default class MyDocument extends Document { export default class MyDocument extends Document {
render() { render() {
return ( return (
...@@ -144,19 +106,31 @@ ruleTester.run('no-document-import-in-page', rule, { ...@@ -144,19 +106,31 @@ ruleTester.run('no-document-import-in-page', rule, {
}, },
], ],
}, },
{ ],
code: `import Document from "next/document" }
export const Test = () => <p>Test</p> describe('no-document-import-in-page', () => {
`, new ESLintTesterV8({
filename: `pages${path.sep}test.js`, parserOptions: {
errors: [ ecmaVersion: 2018,
{ sourceType: 'module',
message: ecmaFeatures: {
'`<Document />` from `next/document` should not be imported outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-document-import-in-page', modules: true,
type: 'ImportDeclaration', jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
}, },
], },
}, },
], }).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-duplicate-head' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-duplicate-head']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-duplicate-head', rule, { const message =
'Do not include multiple instances of `<Head/>`. See: https://nextjs.org/docs/messages/no-duplicate-head'
const tests = {
valid: [ valid: [
{ {
code: `import Document, { Html, Head, Main, NextScript } from 'next/document' code: `import Document, { Html, Head, Main, NextScript } from 'next/document'
...@@ -82,13 +77,11 @@ ruleTester.run('no-duplicate-head', rule, { ...@@ -82,13 +77,11 @@ ruleTester.run('no-duplicate-head', rule, {
filename: 'pages/_document.js', filename: 'pages/_document.js',
errors: [ errors: [
{ {
message: message,
'Do not include multiple instances of `<Head/>`. See: https://nextjs.org/docs/messages/no-duplicate-head',
type: 'JSXElement', type: 'JSXElement',
}, },
{ {
message: message,
'Do not include multiple instances of `<Head/>`. See: https://nextjs.org/docs/messages/no-duplicate-head',
type: 'JSXElement', type: 'JSXElement',
}, },
], ],
...@@ -130,11 +123,36 @@ ruleTester.run('no-duplicate-head', rule, { ...@@ -130,11 +123,36 @@ ruleTester.run('no-duplicate-head', rule, {
filename: 'pages/_document.page.tsx', filename: 'pages/_document.page.tsx',
errors: [ errors: [
{ {
message: message,
'Do not include multiple instances of `<Head/>`. See: https://nextjs.org/docs/messages/no-duplicate-head',
type: 'JSXElement', type: 'JSXElement',
}, },
], ],
}, },
], ],
}
describe('no-duplicate-head', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-head-element' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-head-element']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-head-element', rule, { const message =
'Do not use `<head>` element. Use `<Head />` from `next/head` instead. See: https://nextjs.org/docs/messages/no-head-element'
const tests = {
valid: [ valid: [
{ {
code: `import Head from 'next/head'; code: `import Head from 'next/head';
...@@ -81,8 +76,7 @@ ruleTester.run('no-head-element', rule, { ...@@ -81,8 +76,7 @@ ruleTester.run('no-head-element', rule, {
filename: './pages/index.js', filename: './pages/index.js',
errors: [ errors: [
{ {
message: message,
'Do not use `<head>` element. Use `<Head />` from `next/head` instead. See: https://nextjs.org/docs/messages/no-head-element',
type: 'JSXOpeningElement', type: 'JSXOpeningElement',
}, },
], ],
...@@ -107,11 +101,36 @@ ruleTester.run('no-head-element', rule, { ...@@ -107,11 +101,36 @@ ruleTester.run('no-head-element', rule, {
filename: 'pages/index.ts', filename: 'pages/index.ts',
errors: [ errors: [
{ {
message: message,
'Do not use `<head>` element. Use `<Head />` from `next/head` instead. See: https://nextjs.org/docs/messages/no-head-element',
type: 'JSXOpeningElement', type: 'JSXOpeningElement',
}, },
], ],
}, },
], ],
}
describe('no-head-element', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-head-import-in-document' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-head-import-in-document', rule, { const NextESLintRule = rules['no-head-import-in-document']
const tests = {
valid: [ valid: [
{ {
code: `import Document, { Html, Head, Main, NextScript } from 'next/document' code: `import Document, { Html, Head, Main, NextScript } from 'next/document'
...@@ -173,4 +165,30 @@ ruleTester.run('no-head-import-in-document', rule, { ...@@ -173,4 +165,30 @@ ruleTester.run('no-head-import-in-document', rule, {
], ],
}, },
], ],
}
describe('no-head-import-in-document', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import * as rule from '@next/eslint-plugin-next/dist/rules/no-img-element' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-img-element']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-img-element', rule, { const message =
'Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element'
const tests = {
valid: [ valid: [
`import { Image } from 'next/image'; `import { Image } from 'next/image';
...@@ -78,13 +73,7 @@ ruleTester.run('no-img-element', rule, { ...@@ -78,13 +73,7 @@ ruleTester.run('no-img-element', rule, {
); );
} }
}`, }`,
errors: [ errors: [{ message, type: 'JSXOpeningElement' }],
{
message:
'Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element',
type: 'JSXOpeningElement',
},
],
}, },
{ {
code: ` code: `
...@@ -100,13 +89,33 @@ ruleTester.run('no-img-element', rule, { ...@@ -100,13 +89,33 @@ ruleTester.run('no-img-element', rule, {
); );
} }
}`, }`,
errors: [ errors: [{ message, type: 'JSXOpeningElement' }],
{
message:
'Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element',
type: 'JSXOpeningElement',
},
],
}, },
], ],
}
describe('no-img-element', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-page-custom-font' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-page-custom-font']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
const filename = 'pages/_document.js' const filename = 'pages/_document.js'
ruleTester.run('no-page-custom-font', rule, { const tests = {
valid: [ valid: [
{ {
code: `import Document, { Html, Head } from "next/document"; code: `import Document, { Html, Head } from "next/document";
...@@ -197,4 +189,30 @@ ruleTester.run('no-page-custom-font', rule, { ...@@ -197,4 +189,30 @@ ruleTester.run('no-page-custom-font', rule, {
], ],
}, },
], ],
}
describe('no-page-custom-font', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-script-component-in-head' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-script-component-in-head']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-script-in-head', rule, { const message =
'`next/script` should not be used in `next/head` component. Move `<Script />` outside of `<Head>` instead. See: https://nextjs.org/docs/messages/no-script-component-in-head'
const tests = {
valid: [ valid: [
`import Script from "next/script"; `import Script from "next/script";
const Head = ({children}) => children const Head = ({children}) => children
...@@ -41,12 +36,33 @@ ruleTester.run('no-script-in-head', rule, { ...@@ -41,12 +36,33 @@ ruleTester.run('no-script-in-head', rule, {
); );
}`, }`,
filename: 'pages/index.js', filename: 'pages/index.js',
errors: [ errors: [{ message }],
{
message:
'`next/script` should not be used in `next/head` component. Move `<Script />` outside of `<Head>` instead. See: https://nextjs.org/docs/messages/no-script-component-in-head',
},
],
}, },
], ],
}
describe('no-script-component-in-head', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-styled-jsx-in-document' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-styled-jsx-in-document', rule, { const NextESLintRule = rules['no-styled-jsx-in-document']
const tests = {
valid: [ valid: [
{ {
filename: 'pages/_document.js', filename: 'pages/_document.js',
...@@ -121,4 +113,30 @@ ruleTester.run('no-styled-jsx-in-document', rule, { ...@@ -121,4 +113,30 @@ ruleTester.run('no-styled-jsx-in-document', rule, {
], ],
}, },
], ],
}
describe('no-styled-jsx-in-document', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-sync-scripts' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018, const NextESLintRule = rules['no-sync-scripts']
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('sync-scripts', rule, { const message =
'Synchronous scripts should not be used. See: https://nextjs.org/docs/messages/no-sync-scripts'
const tests = {
valid: [ valid: [
`import {Head} from 'next/document'; `import {Head} from 'next/document';
...@@ -55,13 +50,7 @@ ruleTester.run('sync-scripts', rule, { ...@@ -55,13 +50,7 @@ ruleTester.run('sync-scripts', rule, {
); );
} }
}`, }`,
errors: [ errors: [{ message, type: 'JSXOpeningElement' }],
{
message:
'Synchronous scripts should not be used. See: https://nextjs.org/docs/messages/no-sync-scripts',
type: 'JSXOpeningElement',
},
],
}, },
{ {
code: ` code: `
...@@ -77,13 +66,33 @@ ruleTester.run('sync-scripts', rule, { ...@@ -77,13 +66,33 @@ ruleTester.run('sync-scripts', rule, {
); );
} }
}`, }`,
errors: [ errors: [{ message, type: 'JSXOpeningElement' }],
{
message:
'Synchronous scripts should not be used. See: https://nextjs.org/docs/messages/no-sync-scripts',
type: 'JSXOpeningElement',
},
],
}, },
], ],
}
describe('no-sync-scripts', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-title-in-document-head' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('no-title-in-document-head', rule, { const NextESLintRule = rules['no-title-in-document-head']
const tests = {
valid: [ valid: [
`import Head from "next/head"; `import Head from "next/head";
...@@ -66,4 +58,30 @@ ruleTester.run('no-title-in-document-head', rule, { ...@@ -66,4 +58,30 @@ ruleTester.run('no-title-in-document-head', rule, {
], ],
}, },
], ],
}
describe('no-title-in-document-head', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-typos' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester() const NextESLintRule = rules['no-typos']
ruleTester.run('no-typos', rule, { const tests = {
valid: [ valid: [
` `
export default function Page() { export default function Page() {
...@@ -127,4 +118,30 @@ ruleTester.run('no-typos', rule, { ...@@ -127,4 +118,30 @@ ruleTester.run('no-typos', rule, {
], ],
}, },
], ],
}
describe('no-typos', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
import rule from '@next/eslint-plugin-next/dist/rules/no-unwanted-polyfillio' import { RuleTester as ESLintTesterV8 } from 'eslint-v8'
import { RuleTester } from 'eslint' import { RuleTester as ESLintTesterV9 } from 'eslint'
;(RuleTester as any).setDefaultConfig({ import { rules } from '@next/eslint-plugin-next'
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
})
const ruleTester = new RuleTester()
ruleTester.run('unwanted-polyfillsio', rule, { const NextESLintRule = rules['no-unwanted-polyfillio']
const tests = {
valid: [ valid: [
`import {Head} from 'next/document'; `import {Head} from 'next/document';
...@@ -142,4 +134,30 @@ ruleTester.run('unwanted-polyfillsio', rule, { ...@@ -142,4 +134,30 @@ ruleTester.run('unwanted-polyfillsio', rule, {
], ],
}, },
], ],
}
describe('no-unwanted-polyfillio', () => {
new ESLintTesterV8({
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
modules: true,
jsx: true,
},
},
}).run('eslint-v8', NextESLintRule, tests)
new ESLintTesterV9({
languageOptions: {
ecmaVersion: 2018,
sourceType: 'module',
parserOptions: {
ecmaFeatures: {
modules: true,
jsx: true,
},
},
},
}).run('eslint-v9', NextESLintRule, tests)
}) })
...@@ -6,6 +6,7 @@ import { expectTypeOf } from 'expect-type' ...@@ -6,6 +6,7 @@ import { expectTypeOf } from 'expect-type'
describe('InferGetServerSidePropsType', () => { describe('InferGetServerSidePropsType', () => {
it('should work with sync functions', async () => { it('should work with sync functions', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getServerSideProps(context: GetServerSidePropsContext) { function getServerSideProps(context: GetServerSidePropsContext) {
if (context.params?.notFound) { if (context.params?.notFound) {
return { return {
...@@ -26,6 +27,7 @@ describe('InferGetServerSidePropsType', () => { ...@@ -26,6 +27,7 @@ describe('InferGetServerSidePropsType', () => {
}) })
it('should work with async functions', async () => { it('should work with async functions', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function getServerSideProps(context: GetServerSidePropsContext) { async function getServerSideProps(context: GetServerSidePropsContext) {
if (context.params?.notFound) { if (context.params?.notFound) {
return { return {
...@@ -54,6 +56,7 @@ describe('InferGetServerSidePropsType', () => { ...@@ -54,6 +56,7 @@ describe('InferGetServerSidePropsType', () => {
}) })
it('should work with promised props', async () => { it('should work with promised props', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function getServerSideProps() { async function getServerSideProps() {
return { return {
props: Promise.resolve({ props: Promise.resolve({
......
...@@ -3,6 +3,7 @@ import { expectTypeOf } from 'expect-type' ...@@ -3,6 +3,7 @@ import { expectTypeOf } from 'expect-type'
describe('InferGetServerSidePropsType', () => { describe('InferGetServerSidePropsType', () => {
it('should work with sync functions', async () => { it('should work with sync functions', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getStaticProps(context: GetStaticPropsContext) { function getStaticProps(context: GetStaticPropsContext) {
if (context.params?.notFound) { if (context.params?.notFound) {
return { return {
...@@ -23,6 +24,7 @@ describe('InferGetServerSidePropsType', () => { ...@@ -23,6 +24,7 @@ describe('InferGetServerSidePropsType', () => {
}) })
it('should work with async functions', async () => { it('should work with async functions', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function getStaticProps(context: GetStaticPropsContext) { async function getStaticProps(context: GetStaticPropsContext) {
if (context.params?.notFound) { if (context.params?.notFound) {
return { return {
......
import * as expectMod from "./tests/execution/node_modules/expect"; import type * as expectMod from "./tests/execution/node_modules/expect";
import * as jest from "./tests/execution/node_modules/jest-circus"; import type * as jest from "./tests/execution/node_modules/jest-circus";
export {}; export {};
......
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