如何使用 EXTEND_ESLINT 环境变量扩展 CRA ESLint 规则

sid*_*son 10 javascript npm eslint create-react-app

最近 Facebook 的 Create React App (CRA) 发布了一项新功能,允许您扩展他们的基本 ESLint 规则。

我们认识到,在某些情况下,需要进一步定制。现在可以通过将 EXTEND_ESLINT 环境变量设置为 true 来扩展基本 ESLint 配置。 设置你的编辑器

这是给出的示例,但没有详细信息,例如文件名或“共享配置”是什么。

{
    "eslintConfig": {
        "extends": ["react-app", "shared-config"],
        "rules": {
            "additional-rule": "warn"
        },
        "overrides": [
            {
                 "files": ["**/*.ts?(x)"],
                 "rules": {
                     "additional-typescript-only-rule": "warn"
                 }
             }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

该功能是通过添加环境变量启用的。

EXTEND_ESLINT=true
Run Code Online (Sandbox Code Playgroud)

但在文档页面上它也没有提供任何信息如何使用它 -高级配置

我已将他们的示例代码添加到我的构建文件中,.eslintrc.json但我收到了构建错误:

"错误:.eslintrc.json 中的 ESLint 配置无效:- 意外的顶级属性 "eslintConfig"。 "

有没有人让这个工作?该文件是否需要导出模块?

Emi*_*ron 12

虽然从Create-React-App 文档中不清楚,但他们给出的例子好像项目的 ESLint 配置eslintConfigpackage.json文件的属性内。

您需要按照其文档中的描述配置 ESLint。所以如果你选择这种.eslintrc.json方式,它必须是一个有效的 ESLint 配置文件,它没有eslintConfig属性。

示例中唯一重要的是:

  • 它们是"react-app"在任何其他配置之前扩展的
  • 设置任何附加规则"warn"以避免阻止项目构建
  • 如果使用 TypeScript,请将特定 TS 相关配置放在该"overrides"部分。

.eslintrc.js使用 TypeScript 的 CRA 项目的简单(注意扩展名)配置文件可能如下所示:

const defaultRules = [
  'react-app',
  'eslint:recommended',
  // any other plugins or custom configuration you'd like to extend from.
];

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  env: {
    browser: true,
    node: true,
    es6: true,
    jest: true,
  },
  extends: defaultRules,
  rules: {
    'array-callback-return': 'warn',
    'consistent-return': 'warn',
    'default-case': 'warn',
    // etc.
  },
  overrides: [
    {
      files: ['**/*.ts', '**/*.tsx'],
      plugins: ['@typescript-eslint'],
      extends: [
        ...defaultRules,
        'plugin:@typescript-eslint/recommended',
        // any other TypeScript specific config (from a plugin, or custom)
      ],
      rules: {
        '@typescript-eslint/no-explicit-any': 'warn',
        '@typescript-eslint/no-unused-vars': 'warn',
        '@typescript-eslint/no-unused-expressions': 'warn',
        // etc.
      },
    },
  ],
  settings: {
    react: {
      // React version. "detect" automatically picks the version you have installed.
      version: 'detect',
    },
  },
};
Run Code Online (Sandbox Code Playgroud)

  • 为了将来的参考,您可以查看 CRA 团队使用的 ESLint 配置 @ https://github.com/facebook/create-react-app/blob/master/packages/eslint-config-react-app/index.js (2认同)