插入 `··` prettier/prettier

30
我有一个项目,同时安装了prettier和eslint。问题是,当我保存文件时,eslint会自动更改文件的格式,并且似乎有一些规则与prettier冲突。解决方案是什么?
这是prettier格式: 进入图像描述 保存后,文件会变成这样: 进入图像描述 此外,这是eslintrc文件。
{
  "parser": "@typescript-eslint/parser",
  "extends": [
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier/@typescript-eslint"
  ],
  "rules": {
    "@typescript-eslint/explicit-function-return-type": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/ban-ts-ignore": "off",
    "@typescript-eslint/interface-name-prefix": "off",
    "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }]
  },
  "overrides": [
    {
      "files": ["**/*.tsx"],
      "rules": {
        "react/prop-types": "off"
      }
    }
  ],
  "settings": {
    "react": {
      "version": "detect"
    }
  },
  "ignorePatterns": ["coverage/", "node_modules/", "src/serviceWorker.ts"]
}
6个回答

21

2
你至少为我节省了45分钟的时间:) 谢谢。 - Nostromo

2
尝试将VSCode的默认格式化程序更改为ESLint:
1. 通过VSCode命令行进行操作: - 打开“转到文件”命令行 - 输入并搜索:
> format Document With

将您的默认格式化工具更改为报告错误的工具。

enter image description here

2. 通过进入设置,搜索 格式化程序,将其更改为 ESLint 或其他能够报告错误的工具。

1

.prettierrc

{
  "printWidth": 160
}

1
这个问题是由prettier中的endOfLine规则引起的。行尾可以是LF、CR或CRLF。错误消息与此问题有关。当您创建新行并且其中一个行尾字符(LF、CR或CRLF)被自动添加到前一行的末尾以表示行尾时,就会出现此错误。这可能因您使用的操作系统而异。
要解决此问题,您可以将以下代码添加到.eslintrc.js文件的rules数组中。
// .. 
rules:[
//  ... other rules here
prettier/prettier': [
  'error',  // alternativly change to 'warn' if you want only warning 
  {
    endOfLine: 'auto',   <---- this is the solution
    // ... put other prettier rules here like "semi":flase,
  },
],

]


0
我本地上传了最新版本的prettier。
npm install --save-dev --save-exact prettier

然后检查一切是否如预期般顺利。
npm view prettier version 

然后接受了VS Code提出的快速修复方案,一切都很好。

-1

一个解决方法是使用加法运算符(+)连接字符串,而不是使用模板字符串:

try {
  const response = await api.get(
    API_BOARDS +
      boardSearchParam.boardId +
      `?assignees=${boardSearchParam.assigneeIds.toString()}/`
  );
} catch (err) {
  // ...
}

根据您的ESLint规则,您可能会收到一个错误,提示您应该使用模板字符串而不是加法运算符。在这种情况下,您可以创建一个变量并使用加法赋值运算符(+=):
try {
  let url = API_BOARDS + boardSearchParam.boardId;
  url += `?assignees=${boardSearchParam.assigneeIds.toString()}/`

  const response = await api.get(url);
} catch (err) {
  // ...
}

这只是个人口味问题,但我认为这样阅读起来更加舒适。


1
为什么要踩?问题是“解决方案是什么?”一个解决方案是使用加法运算符和/或加法分配运算符,而不是模板字符串。 - Matias Kinnunen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接