我在努力

$(function(){ 
    alert('Hello'); 
});

在Visual Studio中显示此错误:(TS)无法找到名称“$”..我如何使用jQuery与TypeScript ?


当前回答

2019年更新:

大卫的回答更准确。

Typescript支持第三方供应商库,这些库不使用Typescript进行库开发,使用DefinitelyTyped Repo。


你需要在你的组件中声明jquery/$,如果这些类型的类型检查tsLint是On的。

如。

declare var jquery: any;
declare var $: any;

其他回答

这对我来说很管用:

export var jQuery: any = window["jQuery"];

就我而言,我必须这么做

npm install @types/jquery --save-dev // install jquery type as dev dependency so TS can compile properly
npm install jquery --save // save jquery as a dependency

然后在脚本文件A.ts

import * as $ from "jquery";
... jquery code ...

2019年更新:

大卫的回答更准确。

Typescript支持第三方供应商库,这些库不使用Typescript进行库开发,使用DefinitelyTyped Repo。


你需要在你的组件中声明jquery/$,如果这些类型的类型检查tsLint是On的。

如。

declare var jquery: any;
declare var $: any;

如果你想在web应用程序(例如React)中使用jquery,并且jquery已经加载了<script src="jquery-3.3.1.js"…

在网页上你可以这样做:

npm install --save-dev @types/query
and the use it with:
let $: JQueryStatic = (window as any)["jQuery"];

所以,你不需要第二次加载jquery(使用NPM install—save jquery) 但拥有Typescript的所有优点

下面是我的TypeScript和jQuery配置步骤。

它使jQuery的类型支持比互联网上的大多数文章更好地工作。(我相信。)

第一:

npm install jquery --save
npm install @types/jquery --save-dev




第二(非常非常非常重要!!!):

import jquery = require("jquery");



// this helps TypeScript to understand jQuery best !!!  otherwise It will confused .
const $: JQueryStatic = jquery;




那么,你可以享受它:

$(document).ready(function () {
    $('btn').click(function () {
       alert('I am clicked !')
    }
}




它像丝一样光滑!!