2017-09-24 111 views
0

我有一個使用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)鏈接可能有幫助 –

回答

0

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

只需更換:

import * as $ from 'jquery'

declare var $:any;

+0

是的,這使得'無法找到模塊'錯誤消失。但它仍然需要在根index.html中引用jQuery js文件。在Angular-node-typescript世界裏應該做的事情不完全是這樣,有點感覺不對。 – Passiday

+0

你可以安裝jquery npm模塊並在main.ts文件中要求它 –

相關問題