How to import jQuery in an Ionic project?


#1

Hi all,

there are already a bunch of posts regarding jQuery and Ionic 2, but as nearly all of them are from mid '16 and the mentioned possible solutions target a beta or RC and therefore don’t seem to work anymore, it is time to start a new request on how to achieve this:

don’t get me wrong, i myself do not need to use jQuery at all, but i want to use a third party npm package (ng2-signalr) which relies on the existence of “window.jQuery”.

I did install jQuery with
npm install jquery --save
npm install @types/jquery --save

and tried to import it with different syntax
import * as jQuery from ‘jquery’;
or
import jQuery from ‘jquery’;

but window.jQuery is not defined at all…

Regarding angular2 in general i read something about adding an package entry in the angular-cli config, but i did not find something like that in the ionic project structure…

So can anyone give a hint on how to get jQuery defined in window.jQuery?

thanks
Hannes

My Ionic info:
Cordova CLI: 6.4.0
Ionic CLI Version: 3.0.0-beta.4
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.9.4
Xcode version: Not installed


#2

yeah because you should not use window.jQuery.

therefore you are doing this:

import * as jQuery from 'jquery';

So you can use jQuery in that module/file.
if you need jquery in another part --> import it there.


#3

As i already mentioned in my first post: my Ionic App itself does NOT use jQuery inside the app code!
The App utilizes a npm package which apparently needs jQuery to be globally available via window.jQuery - so you could point out a thousand times “you should not use window.jQuery”, but i have no influence on that (besides not using that package at all or forwarding your post to the developers of that package and hope they eventually will refactor their code; some time…)

So back to some helpful:
Even the current Ionic Docs states that it is possible to include jQuery via script tag (see last passage at: https://ionicframework.com/docs/v2/resources/app-scripts/ ):

When jQuery is included in a web browser, it can be accessed from window.jQuery. In the above example, we’re mapping jQuery to the window.jQuery object. From here, jQuery can be used through the Typescript code without issue.

But there isn’t described how to bundle jquery.min.js so that it can be accessed via script tag…
Any hint on that?


#4

A post was split to a new topic: How to import jquery.marquee