Using jQuery with Typescript 2
我是Typscript 2的新手,我想要做的是在Typescript中使用jQuery。 在这个问题上,我读到您需要做两件事:
1 | npm install --save-dev @types/jquery |
这将安装软件包" @ types / jquery 2.0.39"。
1 2 3 4 5 | "devDependencies": { "@types/jquery":"^2.0.39", "typescript":"^2.0.2", "typings":"^1.0.4" } |
然后,在Typescript文件中输入:
1 | import $ from"jquery"; |
但我收到打字稿错误"无法找到模块'jquery'。 我究竟做错了什么?
与相同的错误
1 | import $ = require("jquery"); |
完整的打字稿文件:
1 2 3 4 5 6 7 8 9 10 11 12 | import { Component } from '@angular/core'; import $ from"jquery"; @Component({ selector: 'my-app', template: ``, }) export class AppComponent { constructor() { $('#test').html('This is a test'); } } |
您仅安装jquery的类型。您也将需要jQuery本身:
1 | npm install jquery --save |
此外,由于您使用typescript @ 2,因此不再需要
1 | npm install @types/jquery --save |
我安装了Visual Studio更新(工具->扩展和更新)" Visual Studio 2015的Typescript 2.0.6"。
另外,我安装了以下NuGet软件包:
- Microsoft.TypeScript.Compiler
- Microsoft.Typescript.MSBuild
然后我通过npm安装了jQuery和jQuery类型:
1 | npm install jquery @types/jquery --save |
最后,在
1 2 3 4 5 | "compilerOptions": { ... other compiler options ... "typeRoots": ["node_modules/@types/" ], "types": ["jquery" ] }, |
现在,我可以构建项目,并且
我要做的是首先在项目目录中为
然后通过以下方式使用它:
一直有效。
Now I have errors in index.d.ts file, for instance: Line:
attr(attributeName: string, value: string|number|null): JQuery;
Error1: A parameter initializer is only allowed in a function or
constructor implementation. Error2: Type expected
不是回答您最初的问题,而是回答您的问题,因为我无权回答您的评论:
我遇到了相同的错误,这是一种解决方法,我从jQuery的index.d.ts中删除了有问题的行,并且能够使用whithin打字稿。我还不知道这是否会有任何不良的副作用,因此使用此方法后果自负。