简体   繁体   中英

ESLint: Why is Symbol not defined (no-undef rule)?

In a Typescript project that I've recently setup, I've gotten Babel to compile my Typescript code. I'm also using @typescript-eslint as my linter. So far, it has been working well until recently when I tried to use Symbol in my code.

For some reason, Typescript (or Babel) is unable to recognise Symbol and is giving me an error that Symbol is not defined .

Here's how my eslintrc looks:

{
  "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"
  ]
}

And in my babelrc, I've the following:

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

Why is this happening and how can I fix this issue?

If you set "ecmaVersion": 2018 under "parserOptions" , only ES2018 syntax is supported by ESLint. For ES6 globals like Symbol , you want to specify env (enables ES6 syntax supporting automatically, if above was not specified):

.eslintrc.json:

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

Have a look at their docs :

By the same token, supporting ES6 syntax is not the same as supporting new ES6 globals (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM