简体   繁体   English

Eslint未定义导入问题

[英]Eslint not defined issue with imports

I have an App.js file like this: 我有一个像这样的App.js文件:

import './bootstrap';

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

It imports a bootstrap javascript file which holds the Vue npm package(node module). 它导入一个引导javascript文件,该文件包含Vue npm包(节点模块)。

In my bootstrap file I import it like so: 在我的引导文件中,我将其导入为:

import Vue from 'vue';

When I run eslint with this setup though I get told: 当我使用此设置运行eslint时,却被告知:

'Vue' is not defined. 未定义“ Vue”。

If the eslinter only checks per file this seems really obvious since the actually Vue variable is defined in a file that is imported. 如果eslinter仅检查每个文件,这似乎很明显,因为实际上Vue变量是在导入的文件中定义的。 Can this be fixed cleanly though or do I have to edit my .eslintrc.js for a case like this? 是否可以彻底解决此问题,还是必须针对这种情况编辑.eslintrc.js

I believe ES6 imports only apply to the current file (which is the main benefit of a module system – to avoid global contamination). 我相信ES6导入仅适用于当前文件(这是模块系统的主要优点–避免了全局污染)。 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: 您可以从引导文件中导出Vue(以及其他任何内容)并导入所有内容:

    In bootstrap.js: 在bootstrap.js中:

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

    In App.js: 在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; 您可以在引导文件中将Vue设置为全局,但无法利用模块的优势: window.Vue = Vue;

The import and export articles at MDN give a good overview of different possible ways of importing and exporting. 进口出口在MDN文章提供的进口和出口的不同可能的方式很好的概述。

You can try few configuration of eslint in .eslintrc to get this working. 您可以在.eslintrc尝试很少的eslint 配置 ,以.eslintrc正常工作。 This error is coming with es6-modules , you can try playing with following config: es6-modules出现此错误,您可以尝试使用以下配置:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM