2017-06-16 60 views
2

我想在我的angluar cli項目中使用jQuery。 我在這裏試圖說明:https://www.gurustop.net/blog/2016/11/18/3821/jquery-angular2-angularcli-how-to無法將jQuery添加到角度cli項目

  1. 安裝jQuery的

    npm install --save jquery; 
    
  2. 安裝jQuery的類型認定中進行類型檢查。

    npm install --save-dev @types/jquery 
    
  3. 在 「腳本」 數組添加的jquery文件的refenece內部 角cli.json文件。在我app.component.ts

    "scripts": [ 
        "../node_modules/jquery/dist/jquery.min.js" 
    ] 
    
  4. 導入jQuery的文件

    import { Component } from '@angular/core'; 
    import * as jQuery from 'jquery'; 
    
    @Component({ 
        selector: 'app-root', 
        templateUrl: './app.component.html', 
        styleUrls: ['./app.component.scss'] 
    }) 
    export class AppComponent { 
        title = 'app'; 
        test = jQuery("body"); 
    } 
    

然而,當一個做ng build我得到以下錯誤:

ERROR in ./src/app/app.component.ts (2,25): Module ''jquery'' resolves 
to a non-module entity and cannot be imported using this construct. 

如果我刪除import * as jQuery from 'jquery';和'ng build'我得到:

ERROR in ./src/app/app.component.ts (10,10): Cannot find name 'jQuery'. 

不知道該從哪裏出發。

更新基於什麼@Saravana公佈1

。 如果我只是做declare const $: JQueryStaticng build,我得到的錯誤:

ERROR in ./src/app/app.component.ts (2,19): Cannot find name 'JQueryStatic'. 

但如果我做什麼Saravana在他的第一篇文章建議之前,他刪除了。

import "jquery"; 
declare const $: JQueryStatic; 

它的構建沒有抱怨。所以我認爲Saravana你應該回復你的帖子。

回答

2

由於jQuery庫添加了一個全局變量$jQuery,你可以聲明變量:

import "jquery"; 
declare const $: JQueryStatic; 
0

升級到最新的CLI,創建一個新的項目,並動了我的位和說明上述概述工作得很好。

npm uninstall -g angular-cli 

npm cache clean 

npm install -g @angular/[email protected]