如何将JQuery导入到Typescript文件中?

更新

无需导入。 相反,我需要添加对文件顶部的引用。 所以我的WebAPI.js的第一行应该是/// 而不是import { $ } from '../jquery-3.1.1';import { $ } from '../jquery-3.1.1';


我试图导入jQuery以在Typescript文件中使用,但我收到的各种错误与我尝试的一切。 我按照这里和这里的解决方案,但没有任何运气。

tsconfig.json

 { "compilerOptions": { "removeComments": true, "preserveConstEnums": true, "out": "Scripts/CCSEQ.Library.js", "module": "amd", "sourceMap": true, "target": "es5", "allowJs": true } 

WebAPI.js

 import { $ } from '../jquery-3.1.1'; export class ExpenseTransaction extends APIBase { constructor() { super(); } Get(): void { let expenses: Array; let self = this; $.ajax({ url: this.Connection, type: "GET", contentType: "application/json", dataType: "json", success: function (data: any): void { expenses = self.ConvertToEntity(data.value); }, error: function (data: any): void { console.log(data.status); } }); }; } 

我也尝试import * as $ from '../jquery.3.1.1'

错误

  • Module jquery-3.1.1 has no exported member $
  • Property ajax does not exist on type (selector: any, context: any) => any

你必须import * as $ from "jquery";导入它作为import * as $ from "jquery"; 根据typescript的文档和jquery的定义文件 ,模块被定义为环境模块:

 declare module "jquery" { export = $; } 

根据这个 :

环境声明是您使用编译器做出的承诺。 如果这些在运行时不存在并且您尝试使用它们,则事情将在没有警告的情况下中断。

希望能帮助到你!

不需要导入。 而是在文件顶部添加对Typescript定义文件的引用。 所以WebAPI.js的第一行应该是

 ///  

代替

 import { $ } from '../jquery-3.1.1'; 

根据DefinitelyTyped wiki:

TypeScript声明文件是在外部第三方JavaScript库中定义类型,函数和参数的方法。 通过在TypeScript代码中使用声明文件,将对正在使用的外部库启用Intellisense和类型检查。

jquery.d.ts是GitHub上的DefinitelyTyped库的一部分。 绝对可以通过NuGet包管理器在Visual Studio项目中包含Typed。

执行此操作:在使用npm安装jquery或与cdn一起使用之后

第一:

 npm install @types/jquery --save-dev 

之后:

从’jquery’导入*为$;

尝试用declare let $:any替换你的导入;