Search code examples
reactjseslintprettier

ESLint & Prettier config for line break after each functions?


I'm currently set up my project using ESLint and Prettier.

I would like to know if there's a way to format this code...

const Demo = () => {
  const [state, setState] = useState(false);
  const [num, setNum] = useState(10);
  useEffect(() => {
    //...
  },[])
  useEffect(() => {
    //...
  },[state])
  const handleSubmit = () => {
  }
  return (
  //...
  )

}

into this...

const Demo = () => {
  const [state, setState] = useState(false);
  const [num, setNum] = useState(10);

  useEffect(() => {
    //...
  },[])

  useEffect(() => {
    //...
  },[state])

  const handleSubmit = () => {
  }

  return (
  //...
  )

}

Here's my .prettierrc file looks like

{
  "printWidth": 100,
  "semi": false,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "all",
  "endOfLine": "auto"
}

I tried like almost every config but I can't format the code desired way. I appreciate it if someone could help to figure this out.


Solution

  • Noting that eslint is for styling and prettier is for formatting, so the responsibility for this lies with prettier.

    I have looked into this before, prettier does not have that option, here is a list of the options which are available

    However i just read that padding-line-between-statements is possible with eslint which may do the job FYI TS-ESlint recommend not using this rule - again formatting is the job of a formatter, not a linter like eslint.

    This would be how to implement the rule in your eslintrc file, the configuration is an object which has 3 properties; blankLine, prev and next. For example, { blankLine: "always", prev: "var", next: "return" } means "one or more blank lines are required between a variable declaration and a return statement."

    "padding-line-between-statements": [
        "error",
        { blankLine: "always", prev: "export", next: "*" },
        { blankLine: "always", prev: "import", next: "*" },
        { blankLine: "always", prev: "var", next: "*" },
    ]