如何配置Prettier/Eslint保留大括号前后的换行?
Great question! Let's break down how to tweak your Prettier + ESLint setup to get the exact arrow function formatting you want in React's render method.
First, let's clarify the two key formatting differences you're seeing:
- Prettier removes the space after the JSX attribute's opening
{(turning{ (e)into{(e)) - Prettier adds a space inside the arrow function's block braces (turning
{console.log(...)}into{ console.log(...) })
Here's how to fix both:
1. Fix JSX curly brace spacing (keep the space after {)
Prettier's default behavior for JSX attributes is to omit the space after { for inline expressions. To override this, we'll use an ESLint rule since Prettier doesn't have a native setting for this specific JSX case.
Add this rule to your .eslintrc.js (or equivalent config file):
rules: { "react/jsx-curly-spacing": ["error", { "when": "always", "children": true, // Optional: If you don't want spaces inside object literals in JSX, add this line // "spacing": { "objectLiterals": "never" } }] }
This will enforce spaces inside JSX curly braces, so onClick={ (e) => ... } stays intact instead of getting condensed to onClick={(e) => ... }.
2. Remove space inside arrow function block braces
Prettier enforces spaces inside block braces by default, but we can use ESLint's block-spacing rule to reverse this. Add this to your ESLint rules:
rules: { // ... other rules "block-spacing": ["error", "never"] }
This will make sure {console.log('Hello, world!');} stays as-is instead of getting a space added after the opening brace.
3. Make sure Prettier-ESLint runs in the right order
Since you're using the Prettier-ESLint VSCode extension, ensure it's set as your default formatter. The extension runs Prettier first, then applies ESLint fixes on top—so our ESLint rules will correct the formatting to match your desired style.
Bonus: Control line breaks
If Prettier was wrapping your arrow function onto multiple lines (and you want it to stay single-line), bump up the printWidth value in your .prettierrc:
{ "printWidth": 120 // Adjust to a value that fits your code }
This gives Prettier more room to keep short expressions on one line before wrapping.
A quick note: Prettier is opinionated by design, so we're using ESLint to override specific rules here. Just make sure your ESLint config doesn't have conflicting rules (you can use eslint-config-prettier to disable ESLint rules that clash with Prettier, except for the ones we're explicitly using to adjust formatting).
内容的提问来源于stack exchange,提问作者FizzyGalacticus

