如何在 VSCode 中的同一项目中的 .ts 文件和 .js 文件上运行 typescript-eslint

Ben*_*Ben 21 javascript typescript eslint visual-studio-code

我有一个包含 javascript 和 typescript 文件的混合代码库。我想让 eslint 在 .js 文件上运行,而 typescript-eslint 在 VSCode 中的 .ts 文件上运行。

我已经成功配置了我的 .eslintrc.json 文件来让 typescript-eslint 在 .ts 文件上运行。问题是它最终也会在 .js 文件上运行 typescript-eslint,而不是普通的旧 eslint。

这看起来应该很简单而且相当普遍,但尽管在互联网上搜索,我仍然无法找到解决方案。

Sat*_*jan 33

您需要覆盖配置以对 js 和 ts文件使用单独的解析器。你可以配置 .eslintrc.js 如下

module.exports = {
    root: true,    
    extends: [
      'eslint:recommended'
    ],
    "overrides": [
      {
        "files": ["**/*.ts", "**/*.tsx"],
        "env": { "browser": true, "es6": true, "node": true },
        "extends": [
          "eslint:recommended",
          "plugin:@typescript-eslint/eslint-recommended",
          "plugin:@typescript-eslint/recommended"
        ],
        "globals": { "Atomics": "readonly", "SharedArrayBuffer": "readonly" },
        "parser": "@typescript-eslint/parser",
        "parserOptions": {
          "ecmaFeatures": { "jsx": true },
          "ecmaVersion": 2018,
          "sourceType": "module",
          "project": "./tsconfig.json"
        },
        "plugins": ["@typescript-eslint"],
        "rules": {
          "indent": ["error", 2, { "SwitchCase": 1 }],
          "linebreak-style": ["error", "unix"],
          "quotes": ["error", "single"],
          "comma-dangle": ["error", "always-multiline"],
          "@typescript-eslint/no-explicit-any": 0
        }
      }
    ]
  };
Run Code Online (Sandbox Code Playgroud)

示例项目在这里

  • 该项目的死链接。请更新。 (4认同)

Hug*_*sen 15

使用overrides属性仅在文件上具有typescript-eslint的解析器和相关 TS 配置.ts/.tsx。例如(React、TypeScript、ES2021):

module.exports = {
  root: true,
  extends: ['eslint:recommended'],
  env: {
    browser: true,
    es2021: true,
  },
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  overrides: [
    {
      files: ['**/*.ts', '**/*.tsx'],
      plugins: [
        '@typescript-eslint',
      ],
      extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
      parser: '@typescript-eslint/parser',
      parserOptions: {
        project: ['./tsconfig.json'],
      },
    },
  ],
};
Run Code Online (Sandbox Code Playgroud)