使用 Prettier 在 VS Code for TypeScript 中快速修复操作

Quick Fix actions in VS Code for TypeScript using Prettier

我有一个通过 Babel 编译 TypeScript 的设置。此外,我还为 linting/formatting 设置了 ESLint 和 Prettier。 ESLint 配置为使用来自 @typescript-eslint/parser 的解析器 - 不涉及 TSLint。

ESLint 正确应用了 Prettier 规则,并在 VS Code 中向我展示了常规 JavaScript 和 TypeScript 的波浪线。但是,只有常规 JavaScript 在 VS 代码工具提示中的 "Quick Fix..." 选项下可以执行任何操作。对于 TypeScript 文件,Prettier 问题总是显示 "No code actions available"。有没有办法让 Prettier 的快速修复也适用于 TypeScript 文件?

这是我的配置文件:

.eslintrc

{
  "extends": [
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier/@typescript-eslint",
    "prettier/react"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "sourceType": "module",
    "ecmaVersion": 2018,
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "plugins": ["@typescript-eslint"],
  "env": {
    "browser": true,
    "jest": true
  }
}

.prettierrc.js

module.exports = {
  printWidth: 120,
  semi: true,
  singleQuote: true,
  tabWidth: 2,
  trailingComma: 'all',
};

babel.config.js

module.exports = api => {
  api.cache.invalidate(() => process.env.NODE_ENV === 'production');

  const presets = ['@babel/env', '@babel/typescript', '@babel/react'];

  const plugins = ['@babel/proposal-class-properties', '@babel/proposal-object-rest-spread'];

  if (process.env.NODE_ENV === 'development') {
    plugins.push('react-hot-loader/babel');
  }

  return {
    presets,
    plugins,
  };
};

这对我有用,添加到我的 settings.json:

"eslint.validate": [
    "javascript",
    "javascriptreact",
    {
        "language": "typescript",
        "autoFix": true
    },
    {
        "language": "typescriptreact",
        "autoFix": true
    }
],

我在这个项目中没有使用 Prettier,所以 YMMV。

更新:如果这不起作用,您可能还需要这个:

"eslint.options": {
  "extensions": [".js", ".jsx", ".ts", ".tsx"]
}