如何导入和使用特定的BootStrap 5 JavaScript插件?



我是Bootstrap (v5.1.0)和gulp的新手,不完全理解我如何只能导入特定的Bootstrap JavaScript插件。我已经尝试过这只是使用bootstrap模态插件,但我要么得到一个错误消息在浏览器控制台(SyntaxError在导入语句)点击模态启动按钮时没有发生任何事情。

My index.html with modal example from Bootsrap 5 docu

<head>
...
<script src="main.js" async></script>
<link rel="stylesheet" href="main.css">
</head>
<body>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
Launch static backdrop modal
</button>
<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Understood</button>
</div>
</div>
</div>
</div>
</body>

我的想法现在只是简单地导入必要的JS插件(位于JS/src/在bootstrap包中)在我的main.js顶部文件:

(async function main() {
import BaseComponent from 'bootstrap/base-component.js'
import Modal from 'bootstrap/modal.js'
const {myConfig} = await import("./myconfig.js");
...
})();

或者我尝试这样导入它们:

import { BaseComponent } from 'bootstrap/base-component'
import { Modal } from 'bootstrap/modal'
(async function main() {
const {myConfig} = await import("./myconfig.js");
...
})();

有人能解释一下如何有选择地导入Bootstrap的JS插件,或者使用Bootstrap JS插件时的最佳实践是什么?目前,我正在用gulp编译我的网站的源文件-以防万一。

我不确定这是否是最终的main.js以及HTML代码,您将发送到浏览器。我希望你知道,像这样的import语句需要在编译时使用Babel、gulp这样的任务运行器和/或webpack这样的模块打包器来解决。否则浏览器将抛出此类错误。在编译过程中,导入语句将被导入的代码所替换,我不明白为什么导入语法会转义到浏览器中。你可以在JS中导入,在浏览器中运行,但语法会有所不同,更重要的是这会影响性能。

然而,如果在构建过程的早期就报告了Import中的语法错误,这可能是由于没有Babel.js或版本的问题,Babel.js应该解释和协调ES版本的差异。也许你的任务运行器设置上的JS语法验证可能不是最新的。

我使用Webpack 4(带Babel)并成功地测试了这个场景。代码中的其他一切似乎都是正确的。(就像在main.js中导入base-component和modal一样)。

注意到另一件事(与您报告的问题无关)。您可以使用

<script .. async>..

这将并行下载脚本并在可用时立即运行它。这意味着它可以在页面完全解析之前(或者在它的DOM树准备好之前)运行。如果您打算做DOM操作,您应该使用defer而不是async。或者,您可以直接将脚本添加到HTML正文的底部。

最新更新