【问题标题】:Webpack bundle - Bootstrap's JavaScript requires jQueryWebpack 包 - Bootstrap 的 JavaScript 需要 jQuery
【发布时间】:2017-06-06 08:11:56
【问题描述】:

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

  • bundle按此顺序jquerytetherbootstrap.js
  • HTMLpage 中加载此捆绑包,并在其下方加载其他特定于页面的脚本。

为此,我使用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 包含:jquerytetherbootstrap
    • 查看内部,例如blog_index.js(在通过webpack 2 运行之后),我注意到jquery 导入没有捆绑在此文件中,而是vendor.bundle.js(这是预期的)。

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

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

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

【问题讨论】:

    标签: javascript jquery twitter-bootstrap webpack ecmascript-6


    【解决方案1】:

    Bootstrap 的 javascript 假定 jQuery 已连接到 window 对象,它不需要它或任何东西。

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

    将此添加到您的插件中,您应该没问题

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

    这将使用 jQuery 包的导出替换所有将 jQuery 假定为全局的实例,即 jQuery 对象。 Tether也一样

    【讨论】:

    • 非常感谢您的回答。我有一个简短的问题:添加这个对vendor.bundle.js 有影响吗?
    • 是的,它将替换单词 jQuery$window.jQuery 等的实例,并替换为实际指向 jQuery 对象的内容。例如,像 * WEBPACK VAR INJECTION */(function(jQuery, __webpack_provided_window_dot_Tether, Tether) {/*! 这样的东西。它不会以任何方式影响功能,
    • 谢谢!我想我明白了,但只是为了确保:因为它只公开了插件,这意味着我不必修改entryCommonChunksPlugin 的配置。我没听错吗?
    • 您绝对不需要修改您的entryCommonChunksPlugin 中的任何内容,但我不明白是什么让您感到困惑。 '仅公开插件'是什么意思?帮我帮你
    • 很抱歉给您带来了困惑。我担心我最终会捆绑库两次(ProvidePluginCommonChunksPlugin)。但是,阅读您的解释后,我了解到只有在 vendor.bundle.js 中加载的模块才会使用 ProvidePlugin (如果指定)公开。这样清楚一点吗?
    猜你喜欢
    • 2023-03-11
    • 2017-10-19
    • 1970-01-01
    • 2015-11-16
    • 2017-04-25
    • 2016-08-16
    • 2018-04-06
    • 2018-07-13
    • 2017-05-10
    相关资源
    最近更新 更多