2017-09-17 177 views
0

我是新來的,所以忍受着我。我想要做的是讓jquery在打字稿代碼文件中工作。使用jQuery與打字稿

我應該如何參考.d.ts代碼?

我曾嘗試以下:

import * as $ from "jquery"; 

這給我的錯誤:「‘jQuery的’解決非模塊實體,並且不能與這個結構導入」

然後我想:

import $ = require("jquery"); 

本提供了以下錯誤:瞄準2015年的EcmaScript模塊

當 導入分配不能使用

我該如何解決這個問題才能讓jquery函數在我的打印代碼中工作?有其他方法嗎?

我使用的是typescript 2.5.2,模塊系統ES2015,EcmaScript 6和@types/jquery。


編輯

我試圖import * as $ from "../wwwroot/lib/jQuery/dist/jquery.min.js";,現在它給我的錯誤「......已經解決......但--allowJs沒有設置」,我沒有一個tsconfig.json還,我可能需要它用於--allowJs命令,是嗎?

+0

我做的'進口*爲jQuery的從「jquery''。它應該工作,如果jQuery通過NPM安裝。 – ideaboxer

+0

嘗試使用jquery的相對路徑:'import * as $ from「path/to/jquery」;' –

+0

(至少TypeScript 2.3.4有效) – ideaboxer

回答

0

我不知道這是一個「正確的方式」做事,但我在我的打字稿項目中使用以下行來使用jquery。

const jquery = require('jquery'); 
// and then later in your class 
jquery('.someclass').show(); 
+0

它給了我錯誤「找不到名字」require'「 –

+0

如果你想使用'require',你需要聲明它:'declare function require(moduleName:string):any;'編譯這個 – ideaboxer

1

將Typescript定義文件的引用添加到文件的頂部。

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

代替

import * as $ from "jquery"; 

按照DefinitelyTyped維基:

A TypeScript declaration file is way of defining the types, functions and parameters in an external third-party JavaScript library. By using a declaration file in your TypeScript code will enable Intellisense and type checking against the external library you are using.

jquery.d.ts是DefinitelyTyped圖書館的一部分上GitHub找到。 ,也可以通過npm進行安裝。

+0

, .js文件不包含jquery的定義,因此無法執行 –

+0

您必須將jquery.js文件添加到頁面以執行jquery函數。 –

0

安裝1端子

npm install --save jquery 

安裝1端子

npm install --save-dev @types/jquery 

安裝3添加在內部角cli.json文件 「腳本」 陣列的jquery文件的refenece。

"scripts": [ 
"../node_modules/jquery/dist/jquery.min.js" 

]

決賽 - 進口

declare var jQuery:any; 

@Component({ 
... 
}) 
export class YourComponent{ 
    ///...usage 
    Query('.classname').show(); 
}