如何在TypeScript中使用jQuery

我在尝试


$(function(){ 

    alert('Hello'); 

});

它在Visual Studio中显示此错误:(TS) Cannot find name '$'.。如何在TypeScript中使用jQuery?


慕娘9325324
浏览 1043回答 3
3回答

繁花不似锦

您很可能需要下载jQuery 的TypeScript声明文件并将其包括在jquery.d.ts项目中。选项1:安装@types软件包(建议用于TS 2.0+)在与package.json文件相同的文件夹中,运行以下命令:npm install --save-dev @types/jquery然后,编译器将自动解析jquery的定义。选项2:手动下载(不推荐)在这里下载。选项3:使用键入内容(TS 2.0之前的版本)如果您使用的是打字,则可以通过以下方式包括它:// 1. Install typingsnpm 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";// orimport $ = require("jquery");您可能需要编译--allowSyntheticDefaultImports-add "allowSyntheticDefaultImports": true在tsconfig.json。还安装软件包吗?如果您没有安装jquery,则可能要通过npm将其安装为依赖项(但这并非总是如此):npm install --save jquery

三国纷争

对于Visual Studio代码对我而言,有效的方法是确保通过index.html中的<script>标记执行标准的JQuery库加载。跑npm install --save @types/jquery现在,所有.ts文件中都可以使用JQuery $函数,无需任何其他导入。

潇潇雨雨

就我而言,我必须这样做npm install @types/jquery --save-dev // install jquery type as dev dependency so TS can compile properlynpm install jquery --save // save jquery as a dependency然后在脚本文件中 A.tsimport * as $ from "jquery";... jquery code ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JQuery