ESLint:为什么未定义符号(无未定义规则)?

Car*_*ven 2 javascript typescript eslint webpack babeljs

在我最近设置的一个 Typescript 项目中,我让 Babel 来编译我的 Typescript 代码。我也@typescript-eslint用作我的 linter。到目前为止,它一直运行良好,直到最近我尝试Symbol在我的代码中使用它。

出于某种原因,Typescript(或 Babel)无法识别Symbol并给我一个错误,即Symbol is not defined.

这是我的 eslintrc 的样子:

{
  "parser": "@typescript-eslint/parser",
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier/@typescript-eslint",
    "plugin:prettier/recommended"
  ],
  "parserOptions": {
      "ecmaVersion": 2018,
      "sourceType": "module"
  },
  "plugins": [
      "@typescript-eslint/eslint-plugin"
  ]
}
Run Code Online (Sandbox Code Playgroud)

在我的 babelrc 中,我有以下内容:

{
  "presets": [
    [
      "@babel/preset-env"
    ],
    ["@babel/preset-typescript"]
  ],
  "plugins": [
    "@babel/plugin-transform-modules-commonjs",
    [
      "@babel/plugin-transform-runtime",
      {
        "corejs": 2
      }
    ]
  ]
}
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况,我该如何解决这个问题?

for*_*d04 10

如果"ecmaVersion": 2018在 下设置"parserOptions",则 ESLint 仅支持ES2018语法。对于像 一样的 ES6 全局变量Symbol,您要指定env(如果未指定,则自动启用 ES6 语法支持):

.eslintrc.json:

{ "env": { "es6": true } }
Run Code Online (Sandbox Code Playgroud)

看看他们的文档:

出于同样的原因,支持 ES6 语法与支持新的 ES6 全局变量(例如,诸如 Set 之类的新类型)不同。对于 ES6 语法,{ "parserOptions": { "ecmaVersion": 6 } };对于新的 ES6 全局变量,使用{ "env": { "es6": true } }. { "env": { "es6": true } }自动启用 ES6 语法,但{ "parserOptions": { "ecmaVersion": 6 } }不会自动启用 ES6 全局变量。