2021 年如何在 VS Code 中的 Razzle、React 和 TypeScript 项目中使用 ESLint 和 Prettier?

How to use ESLint and Prettier within a Razzle, React and TypeScript project inside VS Code in 2021?

我想在一个项目中同时使用 ESLint 和 Prettier,该项目在 VS Code 中同时使用 React 和 TypeScript(通过 Razzle,如果相关的话)。我还没有关于代码风格和格式的偏好,但我希望有一些常识。以下是我的配置文件。我坚持认为我对代码风格和格式没有明确的品味,我希望有一些好的默认值。

我已经安装了 ESLint 和 Prettier VS Code 扩展。

在项目中我安装了以下包:

"@typescript-eslint/eslint-plugin": "^4.28.0",
"@typescript-eslint/parser": "^4.28.0",
"eslint": "^7.29.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-config-prettier": "^8.3.0",
"eslint-import-resolver-typescript": "^2.4.0",
"eslint-plugin-import": "^2.23.4",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-react": "^7.24.0",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-webpack-plugin": "^2.5.4",
"razzle-plugin-eslint": "^4.0.4",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"prettier": "^1.19.1",

我有以下问题:

  1. Prettier 尝试在字符串周围放置双引号,而 ESLint 尝试在字符串周围放置单引号。我做了一个更改,相反的显示为推荐的字符串下方的红色波浪形。

总的来说,我希望在 .tsx 文件中有通用的样式和 linting。其他的就没那么重要了。我看过 a YouTube video 关于这个,但它是从 2018 年开始的,现在对我来说似乎不起作用。

.eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    "prettier",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:@typescript-eslint/recommended-requiring-type-checking",
    "airbnb"
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: "./tsconfig.json",
    tsconfigRootDir: "./",
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: [
    "prettier",
    'react',
    '@typescript-eslint',
    "import",
  ],
  rules: {
    "prettier/prettier": ["error"],
    'import/extensions': ['off'],
    'react/jsx-filename-extension': [1, { extensions: ['.tsx', '.jsx'] }],
    'import/prefer-default-export': [0],
    'import/order': [0],
  },
  settings: {
    "import/resolver": {
      "typescript": {},
    },
  },
};

.prettierrc.json

{}

谢谢。

npm i -D eslint-config-prettier

...

// .eslintrc.json

"extends": [
  ...
  "prettier"
],

该包旨在禁用干扰 prettier 的 eslint 规则。之后你实际上需要配置你的.prettierrc.json,目前它是空的。

// .prettierrc.json

{
  "singleQuote": false,
}