【问题标题】:Using jQuery in Angular (TypeScript, Webpack)在 Angular 中使用 jQuery(TypeScript、Webpack)
【发布时间】:2018-03-05 12:57:22
【问题描述】:

我有一个使用 TypeScript 和 Webpack 的 Angular (v2) 项目。我使用了一些启动项目作为种子,但配置已被大量修改,现在指向源并不重要。

我想在我的项目中使用 jQuery。对 jquery-3.2.0.min.js 的引用已经在 index.html 主文件中,因为它是 Bootstrap 所要求的。因此,我的脚本中对$ 的引用不会破坏打字稿的编译。我得到Cannot find module '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 中使用&lt;script&gt; 声明生存,但这是不对的。显然我在这里遗漏了一些东西。

【问题讨论】:

  • 在这里大声思考:“jQuery 作为模块”是否与 commonjs 模块兼容?或者你需要 AMD / es2016 模块语法吗?另外,您是否尝试过编译一个仅使用 jQuery 作为模块的简单测试(没有角度或其他任何东西,只是为了查看类型/模块是否正常工作)。
  • 检查此Third Party JS 链接可能会有所帮助

标签: node.js angular typescript webpack


【解决方案1】:

您不需要任何额外的努力。

只需替换:

import * as $ from 'jquery'

declare var $:any;

【讨论】:

  • 是的,这会使Cannot find module 错误消失。但它仍然需要引用根 index.html 中的 jQuery js 文件。在 Angular-node-typescript 世界中,事情并不完全应该是这样完成的,感觉有点不对。
  • 你可以安装 jquery npm 模块并在 main.ts 文件中使用它
猜你喜欢
  • 2017-07-12
  • 2018-04-08
  • 2018-05-15
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多