Angular4 can't find Jquery-UI functions
我已经安装了Jquery和Jquery-ui
1 | npm install --save jquery jquery-ui |
这些文件位于node_modules目录中。
我有一个声明Jquery的组件
1 | declare var $: JQueryStatic; |
我的jquery函数可以正常工作,但jquery-ui函数不能。
1 2 | $('some-div').dropdown(); // works $('window').draggable(); // draggable is not recognized as a function |
因此,显然我对jquery-ui的包含是不正确的。 我尝试在我的.angular-cli.json页面中包含许多不同的内容,但均未成功。
我在.angular-cli文件中尝试过的事情:
1 2 3 4 5 6 | ... "scripts": [ "../node_modules/jquery/dist/jquery.min.js", "../node_modules/jquery-ui/ui/widgets/draggable.js", "../node_modules/jquery-ui/ui/draggable.js", ] |
我尝试直接导入到组件中,但是这给定义$ ui带来了问题。 我也得到了未定义的错误。
我看过npm jquery-ui和Jquery-ui升级指南
有什么想法我要去哪里吗?
在angular-cli.json中定义jquery-ui的解决方案(避免在index.html中添加它)是:
1:导入jquery-ui-dist
1 | npm install jquery jquery-ui-dist |
2:在angular-cli.json中添加脚本
1 2 3 4 | "scripts": [ "../node_modules/jquery/dist/jquery.min.js", "../node_modules/jquery-ui-dist/jquery-ui.js" ], |
资源 :
https://stackoverflow.com/a/38795318
圣烟!这个很麻烦,但是经过数天的尝试,我才知道。
因此,这里有很多部分答案,但这应该是完整的。
从我所见,您无法在您的angular-cli和索引中包含jquery-ui。插件包含的内容将被覆盖,并且jquery作为全局变量将未定义。
我仅通过使用angular-cli.json就无法使其正常工作,但仅通过使用索引包含就可以使其正常工作。
这是仅对jquery / jquery-ui使用索引脚本包含的操作。
1:卸载jquery和jquery-ui并将其从package.json中删除
1 | npm uninstall --save jquery jquery-ui |
2:删除node_modules文件夹
3:在angular-cli.json文件中删除对jquery或jquery-ui的任何引用
4:重建node_modules文件夹(仔细检查jquery-ui是否存在,但是只要angular-cli.json不包含它就没有关系。
1 | npm install |
5:在索引文件中包含jquery,然后包含jquery-ui。我使用2.2.4,因为我还不信任3。
1 2 | <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> |
6:在要使用jquery或jquery插件的组件中注入$
1 2 3 | declare var $: any; $('draggable').draggable(); // WORKS! |
请像这样将jQuery ui导入index.html
1 | <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> |
然后像这样在组件中取消$
声明var $:any;