我在努力
$(function(){
alert('Hello');
});
在Visual Studio中显示此错误:(TS)无法找到名称“$”..我如何使用jQuery与TypeScript ?
我在努力
$(function(){
alert('Hello');
});
在Visual Studio中显示此错误:(TS)无法找到名称“$”..我如何使用jQuery与TypeScript ?
当前回答
在安装jquery和@types/jquery(作为dev依赖项)后,使用以下导入:
import * as $ from "jquery";
对我来说,只有这样才有用。 (angular9)
其他回答
如果你想在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的所有优点
我的VS 2019程序在ASP。Net核心项目。因此,我不需要在npm命令行工具上瞎折腾,而是使用npm配置文件采取声明性的方法。
Do you have a package.json (npm dependencies config) in the root of your project? If no, right click project -> Add -> New item -> (Search npm) Select npm Configuration File and keep default filename package.json Add an entry under devDependencies. This tells npm to install "@types/jquery" which is a npm package maintained by DefinitelyTyped. This is essentially the same as the npm install command shown in other answers. "devDependencies": { "@types/jquery": "3.5.1" } Supposedly upon saving the file this should trigger the npm package install. I find I have to right click the package.json file and click Restore Packages (option not shown while project is in debug mode). The first time you run npm restore, you should switch to the Output tab/window and change dropdown to "npm" to verify there were no errors.
您应该会在Project -> node_modules/@types/jquery/下看到一个新项目 Index.d.ts是主要的typescript定义文件,它引用了其他的typescript定义文件。
打开您自己的typescript文件,并将index.d.ts从解决方案资源管理器拖到所打开的typescript文件的第一行上。这应该添加在顶部(相对路径将根据你的typescript文件的位置而变化): /// <引用路径="../node_modules/@types/jquery/index.d. "ts " / > 现在,如果你开始在typescript文件的函数中编写代码,你应该能够输入jQue并得到智能感知完成提示。
注意:最近的VS在重新启动之前没有正确地反映各种更改,特别是涉及到键入错误和智能感知的事情。你可以经常看到,甚至在官方的微软文档中,他们提到需要重新启动来解决红色曲线。因此,当有疑问时,关闭/重新打开VS.最后一步是你最可能发现智能感知在重新启动之前无法工作的地方。
不管你是否使用非npm方法包含jQuery,这个方法都有效。例如,在一个项目中,我们不使用导入、npm、js模块,也不使用requireJS来解析依赖项。jQuery只是html页面上的一个脚本标签链接。但是,我仍然可以引用。d。jQuery typedefs,以获得typescript完成/类型解析。
我可以很容易地在包中添加依赖项。jquery:“3.5.1”来获取jquery本身。
还要注意,如果VS工作正常,它在package.json中有一些缓慢的(由于web查询)名称和版本完成提示:
从现在到现在,在Angular版本9,这对我来说都是有效的
通过npm安装:npm i @types/jquery只需添加——save到全局设置。 转到tsconfig.app.json,在数组“types”中添加jquery。 发球完毕。
在安装jquery和@types/jquery(作为dev依赖项)后,使用以下导入:
import * as $ from "jquery";
对我来说,只有这样才有用。 (angular9)
2019年更新:
大卫的回答更准确。
Typescript支持第三方供应商库,这些库不使用Typescript进行库开发,使用DefinitelyTyped Repo。
你需要在你的组件中声明jquery/$,如果这些类型的类型检查tsLint是On的。
如。
declare var jquery: any;
declare var $: any;