2016-05-12 85 views
0

我有一個使用Typescript的Angular 2應用程序。我想用jQuery的$各種任務,如

$(document).ready(function(){  // throwing error: "[ts] Cannot find '$'. any" 
    console.log("loaded up!"); 
    $("#main_div").niceScroll(); 
}) 

我已導入jQuery.min.js通過index.html文件到我的應用程序,像這樣:

<script src="app/libs/jquery.min.js"></script> 

然而,我關於jQuery代碼,沒有將任何內容導入app.component.ts文件。是否有必要,如果是的話,我該如何導入它?

import { GenericService } from './services/Generic.service';  // did not do this 
import $ from './libs/jquery.min.js';        // tried this but does not work 

令人驚訝的是,我的代碼昨天工作,因爲我正在開發,但不是今天當我跑npm start。任何人都可以幫我解決這個導入過程嗎?

回答

0

簡單地做一個

typings install jquery --ambient --save 

安裝類型定義文件。在你app.component.ts的頂部取下import $ from './libs/jquery.min.js';並加入到d.ts文件的引用,象這樣:

/// <reference path="../typings/jquery.d.ts"/> 

既然你已經加載索引中的JavaScript文件你只需要它的分型,因此打字稿知道,那些jQuery的名稱和方法存在。

+0

什麼'/// <參考路徑=「../ typings/jquery.d.ts」/>'do?它似乎被註釋掉了,所以我很困惑。 –

+0

它告訴TypeScript編譯器在搜索類型定義時包含該文件。 [更多信息](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html) – rinukkusu

+1

@KangzeHuang更多信息在這裏:https://github.com/Microsoft/TypeScript-Handbook/blob /master/pages/Namespaces%20and%20Modules.md#-reference-ing-a-module – Dinistro

0

只需添加與jQuery的分型:

typings install jquery --ambient --save 

然後在您的索引:

<script src="bower_components/jquery/dist/jquery.min.js"></script> 

,通常打字稿將做的工作:)

相關問題