简体   繁体   中英

Eslint not defined issue with imports

I have an App.js file like this:

import './bootstrap';

if (document.getElementById('vue')) {
    new Vue({
    });
}

It imports a bootstrap javascript file which holds the Vue npm package(node module).

In my bootstrap file I import it like so:

import Vue from 'vue';

When I run eslint with this setup though I get told:

'Vue' is not defined.

If the eslinter only checks per file this seems really obvious since the actually Vue variable is defined in a file that is imported. Can this be fixed cleanly though or do I have to edit my .eslintrc.js for a case like this?

I believe ES6 imports only apply to the current file (which is the main benefit of a module system – to avoid global contamination). Importing a module without bindings won't also make that module's imports available; they remain scoped to that module only.

You have a few options:

  1. You can explicitly import it everywhere you need it (the intended way with modules).

     import Vue from 'vue'; 
  2. You can export Vue (and anything else) from your bootstrap file and import everything:

    In bootstrap.js:

     import Vue from 'vue'; export { Vue }; 

    In App.js:

     import * as bootstrap from './bootstrap'; const Vue = bootstrap.Vue; 
  3. You can make Vue global from in your bootstrap file, but it defeats the benefit of modules: window.Vue = Vue;

The import and export articles at MDN give a good overview of different possible ways of importing and exporting.

You can try few configuration of eslint in .eslintrc to get this working. This error is coming with es6-modules , you can try playing with following config:

{
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "rules": {
        "semi": 2
    }
}

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