我在努力

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

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


当前回答

在安装jquery和@types/jquery(作为dev依赖项)后,使用以下导入:

import * as $ from "jquery";

对我来说,只有这样才有用。 (angular9)

其他回答

2019年更新:

大卫的回答更准确。

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


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

如。

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

就我而言,我必须这么做

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 ...

这对我来说很管用:

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

对于Visual Studio代码

对我来说有用的是确保我通过index.html中的< script >标记来加载标准的JQuery库。

Run

npm install --save @types/jquery

现在JQuery $函数在所有.ts文件中都可用,不需要任何其他导入。

在安装jquery和@types/jquery(作为dev依赖项)后,使用以下导入:

import * as $ from "jquery";

对我来说,只有这样才有用。 (angular9)