1

While trying to implement TypeScript with my codebase, I run into this problem. It seems that the way I used to load jQuery and AngularJS in sequence, AngularJS would pick up on the presence of jQuery and extend itself with its functionality. However, when importing locally in a module, AngularJS gets loaded in isolation and cannot seem to extend itself with jQuery. Therefore, when I do something like this:

import * as $ from 'jquery';
import * as angular from 'angular';

export default ['$window', function($window) {
  let position = angular.element($window).scrollTop();
}];

I get this TypeScript error:

Property 'scrollTop' does not exist on type 'JQLite'.

How can I load AngularJS in a way that it knows it can use jQuery and will extend itself with it?

  • please visit :- https://stackoverflow.com/questions/24984014/how-can-i-stop-property-does-not-exist-on-type-jquery-syntax-errors-when-using – Parth Raval Jan 04 '18 at 08:51
  • using any bundlers like webpack or?angular takes jQuery from window object.so its not appended to the window object. – zabusa Jan 04 '18 at 08:52
  • @zabusa indeed that seems to be the case. But is there a way to fix that, perhaps depending on how you set up your webpack configuration? – Lucas van Heerikhuizen Jan 04 '18 at 09:08
  • @LucasvanHeerikhuizen yes.if you are using webpack there is a way or any other bundlers – zabusa Jan 04 '18 at 09:10
  • @ParthRaval the suggested solution in your linked topic does seem to work in the specific case, reducing it to a jQuery - or in this case rather a JQLite - problem. Having to wrap everything in (angular.element($window)).scrollTop(); does look horrible though! – Lucas van Heerikhuizen Jan 04 '18 at 09:11
  • Aren’t you just missing the Type Definitions file? The code is there but your IDE is missing type information. – Kokodoko Jan 04 '18 at 09:45

2 Answers2

0

if you are using webpack then we can use expose-loader library to load jQuery to window object.

webpack v1 usage

module: {
  loaders: [
    { test: require.resolve("jquery"), loader: "expose-loader?$!expose-loader?jQuery" },
  ]
}

webpack v2 usage

module: {
  rules: [{
          test: require.resolve('jquery'),
          use: [{
              loader: 'expose-loader',
              options: 'jQuery'
          },{
              loader: 'expose-loader',
              options: '$'
          }]
      }]
}

for more details goto expose-loader

zabusa
  • 2,520
  • 21
  • 25
0

Based on the link @ParthRaval shared, I was able to fix the problem by typecasting the JQLite base to an 'any' type. So indeed it turned out to be a typecasting problem rather than AngularJS not picking up on loading and using jQuery in full. Wrapping it in a function makes it less ugly.

import * as $ from 'jquery';
import * as angular from 'angular';

export default ['$window', function($window) {

  let position = JQLiteFix(angular.element($window)).scrollTop();

  function JQLiteFix(query) {
    return <any>query;
  }

}];