reactjs - Prettier 没有格式化我的样式组件代码

标签 reactjs formatting eslint styled-components prettier

我在我的项目中使用 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 种可能的解决方案。

  1. 正确配置代码编辑器扩展(但不确定此/您的情况存在什么问题)

  2. 按 Opt+Shift+F 并选择代码编辑器

  3. 按照上面的 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/

    相关文章:

    reactjs - 在 react redux 中的全局状态更改后调度新 Action

    visual-studio-code - ESLint 自动修复忽略规则

    reactjs - 为什么 eslint-plugin-react-hooks 在有条件地使用 React hooks 时不会发出警告?

    reactjs - 获取 Fluent UI DetailsList 中的选定项目

    javascript - 为什么我的 reducer 在 react/redux 中返回一个空数组?

    reactjs - 如何通过单击其他元素来添加和删除元素的类?在 React-redux 中

    formatting - 在 Redmine wiki 页面中插入特殊字符

    intellij-idea - 在 PyCharm 中用换行符包装注释

    excel - VBA 不会改变所有单元格的格式

    node.js - Eslint 无法识别使用 nodejs 12 的私有(private)字段声明