在我最近设置的 Typescript 项目中,我使用 Babel 来编译我的 Typescript 代码。我还使用 @typescript-eslint
作为我的 linter。到目前为止,它一直运行良好,直到最近我尝试在代码中使用 Symbol
时为止。
由于某种原因,Typescript(或 Babel)无法识别 Symbol
并给我一个错误,指出 Symbol 未定义
。
这是我的 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
}
]
]
}
为什么会发生这种情况以及如何解决此问题?
最佳答案
如果您在 "parserOptions"
下设置 "ecmaVersion": 2018
,则 ESLint 仅支持 ES2018 语法。对于像 Symbol
这样的 ES6 全局变量,您需要指定 env
(如果上面未指定,则自动启用 ES6 语法支持):
.eslintrc.json:
{ "env": { "es6": true } }
看看他们的docs :
By the same token, supporting ES6 syntax is not the same as supporting new ES6 globals (e.g., new types such as Set). For ES6 syntax, use
{ "parserOptions": { "ecmaVersion": 6 } };
for new ES6 global variables, use{ "env": { "es6": true } }
.{ "env": { "es6": true } }
enables ES6 syntax automatically, but{ "parserOptions": { "ecmaVersion": 6 } }
does not enable ES6 globals automatically.
关于javascript - ESLint:为什么 Symbol 没有定义(no-undef 规则)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048586/