[英]Using jQuery in Angular (TypeScript, Webpack)
我有一个使用TypeScript和Webpack的Angular(v2)项目。 我使用了一些入门项目作为种子,但是对配置进行了很大的修改,现在不要指向源代码了。
我想在我的项目中使用jQuery。 引用jquery-3.2.0.min.js
已经在主index.html
文件中,这是Bootstrap所必需的。 因此,在我的脚本中对$
的引用不会破坏打字稿的编译。 我得到Cannot find module 'jquery'.
错误,尽管import * as $ from 'jquery';
有import * as $ from 'jquery';
相应打字稿文件顶部的第一行。 但是,由于index.html
中的jQuery <script>
引用,代码仍然可以运行。
好吧,我想正确地做到这一点,所以我继续安装了jQuery库和jQuery类型:
$ npm install --save jquery
$ npm install --save-dev @types/jquery
令我震惊的是,在添加了jQuery类型之后,编译现在充满了很多错误,总共7140个错误。 以下是一小段摘录:
ERROR in [default] /[path]/node_modules/@types/jquery/index.d.ts:35:22
Generic type 'JQueryStatic<TElement, HTMLElement>' requires 2 type argument(s).
ERROR in [default] /[path]/node_modules/@types/jquery/index.d.ts:36:17
Generic type 'JQueryStatic<TElement, HTMLElement>' requires 2 type argument(s).
ERROR in [default] /[path]/node_modules/@types/jquery/index.d.ts:43:45
',' expected.
ERROR in [default] /[path]/node_modules/@types/jquery/index.d.ts:54:11
Generic type 'EventStatic<TTarget, EventTarget>' requires 2 type argument(s).
ERROR in [default] /[path]/node_modules/@types/jquery/index.d.ts:62:14
Generic type 'PlainObject<T, any>' requires 2 type argument(s).
ERROR in [default] /[path]/node_modules/@types/jquery/index.d.ts:70:15
Generic type 'PlainObject<T, any>' requires 2 type argument(s).
ERROR in [default] /[path]/node_modules/@types/jquery/index.d.ts:71:17
Generic type 'JQuery<TElement, HTMLElement>' requires 2 type argument(s).
如果卸载类型,我会返回到更友好的Cannot find module 'jquery'.
错误。
我尝试了节点jquery
和@types/jquery
版本的不同组合,但无济于事。
这是我的tsconfig.json
文件:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"outDir": "../dist",
"rootDir": "../src",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"types": [
"node",
"core-js"
]
},
"compileOnSave": false,
"buildOnSave": false
}
我尝试将jquery
添加到types
,或将target
更改为es6
,但是没有运气。
我在这里没有选择。 我可以通过index.html
根目录中的<script>
声明生存下来,但这是不对的。 显然我在这里缺少什么。
您不需要付出任何额外的努力。
只需替换:
import * as $ from 'jquery'
与
declare var $:any;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.