我在努力

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

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


当前回答

对于Visual Studio代码

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

Run

npm install --save @types/jquery

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

其他回答

下面是我的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 !')
    }
}




它像丝一样光滑!!

很可能你需要下载并包含jQuery-jquery.d的TypeScript声明文件。在你的项目里。

选项1:安装@types包(推荐用于TS 2.0+)

和你的包放在同一个文件夹里。Json文件,执行如下命令:

npm install --save-dev @types/jquery

然后编译器会自动解析jquery的定义。

选项2:手动下载(不推荐)

在这里下载。

选项3:使用类型(Pre TS 2.0)

如果你正在使用类型,那么你可以这样包括它:

// 1. Install typings
npm install typings -g
// 2. Download jquery.d.ts (run this command in the root dir of your project)
typings install dt~jquery --global --save

设置好定义文件后,在所需的TypeScript文件中导入别名($),然后像往常一样使用它。

import $ from "jquery";
// or
import $ = require("jquery");

你可能需要在tsconfig.json中使用——allowSyntheticDefaultImports - add "allowSyntheticDefaultImports": true来编译。

还要安装软件包?

如果你没有安装jquery,你可能想通过npm将它作为依赖项安装(但并不总是这样):

npm install --save jquery

我相信你可能需要JQuery的Typescript类型。既然你说你使用Visual Studio,你可以使用Nuget来获取它们。

https://www.nuget.org/packages/jquery.TypeScript.DefinitelyTyped/

Nuget Package Manager Console中的命令为

Install-Package jquery.TypeScript.DefinitelyTyped

更新:正如评论中提到的,这个包自2016年以来就没有更新过。但你仍然可以访问他们的Github页面https://github.com/DefinitelyTyped/DefinitelyTyped并下载这些类型。导航到库的文件夹,然后在那里下载index.d.ts文件。弹出它在你的项目目录的任何地方,VS应该立即使用它。

对于Visual Studio代码

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

Run

npm install --save @types/jquery

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

如果你想在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的所有优点