Carven
Carven

Reputation: 15660

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?

Upvotes: 5

Views: 4936

Answers (1)

ford04
ford04

Reputation: 74550

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 (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.

Upvotes: 17

Related Questions