javascript - Webpack 包 - Bootstrap 的 JavaScript 需要 jQuery

标签 javascript jquery twitter-bootstrap webpack ecmascript-6

我正在努力实现以下目标:

  • bundle (按此顺序)jquery , tether , 和 bootstrap.js .
  • HTML 中加载这个包页面及其下方加载其他页面特定脚本。

为了实现这一点,我使用了 webpack 2CommonsChunkPlugin .这是我的配置。

对于 entries我有:

const scriptsEntry = {
    blog_index: SRC_DIR + "/js/pages/blog_index.js",
    blog_about: SRC_DIR + "/js/pages/blog_about.js",
    vendor: ["jquery", "tether", "bootstrap"]
};

plugins部分:

scriptsPlugins.push(
    new webpack.optimize.CommonsChunkPlugin({
        name: "vendor", 
        filename:"vendor.bundle.js", 
        minChunks: 2
    }),
    ...
}));

在“index.html”中我加载了包:

<script src="{{ url_for('static', filename='dist/js/vendor.bundle.js') + anti_cache_token }}"></script>
<script src="{{ url_for('static', filename='dist/js/home.js') + anti_cache_token }}"></script>

源码目录在blog_index.js里面我利用 jquery :

import $ from "jquery";

$(".home-click").click(function () {
    alert("clicked from .home-click");
});

结果:

  • 一切都捆绑在一起,没有任何错误。
  • 当我点击 .home-click alert box按预期开火。
  • 检查捆绑文件我看到:
    • vendor.bundle.js包含:jquery , tether , 和 bootstrap .
    • 向内看,例如,blog_index.js (在运行完 webpack 2 之后),我注意到 jquery import 没有捆绑在此文件中,而是 vendor.bundle.js (这是预期的)。

但是,当我检查浏览器控制台时,我遇到了以下问题: enter image description here

我尝试在这行 vendor: ["jquery", "tether", "bootstrap"] 中切换库的顺序,但没有任何改变——错误仍然存​​在。

你知道我该如何解决这个问题,最好不使用额外的 webpack插件?

最佳答案

Bootstrap 的 javascript 假定 jQuery Hook 在 window 对象上,它不需要它或任何东西。

通过捆绑,您不会将变量暴露给全局范围,或者至少您不应该这样做。所以 Bootstrap 代码找不到 jQuery。

将这个添加到你的插件中,你应该没问题

new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    'window.jQuery': 'jquery',
    tether: 'tether',
    Tether: 'tether',
    'window.Tether': 'tether',
})

这将用 jQuery 包的导出替换所有 jQuery 被假定为全局的实例,它是 jQuery 对象。 Tether

也一样

关于javascript - Webpack 包 - Bootstrap 的 JavaScript 需要 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41778884/

相关文章:

javascript - 如何在可以更改的值上触发函数?

jquery - 如何使用jquery在表单提交之前设置属性

javascript - 我可以使用 bootstrap-fileinput 将文件上传到服务器吗?是否支持像jquery多文件 uploader 一样的服务器上传?

html - Bootstrap - 为什么 z-index 较低的 div 会覆盖 z-index 较高的 div?

javascript - 输入元素是否有可能没有焦点的光标?

javascript - 测试 JavaScript 图表

javascript - 在登录 asp.net MVC 应用程序期间检测 javascript...这段代码看起来正常吗?

jquery - 表单验证 regex.test(value) 返回 true 但运行时就好像它是 false,想法?

javascript - 使用 jquery 通过点击替换 div 内容

javascript - 动态更新 Bootstrap 工具提示