在使用Typescript的Aurelia中使用Jquery

我使用Aurelia与打字稿,使用aurelia-cli和npm作为构build系统和客户端包pipe理器。 我的目标是在我的一个.ts文件中使用jquery,所以我添加了jquery

npm install jquery@2.2.4 --save 

之后用于types我使用:

 typings install dt~jquery --global --save 

我还configuration了“jquery”作为供应商捆绑依赖的aurelia.json文件。

使用:

 import * as jq from 'jquery'; 

但该项目未能build立以下错误:

Starting 'readProjectConfiguration'... Finished 'readProjectConfiguration' Starting 'processMarkup'... Starting 'processCSS'... Starting 'configureEnvironment'... Finished 'processCSS' Finished 'processMarkup' Finished 'configureEnvironment' Starting 'buildTypeScript'... typings/globals/jquery/index.d.ts(3218,13): error TS2403: Subsequent variable declarations must have the same type. Variable '$' must be of type 'cssSelectorHelper', but here has type 'JQueryStatic'. [17:45:00] gulp-notify: [Error running Gulp] Error: typings/globals/jquery/index.d.ts(3218,13): error TS2403: Subsequent variable declarations must have the same type. Variable '$' must be of type 'cssSelectorHelper', but here has type 'JQueryStatic'.

所以我的代码有什么问题?

这是一个已知的问题,是由jQuery和Protractortypes定义之间的冲突造成的。

看到这里和这里 。

两者都宣布'$'为全球。 量angular器使用$('css')作为快捷方式select器,导致与jQuery发生冲突。

有几个解决方法 – 前两个是重命名为Protractor或jQuery的声明(这是jQuery的前两个答案)。 如果你宁愿留下jQuery的'$',然后重命名全球的量angular器。 你可以在your-project-directory\typings\globals\angular-protractor\index.d.tsfind声明(这是我在Aurelia + gulp / jspm项目中的位置)。 查找行declare var $: cssSelectorHelper; 并完全编辑或注释掉。

或者,如果您不打算使用量angular器,则将其从您的项目中完全移除。

如果你需要量angular器和jQuery,然后尝试卸载量angular器types(从而删除量angular器全局声明) – 请参阅aureliajsrocks.com上的这篇文章 。 本文还指出,这只是一个转译错误:

尽pipeProtractor声明了一个与jQuery冲突的$variables,但是在运行应用程序时,实际上并没有将Protractor加载到内存中。 所以在运行时不会和jQuery发生冲突。

发生这个问题是因为Protractor TypeScript定义文件是全局的,即使实际的.js库本身没有被加载,也是由转译器加载的。

如果您需要有jQuery并运行Protactortesting,那么现在看起来像最好的解决scheme,希望这将得到解决,或者如果任何人有更好的解决scheme,那么请分享…

只需要将jquery d.ts模块声明更改为:

 declare module "jquery" { export var $:JQueryStatic; export var jquery:JQueryStatic }