Skip to content

Commit

Permalink
Flat config: CLI, tests, docs (#261)
Browse files Browse the repository at this point in the history
  • Loading branch information
lydell committed Aug 5, 2023
1 parent baab944 commit a8bc57e
Show file tree
Hide file tree
Showing 14 changed files with 438 additions and 164 deletions.
4 changes: 2 additions & 2 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
!/.*
/build/
/test-config/
build/**
test-config/**
6 changes: 4 additions & 2 deletions .eslintrc.base.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

// This file is only used in `./.eslintrc.js` and in the tests – it’s not part
// of the eslint-config-prettier npm package.
//
// NOTE: Keep this file in sync with `./eslint.base.config.js`!

const config = require(".");

Expand Down Expand Up @@ -40,7 +42,7 @@ module.exports = {
"indent": "off",
"linebreak-style": "off",
"no-dupe-keys": "error",
"strict": "error",
"strict": ["error", "global"],
"prefer-spread": "off",
"require-jsdoc": "off",
"prettier/prettier": "error",
Expand Down Expand Up @@ -74,7 +76,7 @@ module.exports = {
},
overrides: [
{
files: ["*.ts", "*.tsx"],
files: ["**/*.{ts,tsx}"],
parserOptions: { parser: "@typescript-eslint/parser" },
rules: {
// Force a conflict with Prettier in test-lint/typescript.js.
Expand Down
4 changes: 3 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
// sharable config from npm and then include the configs exposed by this package
// as an “eat your own dogfood” test. That feels like a good test, but
// complicates things a little sometimes.
//
// NOTE: Keep this file in sync with `./eslint.config.js`!

module.exports = {
extends: ["./.eslintrc.base.js", "./index.js", "./prettier.js"],
Expand Down Expand Up @@ -32,7 +34,7 @@ module.exports = {
},
},
{
files: ["*.test.js"],
files: ["**/*.test.js"],
env: { jest: true },
},
],
Expand Down
7 changes: 6 additions & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,14 @@ jobs:
if: steps.cache-node_modules.outputs.cache-hit != 'true'
run: npm ci --no-audit

- name: ESLint
- name: ESLint - flat
run: npx eslint .

- name: ESLint - eslintrc
run: npx eslint .
env:
ESLINT_USE_FLAT_CONFIG: "false"

- name: Prettier
run: npx prettier --check .

Expand Down
23 changes: 20 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,28 @@ jobs:
if: steps.cache-node_modules.outputs.cache-hit != 'true'
run: npm ci --no-audit

- name: Jest
- name: Jest - flat
run: npx jest
env:
ESLINT_CONFIG_PRETTIER_NO_DEPRECATED: "true"

- name: CLI sanity
- name: Jest - eslintrc
run: npx jest
env:
ESLINT_USE_FLAT_CONFIG: "false"

- name: CLI sanity - flat
run: npm run test:cli-sanity

- name: CLI sanity - eslintrc
run: npm run test:cli-sanity
env:
ESLINT_USE_FLAT_CONFIG: "false"

- name: CLI sanity warning - flat
run: npm run test:cli-sanity-warning

- name: CLI sanity warning
- name: CLI sanity warning - eslintrc
run: npm run test:cli-sanity-warning
env:
ESLINT_USE_FLAT_CONFIG: "false"
166 changes: 136 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,46 @@ Note that this config _only_ turns rules _off,_ so it only makes sense using it

## Installation

Install eslint-config-prettier:
1. Install eslint-config-prettier:

```
npm install --save-dev eslint-config-prettier
```
```
npm install --save-dev eslint-config-prettier
```

Then, add `"prettier"` to the "extends" array in your `.eslintrc.*` file. Make sure to put it **last,** so it gets the chance to override other configs.
2. Add eslint-config-prettier to your ESLint configuration – either to [eslintrc] or to [eslint.config.js (flat config)].

<!-- prettier-ignore -->
```json
{
"extends": [
"some-other-config-you-use",
"prettier"
]
}
```
- eslintrc: Add `"prettier"` to the "extends" array in your `.eslintrc.*` file. Make sure to put it **last,** so it gets the chance to override other configs.

<!-- prettier-ignore -->
```json
{
"extends": [
"some-other-config-you-use",
"prettier"
]
}
```

- eslint.config.js (flat config): Import eslint-config-prettier, and put it in the configuration array – **after** other configs that you want to override.

<!-- prettier-ignore -->
```js
import someConfig from "some-other-config-you-use";
import eslintConfigPrettier from "eslint-config-prettier";

Finally, run the [CLI helper tool](#cli-helper-tool) to find problems in the `"rules"` section of your `.eslintrc.*` file. (Remember, `"rules"` always “wins” over `"extends"`!)
export default [
someConfig,
eslintConfigPrettier,
];
```

Extending `"prettier"` turns off a bunch of core ESLint rules, as well as a few rules from these plugins:
3. Finally, run the [CLI helper tool](#cli-helper-tool) to find problems in the `"rules"` sections of your config.

> 👉 Using [eslint-plugin-prettier]? Check out [eslint-plugin-prettier’s recommended config][eslint-plugin-prettier-recommended].
### Plugins

eslint-config-prettier not only turns off _core_ rules, but also some from these plugins automatically:

- [@typescript-eslint/eslint-plugin]
- [@babel/eslint-plugin]
Expand All @@ -41,10 +60,43 @@ Extending `"prettier"` turns off a bunch of core ESLint rules, as well as a few
- [eslint-plugin-unicorn]
- [eslint-plugin-vue]

> 👉 Using [eslint-plugin-prettier]? Check out [eslint-plugin-prettier’s recommended config][eslint-plugin-prettier-recommended].
> ℹ️ Note: You might find guides on the Internet saying you should also extend stuff like `"prettier/react"`. Since version 8.0.0 of eslint-config-prettier, all you need to extend is `"prettier"`! That includes all plugins.
#### eslint.config.js (flat config) plugin caveat

With flat config, _you_ get to decide the plugin name! For example:

```js
import typescriptEslint from "@typescript-eslint/eslint-plugin";
import eslintConfigPrettier from "eslint-config-prettier";

export default [
{
plugins: {
// You’d typically use one of the following two:
// typescriptEslint: typescriptEslint,
// typescriptEslint,
// But in this example we give it another name.
// It might be tempting to use something shorter like “ts”:
ts: typescriptEslint, // 🚨 Don’t do this!
},
rules: {
// With eslintrc, this is _always_ called:
// @typescript-eslint/indent
// But in eslint.config.js (flat config), the name chosen above in `plugins` is used.
"ts/indent": "error", // 🚨 Don’t do this!
},
},
eslintConfigPrettier,
];
```

You might expect eslint-config-prettier to turn off `ts/indent`, but it won’t! Because eslint-config-prettier only turns off `@typescript-eslint/indent`. It cannot know what you chose to call the plugin. Same thing for the CLI helper tool.

Simply stick to the official plugin names and you’ll be all good.

If you encounter a shared _config_ that uses a non-standard plugin name, please ask them to use the standard name instead.

### Excluding deprecated rules

Some of the rules that eslint-config-prettier turns off may be deprecated, or even removed from ESLint. **This is perfectly fine,** but if you really need to omit the deprecated and removed rules, you can do so by setting the `ESLINT_CONFIG_PRETTIER_NO_DEPRECATED` environment variable to a non-empty value. For example:
Expand All @@ -55,9 +107,19 @@ env ESLINT_CONFIG_PRETTIER_NO_DEPRECATED=true npx eslint-find-rules --deprecated

## CLI helper tool

eslint-config-prettier also ships with a little CLI tool to help you check if your configuration contains any rules that are unnecessary or conflict with Prettier.
eslint-config-prettier also ships with a little CLI tool to help you check if your configuration contains any rules that are unnecessary or conflict with Prettier. Here’s how to run it:

```
npx eslint-config-prettier path/to/main.js
```

(Change `path/to/main.js` to a file that exists in your project.)

### What and why

Now, let’s have a look at what it does and why you might want to use it.

🚨 This example has a **conflicting rule** `"indent"` enabled:
🚨 This eslintrc example has a **conflicting rule** `"indent"` enabled:

<!-- prettier-ignore -->
```json
Expand All @@ -72,28 +134,69 @@ eslint-config-prettier also ships with a little CLI tool to help you check if yo
}
```

While the `"prettier"` config can disable problematic rules in `"some-other-config-you-use"`, it cannot touch `"rules"`! (That’s how ESLint works – it lets you override configs you extend.) The CLI helper tool reports that `"indent"` conflicts with Prettier, so you can remove it. (Which is nice – simplifying your config!)
For eslintrc, while the `"prettier"` config can disable problematic rules in `"some-other-config-you-use"`, it cannot touch `"rules"`! (That’s how ESLint works – it lets you override configs you extend.) The CLI helper tool reports that `"indent"` conflicts with Prettier, so you can remove it. (Which is nice – simplifying your config!)

You can run it using `npx`:
🚨 This eslint.config.js (flat config) example also has a **conflicting rule** `"indent"` enabled:

```js
import someConfig from "some-other-config-you-use";
import eslintConfigPrettier from "eslint-config-prettier";

export default [
someConfig,
eslintConfigPrettier,
{
rules: {
indent: "error",
},
},
];
```
npx eslint-config-prettier path/to/main.js

With the new ESLint “flat config” format, you can control what things override what yourself. One way of solving the above conflict is to reorder the config objects so that eslint-config-prettier is last:

```js
import someConfig from "some-other-config-you-use";
import eslintConfigPrettier from "eslint-config-prettier";

export default [
someConfig,
{
rules: {
indent: "error",
},
},
eslintConfigPrettier, // eslint-config-prettier last
];
```

(Change `path/to/main.js` to a file that exists in your project.)
However, looking at the above config might feel confusing. It looks like we enable the `indent` rule, but in reality it’s disabled thanks to the `eslintConfigPrettier` line below it. Instead you might want to actually have your own rules _after_ eslint-config-prettier and run the CLI helper tool to find out about problems, so you can remove conflicting rules from the config file altogether (simplifying your config).

### Checking multiple files

In theory you need to run the tool for every single file in your project to be 100% sure that there are no conflicting rules, because ESLint supports having different rules for different files. Usually you’ll have about the same rules for all files, so it is good enough to run the command on one file. But if you use [multiple configuration files] or [overrides], you can provide several files check:
In theory you need to run the tool for every single file in your project to be 100% sure that there are no conflicting rules, because ESLint supports having different rules for different files. Usually you’ll have about the same rules for all files, so it is good enough to run the command on one file. But if you use [multiple configuration files] or [overrides], you can provide several files to check:

```
npx eslint-config-prettier index.js test/index.js legacy/main.js
```

Exit codes:
### Exit codes

- 0: No problems found.
- 1: Unexpected error.
- 2: Conflicting rules found.

### ESLINT_USE_FLAT_CONFIG environment variable

Just like ESLint itself, you can control the eslint-config-prettier CLI helper tool using the `ESLINT_USE_FLAT_CONFIG` environment variable:

- `ESLINT_USE_FLAT_CONFIG=true`: Only use eslint.config.js (flat config).
- `ESLINT_USE_FLAT_CONFIG=false`: Only use eslintrc files.
- Unset or any other value: First try eslint.config.js, then eslintrc.

> **Warning**
> For eslint.config.js (flat config), the CLI helper tool imports `eslint/use-at-your-own-risk` which may break at any time.
### Legacy

eslint-config-prettier versions before 7.0.0 had a slightly different CLI tool that was run in a different way. For example:
Expand Down Expand Up @@ -664,17 +767,18 @@ Then, create `test-lint/foobar.js`:
console.log();
```

`test-lint/foobar.js` must fail when used with eslint-plugin-foobar and eslint-plugin-prettier at the same time – until `"prettier/foobar"` is added to the "extends" property of an ESLint config. The file should be formatted according to Prettier, and that formatting should disagree with the plugin.
`test-lint/foobar.js` must fail when used with eslint-plugin-foobar and eslint-plugin-prettier at the same time – until eslint-config-prettier is added to the ESLint config. The file should be formatted according to Prettier, and that formatting should disagree with the plugin.

Finally, you need to mention the plugin in several places:

- Add eslint-plugin-foobar to the "devDependencies" field in `package.json`.
- Make sure that at least one rule from eslint-plugin-foobar gets used in `.eslintrc.base.js`.
- Add it to the lists of supported plugins and in this `README.md`.
- Make sure that at least one rule from eslint-plugin-foobar gets used in `.eslintrc.base.js` and `eslint.base.config.js`.
- Add it to the lists of supported plugins in this `README.md`.

When you’re done, run `npm test` to verify that you got it all right. It runs several other npm scripts:

- `"test:lint"` makes sure that the files in `test-lint/` pass ESLint when the exclusions from eslint-config-prettier are used. It also lints the code of eslint-config-prettier itself, and checks that Prettier has been run on all files.
- `"test:prettier"` checks that Prettier has been run on all files.
- `"test:eslint"` makes sure that the files in `test-lint/` pass ESLint when the exclusions from eslint-config-prettier are used. It also lints the code of eslint-config-prettier itself.
- `"test:lint-verify-fail"` is run by a test in `test/lint-verify-fail.test.js`.
- `"test:lint-rules"` is run by a test in `test/rules.test.js`.
- `"test:jest"` runs unit tests that check a number of things:
Expand Down Expand Up @@ -703,6 +807,8 @@ When you’re done, run `npm test` to verify that you got it all right. It runs
[eslint-plugin-standard]: https://github.com/xjamundx/eslint-plugin-standard
[eslint-plugin-unicorn]: https://github.com/sindresorhus/eslint-plugin-unicorn
[eslint-plugin-vue]: https://github.com/vuejs/eslint-plugin-vue
[eslint.config.js (flat config)]: https://eslint.org/docs/latest/use/configure/configuration-files-new
[eslintrc]: https://eslint.org/docs/latest/use/configure/configuration-files
[lines-around-comment]: https://eslint.org/docs/rules/lines-around-comment
[max-len]: https://eslint.org/docs/rules/max-len
[multiple configuration files]: https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy
Expand Down
39 changes: 34 additions & 5 deletions bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,19 @@ const prettier = require("../prettier");

// Require locally installed eslint, for `npx eslint-config-prettier` support
// with no local eslint-config-prettier installation.
const { ESLint } = require(require.resolve("eslint", {
paths: [process.cwd(), ...require.resolve.paths("eslint")],
}));
const localRequire = (request) =>
require(require.resolve(request, {
paths: [process.cwd(), ...require.resolve.paths("eslint")],
}));

let experimentalApi = {};
try {
experimentalApi = localRequire("eslint/use-at-your-own-risk");
// eslint-disable-next-line unicorn/prefer-optional-catch-binding
} catch (_error) {}

const { ESLint, FlatESLint = experimentalApi.FlatESLint } =
localRequire("eslint");

const SPECIAL_RULES_URL =
"https://github.com/prettier/eslint-config-prettier#special-rules";
Expand All @@ -27,8 +37,27 @@ if (module === require.main) {
}

const eslint = new ESLint();

Promise.all(args.map((file) => eslint.calculateConfigForFile(file)))
const flatESLint = FlatESLint === undefined ? undefined : new FlatESLint();

Promise.all(
args.map((file) => {
switch (process.env.ESLINT_USE_FLAT_CONFIG) {
case "true": {
return flatESLint.calculateConfigForFile(file);
}
case "false": {
return eslint.calculateConfigForFile(file);
}
default: {
// This turns synchronous errors (such as `.calculateConfigForFile` not existing)
// and turns them into promise rejections.
return Promise.resolve()
.then(() => flatESLint.calculateConfigForFile(file))
.catch(() => eslint.calculateConfigForFile(file));
}
}
})
)
.then((configs) => {
const rules = configs.flatMap(({ rules }, index) =>
Object.entries(rules).map((entry) => [...entry, args[index]])
Expand Down

0 comments on commit a8bc57e

Please sign in to comment.