简体   繁体   中英

how to fix indent eslint error in nested styled-components?

How to fix this eslint error?

I want to write below format.

const Hoge = styled.div`
  ...

  .class {
    color: ${props =>
      props.a !== 'aaaaaa' &&
      props.b !== 'bbbbbb' &&
      '#ccc'};
  }
`

But this format has eslint error.

在此处输入图像描述

error: [eslint] Expected indentation of 4 spaces but found 6. (indent)

I'd like to know about fix this.

I'm using below versions.

"styled-components": "^3.1.6",
"eslint": "^4.17.0",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-prettier": "^2.6.0",
"prettier": "^1.10.2",
"prettier-eslint": "^8.8.1",

And eslint setting for indent is just below.

 "indent": ["error", 2, { "SwitchCase": 1 }],

First, eslint's indent rule is working correctly, see here . If you want to continue to use styled-components and adhere to your linter configurations for indent the easiest solution is to probably not write the interpolation function inline, but instead assign it to a variable.

For example:

const getColorForClass = ({ a, b }) => {
  return a !== 'aaaaaa' && b !== 'bbbbbb' && '#ccc'
}

const Hoge = styled.div`
  .class {
    color: ${getColorForClass};
  }
`

By adding an exception to the eslint config, I'm able to ignore the relevant blocks so that autofix doesn't trash the identation. You still have to manage it manually but at least it's keeps what you write

In .eslintrc.js :

const styledComponentArrowFn =
  'TaggedTemplateExpression > TemplateLiteral > ArrowFunctionExpression';

const ignoredNodes = [
  styledComponentArrowFn,
  `${styledComponentArrowFn} > BlockStatement`,
];

module.exports = {
  rules: {
    'indent': ['error', 2, {
      ignoredNodes,
    }],
  }
}

Reference: https://eslint.org/docs/rules/indent#ignorednodes

I wanna point out this needs to fix some if/case to properly handle success/error case, otherwise you'll end up with

.class {
  color:
}

So I suggest this approach, and fortunately it solve the eslint issue itself.

.class {
  ${props =>
    props.a !== 'aaaaaa' &&
    props.b !== 'bbbbbb' && 'color: #ccc'
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM