Webpack bundle – Bootstrap的JavaScript需要jQuery
我想要实现以下目标:
-
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’里面我加载了包:
在blog_index.js
的源目录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
导入没有捆绑在这个文件中,而是vendor.bundle.js
(这是预期的)。
-
但是,当我检查浏览器控制台时,我遇到以下问题 :
我尝试在这个行vendor: ["jquery", "tether", "bootstrap"]
切换库的顺序vendor: ["jquery", "tether", "bootstrap"]
,但没有任何改变 – 错误仍然存在。
你知道我怎么能解决这个问题,最好不要使用额外的webpack
插件?
Bootstrap的javascript假设jQuery挂钩在window
对象上,它不需要它或任何东西。
通过捆绑东西,您不会将变量暴露给全局范围,或者至少您不应该这样做。 所以bootstrap代码找不到jQuery。
将其添加到您的插件中,您应该没问题
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', tether: 'tether', Tether: 'tether', 'window.Tether': 'tether', })
这将替换jQuery
被假定为全局的所有实例,并导出jQuery包,即jQuery
对象。 同样的Tether