ESLint 无法识别 node.js 的 'global' 对象

ESLint doesn't recognize node.js's 'global' object

错误:

3:5  error  'global' is not defined  no-undef

我当前的 ESLint 配置:

module.exports = {
  parser: "babel-eslint",
  env: {
    browser: true,
    es6: true,
    "jest/globals": true,
    jest: true
  },
  extends: ["eslint:recommended", "plugin:react/recommended", "prettier", "prettier/react"],
  parserOptions: {
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
      jsx: true
    },
    sourceType: "module"
  },
  globals: {
    testGlobal: true
  },
  plugins: ["react", "prettier", "jest"],
  rules: {
    "prettier/prettier": 1,
    "no-console": 0
  }
};

导致 ESLint 错误的简化示例测试文件:

describe("Jest global:", () => {
  it("should not cause ESLint error", () => {
    global.testGlobal = {
      hasProp: true
    };
  });
});

我希望在 eslint 配置中包含 env: { jest: true } 来涵盖这个 Jest 功能。我当然可以禁用文件中的规则或行,但每次使用 global.

时我都需要这样做

global object is part of Node.js. It is not specific to Jest and therefore it's not included in the jest environment. In fact, you are running your unit tests in Node and you happen to use the global object for your tests. In general the globals defined for specific libraries are the ones they provide to make it more convenient to use them without having to import them. A counterexample would be AVA, which requires you to import it 而不是定义全局变量。

如果您也想使用 ESLint 进行测试,则必须添加 node 环境。

env: {
  browser: true,
  es6: true,
  node: true,
  jest: true
},