视图 | npm 运行服务 | ESLint 全局变量未在组件内定义

Jet*_*rst 3 javascript npm eslint vue.js

我在窗口上设置了一个 vue 实例,main.js如下所示:

window.todoEventBus = new Vue()
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我试图像这样访问这个 todoEventBus 全局对象:

created() {
    todoEventBus.$on('pluralise', this.handlePluralise);
},
Run Code Online (Sandbox Code Playgroud)

但我收到错误说:

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.
Run Code Online (Sandbox Code Playgroud)

但是,如果我在 console.log todoEventBus 中看到 vue 对象。

我的 package.json 文件看起来像这样。

{
  "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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*dis 12

此错误来自规则no-undef。当一个变量的范围没有定义Eslint将抛出这个错误,它不是一个闻名全球的(如Promisedocument等...)。

您可以通过在要使用它的文件中添加注释来将变量声明为全局变量,如下所示:

/* global todoEventBus */

或者您可以在 eslint 配置中将其声明为全局

"eslintConfig": {
    "globals": {
        "todoEventBus": "readable"
    }
}
Run Code Online (Sandbox Code Playgroud)