Bootstrap DOM脚本中的JavaScript变量引用不起作用

jhdbpxl9  于 2023-02-17  发布在  Bootstrap
关注(0)|答案(1)|浏览(138)

我刚接触Vite,只想做一件简单的事情-〉引用我在main.js中声明的DOM中的变量。
main.js中重要代码:

let getThis = 'Why does this not work';

index.html中重要代码:

<body>
<p id="test">not working</p>
<script type="module" src="/main.js"></script>
<script type="module">
  document.getElementById('test').innerHTML = getThis;
</script>

示例:https://stackblitz.com/edit/vitejs-vite-urotp2?file=main.js,index.html,counter.js&terminal=dev我在互联网上搜索了2天:/
首先,我在使用Bootstrap和Vite时遇到了一个问题。我想通过Javascript触发一个Modal,就像下面的例子:https://stackblitz.com/edit/github-4akyeo?file=src%2Fjs%2Fmain.js,src%2Findex.html
index.html中重要代码:

<script>
    const myModalAlternative = new bootstrap.Modal('#exampleModal');
    myModalAlternative.show();
  </script>

main.js中重要代码:

import * as bootstrap from 'bootstrap';
window.bootstrap = bootstrap;

但我总是收到Uncaught ReferenceError: bootstrap is not defined(在控制台中查看)。我研究并发现这是因为引导变量没有链接到窗口对象,但这并没有解决这个问题。所以我分解它并意识到这是一个更普遍的问题。我假设它与文件的捆绑有关,现在变量在中不可读。
这是可能的吗?还是我错过了什么?这可能是一个正常的JavaScript范围问题?感谢任何帮助。

pbgvytdp

pbgvytdp1#

感谢来自维特的Arnaud,我已经解决了这个问题。以下是他告诉我的:
ESM模块中的变量的作用域仅限于该模块,您只能通过导出变量并在其他模块中使用import来访问它们,就像您对计数器所做的那样。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
如果你想绕过它,你可以在窗口对象上设置一些东西,使它成为全局的,但这应该只在特殊情况下使用
所以我研究了JS模块并修复了上面提到的两个问题。

解决标题中提到的主要问题

我不得不从导入到我的main.js的文件中导出变量,然后将变量导入到我的。
custom.js中的代码:

export let getThis = 'Why does this not work';

index.html中重要代码:

import { getThis } from './custom.js';

参见main problem solved

修复"未捕获引用错误:未定义引导'

我只需要将type="module"添加到<script>中,bootstrap.Modal('#exampleModal');现在就可以工作了。请记住,只有在您首先将bootstrap设置为全局的情况下才可以工作,例如:

import * as bootstrap from 'bootstrap';
window.bootstrap = bootstrap; // <- add to window object to bypass the scope and make it global

参见bootstrap problem solved - Stackblitz
希望这对某人有帮助。

相关问题