无法将jQuery插件与Angular 4和Webpack一起使用 [英] Not able to use a jQuery plugin with Angular 4 and Webpack
问题描述
我正在将Angular 4与webpack一起使用,但无法使用jQuery插件,但它与angular cli一起使用时却无法使用webpack
I'm using Angular 4 with webpack and I'm not able to use a jQuery plugin,with angular cli it works,with webpack not
我已将该插件包含在webpack.config.vendor.js中
I've included the plugin in webpack.config.vendor.js
const treeShakableModules = [
.....
'@angular/router',
'zone.js',
'virtual-keyboard',
如果我在以下位置查看源页面
If i check the source page at
script src="/dist/vendor.js?v=SsiHzOEk9BPk3CnH6ivS_kkChKmOOxXsB-fFyDO1R8w"></script>
我可以找到js插件代码
I can find the js plugin code
在我的.ts代码中,
import * as $ from 'jquery';
....
$('#mycontrol').css('background-color', 'red');// I see the change so jQuery works
(<any>$('#mycontrol')).keyboard();
在控制台中,我收到此错误: $(...).键盘不是功能
In console I got this error: $(...).keyboard is not a function
带有角度cli的这段代码非常简单
with angular cli works very simple with this code
declare var $: any;
$('#mycontrol').keyboard();
谢谢
推荐答案
首先,您应该将其添加到webpack配置中:
first you should to add it webpack config :
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.pt'
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}),
]
在您的组件中之后,您可以将其导入:
after in your component you can import it :
import * as $ from 'jquery';
这是对jquery的全局解决方案访问,因此存在多个选项.
this is a global solution access to jquery then several options exist.
当然不要忘记通过npm安装jquery:
of course don't forget to install jquery via npm :
npm i --save jquery
这篇关于无法将jQuery插件与Angular 4和Webpack一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!