fix: replace deprecated/removed functions in eslint-plugin-next (#64251)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

Hi everyone, this is my first PR to such a large project so please be
gentle. 😄 I'm also new to publishing packages so I'm not sure if I'm
missing any steps.

ESLint 9.0.0 came out a few days ago and unfortunately,
`eslint-plugin-next` is not compatible as it uses deprecated (and with
ESLint 9.0.0 removed) functions.
In this PR, I replaced the deprecated functions with the suggested
replacements ([check this
out](https://eslint.org/blog/2023/09/preparing-custom-rules-eslint-v9/)).

Regarding backwards compatibility, everything I used is available since
ESLint 8.40 (released May 2023). I'm not sure how far back Next.js
support goes but it feels fine to me.

I successfully tested some rules locally with ESLint 9.0.0 and this
`eslint.config.js` (flat config format):
```js
import js from '@eslint/js';
import nextPlugin from '@next/eslint-plugin-next';
import prettierRecommended from 'eslint-plugin-prettier/recommended';
import importSortPlugin from 'eslint-plugin-simple-import-sort';
import globals from 'globals';
import tseslint from 'typescript-eslint';

/**
 * TypeScript config with strict type checking and no type checking for JS files.
 */
const typeScriptConfig = [
  ...tseslint.configs.strictTypeChecked,
  {
    plugins: {
      '@typescript-eslint': tseslint.plugin,
    },
    languageOptions: {
      parser: tseslint.parser,
      parserOptions: {
        project: true,
      },
    },
  },
  {
    // disable type-aware linting on JS files
    files: ['**/*.js', '**/*.mjs', '**/*.cjs'],
    ...tseslint.configs.disableTypeChecked,
  },
];

/**
 * Next.js config with recommended and core web vitals rules.
 */
const nextConfig = {
  plugins: {
    '@next/next': nextPlugin,
  },
  rules: {
    ...nextPlugin.configs.recommended.rules,
    ...nextPlugin.configs['core-web-vitals'].rules,
  },
};

/**
 * Import sort config with simple-import-sort plugin.
 */
const importSortConfig = {
  plugins: {
    'simple-import-sort': importSortPlugin,
  },
  rules: {
    'simple-import-sort/imports': 'error',
    'simple-import-sort/exports': 'error',
  },
};

/**
 * The final ESLint config wrapped with the tseslint.config helper for type hinting.
 */
export default tseslint.config(
  {
    ignores: ['.next', '.yarn', '**/*.d.ts', 'node_modules'],
  },
  {
    languageOptions: {
      globals: {
        ...globals.browser,
        ...globals.node,
      },
    },
  },
  js.configs.recommended,
  ...typeScriptConfig,
  nextConfig,
  prettierRecommended,
  importSortConfig,
);

```

It has a few more configs but I'm sure you can remove most of them. The
important one is the `nextConfig`. Also important: Run `eslint` and not
`next lint`, it's currently not compatible with the new flat config
format.

Related discussion: https://github.com/vercel/next.js/discussions/54238

---------

Co-authored-by: JJ Kasper <jj@jjsweb.site>
This commit is contained in:
Markus Renken 2024-05-06 23:22:18 +02:00 committed by GitHub
parent cdb415451a
commit d8e866686d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 25 additions and 37 deletions

View file

@ -15,7 +15,7 @@
"glob": "10.3.10"
},
"devDependencies": {
"eslint": "7.24.0"
"eslint": "8.56.0"
},
"scripts": {
"build": "swc -d dist src",

View file

@ -28,7 +28,7 @@ export = defineRule({
scriptImportName = node.local.name
},
JSXOpeningElement(node) {
const pathname = convertToCorrectSeparator(context.getFilename())
const pathname = convertToCorrectSeparator(context.filename)
const isInAppDir = pathname.includes(`${path.sep}app${path.sep}`)
@ -57,7 +57,7 @@ export = defineRule({
return
}
const document = context.getFilename().split('pages', 2)[1]
const document = context.filename.split('pages', 2)[1]
if (document && path.parse(document).name.startsWith('_document')) {
return
}

View file

@ -21,7 +21,7 @@ export = defineRule({
return
}
const paths = context.getFilename().split('pages')
const paths = context.filename.split('pages')
const page = paths[paths.length - 1]
if (

View file

@ -13,6 +13,7 @@ export = defineRule({
schema: [],
},
create(context) {
const { sourceCode } = context
let documentImportName
return {
ImportDeclaration(node) {
@ -26,7 +27,7 @@ export = defineRule({
}
},
ReturnStatement(node) {
const ancestors = context.getAncestors()
const ancestors = sourceCode.getAncestors(node)
const documentClass = ancestors.find(
(ancestorNode) =>
ancestorNode.type === 'ClassDeclaration' &&
@ -39,7 +40,6 @@ export = defineRule({
return
}
// @ts-expect-error - `node.argument` could be a `JSXElement` which has property `children`
if (
node.argument &&
'children' in node.argument &&

View file

@ -17,7 +17,7 @@ export = defineRule({
create(context) {
return {
JSXOpeningElement(node) {
const paths = context.getFilename()
const paths = context.filename
const isInAppDir = () =>
paths.includes(`app${path.sep}`) ||

View file

@ -20,7 +20,7 @@ export = defineRule({
return
}
const document = context.getFilename().split('pages', 2)[1]
const document = context.filename.split('pages', 2)[1]
if (!document) {
return
}

View file

@ -20,7 +20,8 @@ export = defineRule({
schema: [],
},
create(context) {
const paths = context.getFilename().split('pages')
const { sourceCode } = context
const paths = context.filename.split('pages')
const page = paths[paths.length - 1]
// outside of a file within `pages`, bail
@ -71,7 +72,7 @@ export = defineRule({
return
}
const ancestors = context.getAncestors()
const ancestors = sourceCode.getAncestors(node)
// if `export default <name>` is further down within the file after the
// currently traversed component, then `localDefaultExportName` will

View file

@ -16,7 +16,7 @@ export = defineRule({
create(context) {
return {
JSXOpeningElement(node) {
const document = context.getFilename().split('pages', 2)[1]
const document = context.filename.split('pages', 2)[1]
if (!document) {
return
}

View file

@ -73,7 +73,7 @@ export = defineRule({
}
return {
ExportNamedDeclaration(node) {
const page = context.getFilename().split('pages', 2)[1]
const page = context.filename.split('pages', 2)[1]
if (!page || path.parse(page).dir.startsWith('/api')) {
return
}

View file

@ -14,7 +14,7 @@ const processRootDir = (rootDir: string): string[] => {
* Gets one or more Root, returns an array of root directories.
*/
export const getRootDirs = (context: Rule.RuleContext) => {
let rootDirs = [context.getCwd()]
let rootDirs = [context.cwd]
const nextSettings: { rootDir?: string | string[] } =
context.settings.next || {}

View file

@ -784,8 +784,8 @@ importers:
version: 10.3.10
devDependencies:
eslint:
specifier: 7.24.0
version: 7.24.0
specifier: 8.56.0
version: 8.56.0
packages/font:
dependencies:
@ -12172,34 +12172,34 @@ packages:
ajv: 6.12.6
chalk: 4.1.2
cross-spawn: 7.0.3
debug: 4.3.4
debug: 4.1.1
doctrine: 3.0.0
enquirer: 2.3.6
eslint-scope: 5.1.1
eslint-utils: 2.1.0
eslint-visitor-keys: 2.1.0
espree: 7.3.1
esquery: 1.4.0
esquery: 1.5.0
esutils: 2.0.3
file-entry-cache: 6.0.1
functional-red-black-tree: 1.0.1
glob-parent: 5.1.2
globals: 13.12.0
globals: 13.19.0
ignore: 4.0.6
import-fresh: 3.2.1
import-fresh: 3.3.0
imurmurhash: 0.1.4
is-glob: 4.0.3
js-yaml: 3.14.1
json-stable-stringify-without-jsonify: 1.0.1
levn: 0.4.1
lodash: 4.17.21
minimatch: 3.1.2
minimatch: 3.0.4
natural-compare: 1.4.0
optionator: 0.9.1
optionator: 0.9.3
progress: 2.0.3
regexpp: 3.1.0
semver: 7.3.7
strip-ansi: 6.0.1
strip-ansi: 6.0.0
strip-json-comments: 3.1.1
table: 6.8.0
text-table: 0.2.0
@ -12340,6 +12340,7 @@ packages:
engines: {node: '>=0.10'}
dependencies:
estraverse: 5.3.0
dev: false
/esquery@1.5.0:
resolution: {integrity: sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==}
@ -13567,13 +13568,6 @@ packages:
resolution: {integrity: sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==}
engines: {node: '>=4'}
/globals@13.12.0:
resolution: {integrity: sha512-uS8X6lSKN2JumVoXrbUz+uG4BYG+eiawqm3qFcT7ammfbUHeCBoJMlHcec/S3krSk73/AE/f0szYFmgAA3kYZg==}
engines: {node: '>=8'}
dependencies:
type-fest: 0.20.2
dev: true
/globals@13.19.0:
resolution: {integrity: sha512-dkQ957uSRWHw7CFXLUtUHQI3g3aWApYhfNR2O6jn/907riyTYKVBmxYVROkBcY614FSSeSJh7Xm7SrUWCxvJMQ==}
engines: {node: '>=8'}
@ -14355,14 +14349,6 @@ packages:
resolve-from: 3.0.0
dev: true
/import-fresh@3.2.1:
resolution: {integrity: sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ==}
engines: {node: '>=6'}
dependencies:
parent-module: 1.0.1
resolve-from: 4.0.0
dev: true
/import-fresh@3.3.0:
resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==}
engines: {node: '>=6'}
@ -18911,6 +18897,7 @@ packages:
prelude-ls: 1.2.1
type-check: 0.4.0
word-wrap: 1.2.3
dev: false
/optionator@0.9.3:
resolution: {integrity: sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==}