我在我的项目中使用 Prettier、Eslint 和 Styled 组件。 eslint 规则到目前为止正在发挥作用。我不知道为什么,但 Prettier 没有格式化样式组件代码。
让我向您展示我正在尝试修复的示例代码:
这是原始代码:
import { createGlobalStyle } from 'styled-components';
export const GlobalStyles = createGlobalStyle`
* {
box-sizing: border-box;
}
body {
font-size: 1.15em;
margin: 0;
}
`;
这是我期望通过 Prettier 和 Eslint 格式化后获得的代码(但我不是):
import { createGlobalStyle } from 'styled-components';
export const GlobalStyles = createGlobalStyle`
* {
box-sizing: border-box;
}
body {
font-size: 1.15em;
margin: 0;
}
`;
我的 eslintrc.json:
{
"env": {
"browser": true,
"es2021": true,
"jest": true
},
"extends": [
"next/core-web-vitals",
"eslint:recommended",
"plugin:jsx-a11y/recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"project": "tsconfig.json",
"sourceType": "module"
},
"plugins": ["@typescript-eslint/eslint-plugin", "react", "prettier"],
"rules": {
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off",
"no-shadow": "off"
},
"ignorePatterns": ["dist", "node_modules"]
}
我的.prettierrc:
{
"arrowParens": "always",
"printWidth": 120,
"semi": true,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "es5",
"useTabs": false
}
任何修改或建议都将受到欢迎。那么有没有什么办法可以正确解决这个问题呢?感谢您的帮助!
最佳答案
我读到here这似乎是代码编辑器格式问题。我找到了 4 种可能的解决方案。
正确配置代码编辑器扩展(但不确定此/您的情况存在什么问题)
按 Opt+Shift+F 并选择代码编辑器
按照上面的 github 链接中建议的解决方法,执行以下操作:
import * as styled from 'styled-components';
export default styled.createGlobalStyle`
body {
margin: 0;
}
code {
font-family: comic-sans-ms;
}
`;
- 另一种解决方法:
const xyz = css`
body {
background: red;
}
`;
/* ↑ gets formatted by Prettier */
createGlobalStyle`
${xyz}
`;
关于reactjs - Prettier 没有格式化我的样式组件代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73464603/