2016-07-09 94 views
7

我測試用jQuery打字稿,但是當我編譯test.ts文件時,它總是給我提示錯誤信息:找不到名稱「$」。

我已經進口的jQuery &加入其定義的參考。 如果我在test.ts文件中使用import $ = require("jquery"),另一個錯誤「Cannot find module jquery」會做tsc編譯時發生。但是,JQuery文件夾已經存在於node_modules文件夾中。

有誰知道什麼是打字稿使用jquery正確的方法是什麼?

下面是我的步驟:

  1. 使用npm install jquery --save
  2. 安裝分型使用在test.ts的頂部/// <reference path="../../../typings/globals/jquery/index.d.ts" />

tsconfig typings install --global --save dt~jquery

  • 添加jQuery的參考& jQuery的定義中安裝jQuery .json

    { 
        "compilerOptions": { 
         "jsx": "react", 
         "outDir": "./dist", 
         "sourceMap": true, 
         "noImplicitAny": true, 
         "module": "commonjs", 
         "target": "es5", 
         "experimentalDecorators": true 
        }, 
        "exclude": [ 
         "node_modules" 
        ], 
        "files": [ 
         "./typings/index.d.ts", 
         "./src/wo/tests/test.ts", 
        ] 
    } 
    

    test.ts

    /// <reference path="../../../typings/globals/jquery/index.d.ts" /> 
    
    let test:any=$("div"); 
    
  • +2

    你如何編譯該項目?同樣,你的'tsconfig.json'定義是錯誤的。你不能同時使用'exclude'和'files'(在這種情況下'files'會勝出,所以可能路徑是錯誤的)。如果使用tsconfig.json,你也不需要'/ /參考' –

    回答

    11

    我不知道是否有幫助,但我解決了同樣的問題,我的日期選擇器。

    首先,我安裝了jQuery的使用這個命令:npm install --save-dev @types/jquery

    然後在你的角cli.json文件中添加依賴關係:

    "styles": [ 
          "../node_modules/bootstrap/dist/css/bootstrap.css", 
          "../node_modules/font-awesome/css/font-awesome.css", 
          "../node_modules/ng2-datetime/src/vendor/bootstrap-datepicker/bootstrap-datepicker3.min.css", 
          "styles.css" 
         ] 
    
    "scripts": [ 
          "../node_modules/jquery/dist/jquery.js", 
          "../node_modules/ng2-datetime/src/vendor/bootstrap-datepicker/bootstrap-datepicker.min.js" 
         ] 
    

    我認爲加上jQuery的部分可以先制定出適合您。請讓我知道它是否有效。

    +5

    'npm install --save-dev @ types/jquery'解決了這個問題。謝謝。 – Shikhar

    +0

    不客氣,兄弟。很高興幫助。 –

    7

    如果你發現這些錯誤90%的時間它,因爲@類型的版本問題/ jQuery的

    嘗試運行的:

    npm install jquery --save 
    

    然後在app.module.ts

    import * as $ from 'jquery'; 
    

    然後運行:

    npm install @types/[email protected] 
    

    ,你應該準備好了。

    +0

    這工作對我來說,雖然我不得不把jquery放在一個字符串中,比如從'jquery';''的$ import *。 IntelliJ突出灰色作爲一個未使用的導入,但應用程序將只能用這一行進行編譯。 – hughjdavey