繁体   English   中英

在Angular中使用jQuery(TypeScript,Webpack)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM