Unverified Commit 4141aaef authored by Houssein Djirdeh's avatar Houssein Djirdeh Committed by GitHub

[ESLint] Support single-file linting in `next lint` (necessary for `lint-staged`) (#28042)

Co-authored-by: 's avatarTim Neutkens <timneutkens@me.com>
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent eab3db20
...@@ -121,7 +121,7 @@ If you're using `eslint-plugin-next` in a project where Next.js isn't installed ...@@ -121,7 +121,7 @@ If you're using `eslint-plugin-next` in a project where Next.js isn't installed
`rootDir` can be a path (relative or absolute), a glob (i.e. `"/packages/*/"`), or an array of paths and/or globs. `rootDir` can be a path (relative or absolute), a glob (i.e. `"/packages/*/"`), or an array of paths and/or globs.
## Linting Custom Directories ## Linting Custom Directories and Files
By default, Next.js will run ESLint for all files in the `pages/`, `components/`, and `lib/` directories. However, you can specify which directories using the `dirs` option in the `eslint` config in `next.config.js` for production builds: By default, Next.js will run ESLint for all files in the `pages/`, `components/`, and `lib/` directories. However, you can specify which directories using the `dirs` option in the `eslint` config in `next.config.js` for production builds:
...@@ -133,10 +133,10 @@ module.exports = { ...@@ -133,10 +133,10 @@ module.exports = {
} }
``` ```
Similarly, the `--dir` flag can be used for `next lint`: Similarly, the `--dir` and `--file` flags can be used for `next lint` to lint specific directories and files:
```bash ```bash
next lint --dir pages --dir utils next lint --dir pages --dir utils --file bar.js
``` ```
## Caching ## Caching
...@@ -175,7 +175,9 @@ The `next/core-web-vitals` rule set is enabled when `next lint` is run for the f ...@@ -175,7 +175,9 @@ The `next/core-web-vitals` rule set is enabled when `next lint` is run for the f
> The `next/core-web-vitals` entry point is automatically included for new applications built with [Create Next App](/docs/api-reference/create-next-app.md). > The `next/core-web-vitals` entry point is automatically included for new applications built with [Create Next App](/docs/api-reference/create-next-app.md).
## Usage with Prettier ## Usage With Other Tools
### Prettier
ESLint also contains code formatting rules, which can conflict with your existing [Prettier](https://prettier.io/) setup. We recommend including [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) in your ESLint config to make ESLint and Prettier work together. ESLint also contains code formatting rules, which can conflict with your existing [Prettier](https://prettier.io/) setup. We recommend including [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) in your ESLint config to make ESLint and Prettier work together.
...@@ -185,6 +187,19 @@ ESLint also contains code formatting rules, which can conflict with your existin ...@@ -185,6 +187,19 @@ ESLint also contains code formatting rules, which can conflict with your existin
} }
``` ```
### lint-staged
If you would like to use `next lint` with [lint-staged](https://github.com/okonet/lint-staged) to run the linter on staged git files, you'll have to add the following to the `.lintstagedrc.js` file in the root of your project in order to specify usage of the `--file` flag.
```js
module.exports = {
'**/*.js?(x)': (filenames) =>
`next lint --fix --file ${filenames
.map((file) => file.split(process.cwd())[1])
.join(' --file ')}`,
}
```
## Migrating Existing Config ## Migrating Existing Config
### Recommended Plugin Ruleset ### Recommended Plugin Ruleset
......
...@@ -39,6 +39,7 @@ const nextLint: cliCommand = async (argv) => { ...@@ -39,6 +39,7 @@ const nextLint: cliCommand = async (argv) => {
'--help': Boolean, '--help': Boolean,
'--base-dir': String, '--base-dir': String,
'--dir': [String], '--dir': [String],
'--file': [String],
'--strict': Boolean, '--strict': Boolean,
// Aliases // Aliases
...@@ -89,15 +90,16 @@ const nextLint: cliCommand = async (argv) => { ...@@ -89,15 +90,16 @@ const nextLint: cliCommand = async (argv) => {
If not configured, ESLint will be set up for the first time. If not configured, ESLint will be set up for the first time.
Usage Usage
$ next lint <baseDir> [options] $ next lint <baseDir> [options]
<baseDir> represents the directory of the Next.js application. <baseDir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used. If no directory is provided, the current directory will be used.
Options Options
Basic configuration: Basic configuration:
-h, --help List this help -h, --help List this help
-d, --dir Array Set directory, or directories, to run ESLint - default: 'pages', 'components', and 'lib' -d, --dir Array Include directory, or directories, to run ESLint - default: 'pages', 'components', and 'lib'
--file Array Include file, or files, to run ESLint
-c, --config path::String Use this configuration file, overriding all other config options -c, --config path::String Use this configuration file, overriding all other config options
--ext [String] Specify JavaScript file extensions - default: .js, .jsx, .ts, .tsx --ext [String] Specify JavaScript file extensions - default: .js, .jsx, .ts, .tsx
--resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default --resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default
...@@ -147,16 +149,18 @@ const nextLint: cliCommand = async (argv) => { ...@@ -147,16 +149,18 @@ const nextLint: cliCommand = async (argv) => {
const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir) const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir)
const files: string[] = args['--file'] ?? []
const dirs: string[] = args['--dir'] ?? nextConfig.eslint?.dirs const dirs: string[] = args['--dir'] ?? nextConfig.eslint?.dirs
const lintDirs = (dirs ?? ESLINT_DEFAULT_DIRS).reduce( const filesToLint = [...(dirs ?? []), ...files]
(res: string[], d: string) => {
const currDir = join(baseDir, d) const pathsToLint = (
if (!existsSync(currDir)) return res filesToLint.length ? filesToLint : ESLINT_DEFAULT_DIRS
res.push(currDir) ).reduce((res: string[], d: string) => {
return res const currDir = join(baseDir, d)
}, if (!existsSync(currDir)) return res
[] res.push(currDir)
) return res
}, [])
const reportErrorsOnly = Boolean(args['--quiet']) const reportErrorsOnly = Boolean(args['--quiet'])
const maxWarnings = args['--max-warnings'] ?? -1 const maxWarnings = args['--max-warnings'] ?? -1
...@@ -168,7 +172,7 @@ const nextLint: cliCommand = async (argv) => { ...@@ -168,7 +172,7 @@ const nextLint: cliCommand = async (argv) => {
runLintCheck( runLintCheck(
baseDir, baseDir,
lintDirs, pathsToLint,
false, false,
eslintOptions(args, defaultCacheLocation), eslintOptions(args, defaultCacheLocation),
reportErrorsOnly, reportErrorsOnly,
......
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>
)
}
}
...@@ -31,6 +31,7 @@ const dirNoEslintPlugin = join(__dirname, '../no-eslint-plugin') ...@@ -31,6 +31,7 @@ const dirNoEslintPlugin = join(__dirname, '../no-eslint-plugin')
const dirNoConfig = join(__dirname, '../no-config') const dirNoConfig = join(__dirname, '../no-config')
const dirEslintCache = join(__dirname, '../eslint-cache') const dirEslintCache = join(__dirname, '../eslint-cache')
const dirEslintCacheCustomDir = join(__dirname, '../eslint-cache-custom-dir') const dirEslintCacheCustomDir = join(__dirname, '../eslint-cache-custom-dir')
const dirFileLinting = join(__dirname, '../file-linting')
describe('ESLint', () => { describe('ESLint', () => {
describe('Next Build', () => { describe('Next Build', () => {
...@@ -507,5 +508,52 @@ describe('ESLint', () => { ...@@ -507,5 +508,52 @@ describe('ESLint', () => {
expect(fs.existsSync(cacheFile)).toBe(true) expect(fs.existsSync(cacheFile)).toBe(true)
}) })
test('file flag can selectively lint only a single file', async () => {
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--file', 'utils/math.js'],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain('utils/math.js')
expect(output).toContain(
'Comments inside children section of tag should be placed inside braces'
)
expect(output).not.toContain('pages/')
expect(output).not.toContain('External synchronous scripts are forbidden')
})
test('file flag can selectively lints multiple files', async () => {
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--file', 'utils/math.js', '--file', 'pages/bar.js'],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain('utils/math.js')
expect(output).toContain(
'Comments inside children section of tag should be placed inside braces'
)
expect(output).toContain('pages/bar.js')
expect(output).toContain(
"Do not use <img>. Use Image from 'next/image' instead"
)
expect(output).not.toContain('pages/index.js')
expect(output).not.toContain('External synchronous scripts are forbidden')
})
}) })
}) })
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