Vue | npm run serve | ESLint global variable is not defined within a component

Viewed 4489

I am setting a vue instance on the window in my main.js like this:

window.todoEventBus = new Vue()

Inside my components I am trying to access this todoEventBus global object like this:

created() {
    todoEventBus.$on('pluralise', this.handlePluralise);
},

But I am getting errors saying:

Failed to compile.

./src/components/TodoItem.vue
Module Error (from ./node_modules/eslint-loader/index.js):
error: 'todoEventBus' is not defined (no-undef) at src\components\TodoItem.vue:57:9:
  55 | 
  56 |     created() {
> 57 |         todoEventBus.$on('pluralise', this.handlePluralise);
     |         ^
  58 |     },
  59 | 
  60 |     methods: {


1 error found.

However if I console.log todoEventBus I see the vue object.

My package.json file looks like this.

{
  "name": "todo-vue",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.3.2",
    "vue": "^2.6.10"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-plugin-eslint": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "sass": "^1.23.1",
    "sass-loader": "^8.0.0",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}
2 Answers

This error comes from the rule no-undef. Eslint will throw this error when a variable is not defined in scope and it's not a known global (like Promise, document, etc...).

You can declare your variable as a global by putting a comment in the file you want to use it like this:

/* global todoEventBus */

or you could declare it as a global in your eslint config

"eslintConfig": {
    "globals": {
        "todoEventBus": "readable"
    }
}

Amending Alex's answer, you could also narrow down the rules to Vue SFC specifically:

// .eslintrc.js

module.exports = {
    ...
    overrides: [
        {
            files: "*.vue",
            globals: {
                todoEventBus: "readable",
            },
        },
    ],
}
Related