首页 > 解决方案 > ESLint:为一个具有大规则对象的规则运行 ESLint

问题描述

我试图在我的 React 项目中运行 ESLint 只是为了检查一个特定的(例如:max-len)规则,如下所示:

eslint . --ext .js,.jsx,.ts,.tsx --rule "{'max-len': ['error', { code: 120, ignoreComments: true, ignoreTrailingComments: true, ignoreUrls: true, ignoreStrings: true, ignoreTemplateLiterals: true, }]}"

但结果也显示其他类型错误的错误。

这是我的.eslintrc.js文件:

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'react-app',
    'airbnb',
    'plugin:react/recommended',
    'plugin:import/errors',
    'plugin:import/warnings',
    'plugin:import/typescript',
    'plugin:jsx-a11y/recommended',
  ],
  plugins: [
    'react',
    'jsx-a11y',
    '@typescript-eslint',
  ],
  // parser: 'babel-eslint',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
    },
  },
  rules: {
    'max-len': ['error', {
      code: 120,
      ignoreComments: true,
      ignoreTrailingComments: true,
      ignoreUrls: true,
      ignoreStrings: true,
      ignoreTemplateLiterals: true,
    }],
  },
};

我也尝试过忽略文件.eslintrc.js运行,--no-eslintrc如下所示:

eslint . --ext .js,.jsx,.ts,.tsx --no-eslintrc --rule ....same-rule-above

这次我只得到一个 max-len 错误,其余的是解析 import 关键字的错误:

/Users/olcayertas/10n/src/util/helpers.ts
  1:1  error  Parsing error: The keyword 'import' is reserved

/Users/olcayertas/10n/src/util/routes.ts
  1:1  error  Parsing error: The keyword 'export' is reserved

/Users/olcayertas/10n/src/util/ui-helpers.ts
  1:1  error  Parsing error: The keyword 'import' is reserved

✖ 196 problems (196 errors, 0 warnings)

如何使用规则对象仅针对一条规则运行 ESLint?

标签: javascriptreactjstypescripteslint

解决方案


我找到了问题,这就是答案。因为我们的项目使用的是TypeScript,所以我们需要对eslintrc.js文件进行配置,所以 using--no-eslintrc不起作用。相反,我们禁用了扩展规则(不是插件):

module.exports = {
  ...
  extends: [
    'plugin:import/errors',
    'plugin:import/warnings',
    'plugin:import/typescript',
    //'plugin:react/recommended',
    //'arbnb',
  ],
  rules: {
    'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx', '.ts', '.tsx'] }],
    'import/prefer-default-export': 'off',
    'import/no-unresolved': ['error', { ignore: [ '.svg' ] } ],
    'import/extensions': [
      'error',
      'ignorePackages',
      {
        js: 'never',
        jsx: 'never',
        ts: 'never',
        tsx: 'never',
      },
    ],
  },
}

由于我想查看导入错误,因此我为导入启用了插件和规则。禁用扩展规则后,我运行以下命令:

eslint . --ext .js,.jsx,.ts,.tsx

而且效果很好!这样我们可以逐步添加规则。


推荐阅读