首页 > 解决方案 > ESLint:为什么没有定义符号(no-undef 规则)?

问题描述

在我最近设置的一个 Typescript 项目中,我让 Babel 编译我的 Typescript 代码。我也@typescript-eslint用作我的短绒。到目前为止,它一直运行良好,直到最近我尝试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"
  ]
}

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

{
  "presets": [
    [
      "@babel/preset-env"
    ],
    ["@babel/preset-typescript"]
  ],
  "plugins": [
    "@babel/plugin-transform-modules-commonjs",
    [
      "@babel/plugin-transform-runtime",
      {
        "corejs": 2
      }
    ]
  ]
}

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

标签: javascripttypescriptwebpackbabeljseslint

解决方案


如果设置"ecmaVersion": 2018"parserOptions",则 ESLint 仅支持 ES2018语法。对于像 ES6 这样的全局变量Symbol,你想指定env(如果上面没有指定,则自动启用 ES6 语法支持):

.eslintrc.json:

{ "env": { "es6": true } }

看看他们的文档

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


推荐阅读