如何通过 Webpack 导入和使用 jQuery 库?
How to import and use a jQuery library via Webpack?
我正在将 VueJS 与 Webpack 一起使用,我正在尝试使用 this jQuery tags input library。考虑到它的需要,我将 jQuery 作为一个全局变量包括在内:
// in webpack.config.js
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"jQuery.tagsinput": "bootstrap-tagsinput"
})
// in main JS
import jQuery from 'jquery';
一切正常,但问题是能否将此其他库放入。我可以 require
将其放入主 JS 文件 (require('../node_modules/bootstrap-tagsinput/dist/bootstrap-tagsinput.js');
),然后将其放入我的供应商文件, 但它没有执行,也没有任何反应。
我做错了什么?我是否需要以某种方式使用 import-loader
,或者一些填充物 - 完全不同的东西?
好的,我成功了。这是我所做的:
在webpack.config.js
:
plugins : [
// ...
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"jQuery.tagsinput": "bootstrap-tagsinput"
})
]
在我的主 Javascript 文件中:
// other imports, etc.
require('imports?$=jquery!../node_modules/bootstrap-tagsinput/dist/bootstrap-tagsinput.js');
请注意,这需要使用 imports-loader
。
在我的组件中:
export default {
// ...
ready: function() {
this.$watch('MY_MODEL', function(elt) {
$('input[data-role=tagsinput]').tagsinput();
});
}
}
注意这里需要手动申请.tagsInput()
。 .$watch
是为了确保元素实际呈现在页面上。如果您只是将 .tagsinput()
调用直接放入 ready
,它不会触发,因为该元素不一定已添加到 DOM。如果需要,您还可以使用 window.requestAnimationFrame
编写解决方案。
我正在将 VueJS 与 Webpack 一起使用,我正在尝试使用 this jQuery tags input library。考虑到它的需要,我将 jQuery 作为一个全局变量包括在内:
// in webpack.config.js
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"jQuery.tagsinput": "bootstrap-tagsinput"
})
// in main JS
import jQuery from 'jquery';
一切正常,但问题是能否将此其他库放入。我可以 require
将其放入主 JS 文件 (require('../node_modules/bootstrap-tagsinput/dist/bootstrap-tagsinput.js');
),然后将其放入我的供应商文件, 但它没有执行,也没有任何反应。
我做错了什么?我是否需要以某种方式使用 import-loader
,或者一些填充物 - 完全不同的东西?
好的,我成功了。这是我所做的:
在
webpack.config.js
:plugins : [ // ... new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", "jQuery.tagsinput": "bootstrap-tagsinput" }) ]
在我的主 Javascript 文件中:
// other imports, etc. require('imports?$=jquery!../node_modules/bootstrap-tagsinput/dist/bootstrap-tagsinput.js');
请注意,这需要使用 imports-loader
。
在我的组件中:
export default { // ... ready: function() { this.$watch('MY_MODEL', function(elt) { $('input[data-role=tagsinput]').tagsinput(); }); } }
注意这里需要手动申请.tagsInput()
。 .$watch
是为了确保元素实际呈现在页面上。如果您只是将 .tagsinput()
调用直接放入 ready
,它不会触发,因为该元素不一定已添加到 DOM。如果需要,您还可以使用 window.requestAnimationFrame
编写解决方案。