gpt4 book ai didi

javascript - Eslint 未定义导入问题

转载 作者:行者123 更新时间:2023-11-29 21:09:31 25 4
gpt4 key购买 nike

我有一个像这样的 App.js 文件:

import './bootstrap';

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

它导入一个包含 Vue npm 包( Node 模块)的 Bootstrap javascript 文件。

在我的 Bootstrap 文件中,我像这样导入它:

import Vue from 'vue';

当我使用此设置运行 eslint 时,我被告知:

'Vue' is not defined.

如果 eslinter 只检查每个文件,这似乎很明显,因为实际的 Vue 变量是在导入的文件中定义的。这可以彻底修复吗,还是我必须为这种情况编辑我的 .eslintrc.js

最佳答案

我相信 ES6 导入仅适用于当前文件(这是模块系统的主要好处——避免全局污染)。导入一个没有绑定(bind)的模块也不会使该模块的导入可用;它们仍然仅限于该模块。

您有几个选择:

  1. 您可以在任何需要的地方显式导入它(模块的预期方式)。

    import Vue from 'vue';
  2. 您可以从 Bootstrap 文件中导出 Vue(以及其他任何东西)并导入所有内容:

    在 bootstrap.js 中:

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

    在 App.js 中:

    import * as bootstrap from './bootstrap';
    const Vue = bootstrap.Vue;
  3. 您可以在您的 Bootstrap 文件中将 Vue 设为全局,但它会破坏模块的优势:window.Vue = Vue;

importexport MDN 上的文章很好地概述了导入和导出的不同可能方式。

关于javascript - Eslint 未定义导入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42392206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com