在Angular中使用jQuery(TypeScript,Webpack)

在Angular中使用jQuery(TypeScript,Webpack)

问题描述:

我有一个使用TypeScript和Webpack的Angular(v2)项目。我为种子使用了一些启动器项目,但配置已经过很大的修改,现在指向源代码并不重要。在Angular中使用jQuery(TypeScript,Webpack)

我想在我的项目中使用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 
} 

我曾尝试加入jquerytypes,或者改变targetes6,但没有运气。

我在这里没有选择。我可以在根index.html<script>声明中生存,但这是不对的。很明显,我在这里错过了一些东西。

+0

只是想大声这里:是 “jQuery的一个模块” 与CommonJS的模块兼容?或者您是否需要AMD/es2016模块语法?另外,你是否试过编译一个简单的测试,它只使用jQuery作为一个模块(没有角度或其他任何东西,只是为了查看类型/模块是否工作)。 – Kokodoko

+0

检查此[第三方JS](https://rahulrsingh09.github.io/AngularConcepts/faq)链接可能有帮助 –

你不需要你做的任何额外的努力。

只需更换:

import * as $ from 'jquery'

declare var $:any;

+0

是的,这使得'无法找到模块'错误消失。但它仍然需要在根index.html中引用jQuery js文件。在Angular-node-typescript世界里应该做的事情不完全是这样,有点感觉不对。 – Passiday

+0

你可以安装jquery npm模块并在main.ts文件中要求它 –