Vue app: ESLint throwing error for undefined global variable in component during npm run serve

In my main.js file, I am initializing a new Vue instance on the window object:

window.todoEventBus = new Vue()

Within my components, I am attempting to access this global todoEventBus object like so:

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

Unfortunately, I am encountering errors indicating:

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 can see the Vue object.

The content of my package.json file is as follows:

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

Answer №1

If you encounter this particular error, it is triggered by the rule no-undef. This error is generated by Eslint when a variable is not defined within a certain scope and is not recognized as a global entity (such as Promise, document, etc...).

To resolve this issue, you have two options: one is to declare your variable as a global within the file where you intend to use it, like so:

/* global todoEventBus */

Alternatively, you can define it as a global in your eslint configuration settings:

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

Answer №2

Expanding on Alex's response, one can further refine the guidelines to focus on Vue Single File Components:

// .eslintrc.js

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

Exploring Vue: Techniques for leveraging and working with mappedState data

In this component, I am using `mapState` to retrieve 2 different states from the user store. The user store makes a GQL call and receives a list of `potentialNames`. Initially, while waiting for the query to complete, `fetchingData` is set to `true`, and o ...

Encountered difficulties logging in with MongoDB and Node.js

I encountered an issue while attempting to authenticate a user using MongoDB and Node.js. Although no errors are thrown, the system fails to provide the expected data after the user logs in. Below is a breakdown of my code. server.js var port=8888; va ...

Encountering a SubprocessError while attempting an Ionic v4 production build

Encountering issues with Ionic v4 production builds on Ubuntu v.18. Upon running ionic build --prod, an error is thrown: Error at new SubprocessError (/root/.nvm/versions/node/v12.2.0/lib/node_modules/@ionic/cli/node_modules/@ionic/utils-subprocess/dist/i ...

How can I address multiple buttons with various events using jQuery?

I am new to learning jQuery and I'm currently working on some exercises. However, I've run into an issue with two buttons in the DOM that are supposed to perform different actions. I can't seem to figure out how to assign different functions ...

How can I display a clicked-on div while hiding all other divs using jQuery?

I want to create a website where a button can show and hide a specific div, but my challenge is; How can I ensure that clicking on one button hides all other divs? Here is the JavaScript code: function showHide(divId){ var theDiv = document.getEleme ...

How can I attach a cookie to a div that becomes visible after a few seconds of video playback?

After 20 seconds of video play, a div element appears. I am trying to set up a cookie so that once the div is shown, it continues to appear unless the user clears their cache (cookie logic). This is my current attempt - http://jsfiddle.net/9L29o365/ Any ...

Encountering issues with npm installation when running `eb create` on Node version 6.2.2

Is anyone else encountering this problem? 1620 verbose unsafe-perm in lifecycle false 1621 info <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385a4d5e5e5d4a4d4c51547809160a1609">[email protected]</a> Failed to ...

The `finally` function in promises is failing to execute properly

Currently working with Typescript and I've included import 'promise.prototype.finally' at the beginning of my index.js file (in fact, I've added it in multiple places). Whenever I try to use a promise, I encounter the error message say ...

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...

Activate the opening of a .docx file in a new tab by utilizing an anchor tag

I have attached a docx file containing the terms and conditions for our project. Now, I would like to open it in a new tab. By clicking this link, you can view the <a title="click to view terms and conditions" style="color:blue;" target="_blank" href ...

Validate if the JSON data array contains any elements

I'm currently working with an ajax code and I need to determine whether the JSON data contains an array or not. However, despite my attempts, I am still receiving incorrect output. $.ajax({ url: url, type: 'POST', da ...

Deselect an item from a three.js scene by clicking on it

In my three.js scene, I have multiple OBJ models, some already loaded in the scene and others added via a button click. If a user adds an object but later decides to remove it, I am seeking guidance on how to accomplish this effectively. My ideal solutio ...

Closing a dropdown on outside click in NEXT.JS can be done by adding an event

Currently, I am in the process of developing an ecommerce platform that features a search input with results displayed in a dropdown. The search functionality is working as intended, but now I would like to implement a feature where the dropdown closes whe ...

Tips for resetting form fields and clearing previous values before resubmitting the form, allowing for a fresh start with empty fields

Welcome to my website! If you visit , you'll notice a feature I've added that clears form field values after submission. However, I'm encountering an issue where the fields remain filled when revisiting the page for another appointment. I at ...

Having difficulty assigning an argument to an HTTP get request in AngularJS

I am new to working with AngularJS and I am attempting to pass an integer argument to an HTTP GET request in my controller. Here is a snippet of my code: (function() { angular .module('myApp.directory', []) .factory('Ne ...

User creation causing redirection malfunction

Recently, while working on a website, I encountered an issue with the registration process for users. It was functioning properly when I tested it a few days ago. After making some updates to other aspects of the website such as the login and profile sect ...

Capturing user-selected option from dropdown menu using npm

I am a beginner when it comes to node.js and async programming. My current project involves creating a program that shuffles a Spotify playlist. I have managed to store the user's playlists in an array for easier access. My goal is to present this ar ...

Vue parent Component refreshes child Component data when props are updated

One of the challenges I am facing is with a child component that has internal data which should not be changed from outside. However, whenever I update the prop from the parent component, this internal data gets reset. For example, in the code snippet bel ...

Padding-left in InfoBox

Currently, I am in the process of developing a map using Google Maps API3 along with the InfoBox extension available at this link I have successfully implemented an overall padding to the Infobox using the following code snippet: var infoOptions = { disa ...