我正在努力实现以下目标:
-
bundle
(按此顺序)jquery
,tether
, 和bootstrap.js
. - 在
HTML
中加载这个包页面及其下方加载其他页面特定脚本。
为了实现这一点,我使用了 webpack 2
和 CommonsChunkPlugin
.这是我的配置。
对于 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
(这是预期的)。
-
我尝试在这行 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/