如何在 TypeScript 中使用 jQuery [英] How to use jQuery with TypeScript

查看:83
本文介绍了如何在 TypeScript 中使用 jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力

$(function(){alert('你好');});

它在 Visual Studio 中显示此错误:(TS) 找不到名称$"..如何在 TypeScript 中使用 jQuery?

解决方案

您很可能需要下载并包含 TypeScript 声明文件 用于 jQuery——jquery.d.ts——在你的项目中.

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

在与 package.json 文件相同的文件夹中,运行以下命令:

npm install --save-dev @types/jquery

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

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

此处下载.>

选项 3:使用打字(TS 2.0 之前)

如果您使用的是typings,那么您可以这样包含:

//1. 安装类型npm 安装类型 -g//2. 下载jquery.d.ts(在你项目的根目录下运行这个命令)打字安装 dt~jquery --global --save

<小时>

设置定义文件后,在所需的 TypeScript 文件中导入别名 ($) 以正常使用它.

import $ from "jquery";//或者import $ = require("jquery");

您可能需要使用 --allowSyntheticDefaultImports 进行编译—在 tsconfig.json 中添加 "allowSyntheticDefaultImports": true.

还要安装软件包吗?

如果您没有安装 jquery,您可能希望通过 npm 将其安装为依赖项(但情况并非总是如此):

npm install --save jquery

I am trying

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

Its showing this error in Visual Studio: (TS) Cannot find name '$'.. How can I use jQuery with TypeScript ?

解决方案

Most likely you need to download and include the TypeScript declaration file for jQuery—jquery.d.ts—in your project.

Option 1: Install the @types package (Recommended for TS 2.0+)

In the same folder as your package.json file, run the following command:

npm install --save-dev @types/jquery

Then the compiler will resolve the definitions for jquery automatically.

Option 2: Download Manually (Not Recommended)

Download it here.

Option 3: Using Typings (Pre TS 2.0)

If you're using typings then you can include it this way:

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


After setting up the definition file, import the alias ($) in the desired TypeScript file to use it as you normally would.

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

You may need to compile with --allowSyntheticDefaultImports—add "allowSyntheticDefaultImports": true in tsconfig.json.

Also Install the Package?

If you don't have jquery installed, you probably want to install it as a dependency via npm (but this is not always the case):

npm install --save jquery

这篇关于如何在 TypeScript 中使用 jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆