BY ON Jul 27, 2018

How to load JQuery correctly on Angular

Sounds like a joke, I know :)

This is more a personal note because I had to spend more time than I expected to solve a related issue trying to use a JQuery plugin for a legacy code over Angular 6.

Please keep in mind the following, loading via the angular.json file it’s the equivalent to the script tag on a index.html page, so this will be loaded on a global scope. If you import it using the import statement then you get another copy. This is something based on ES6 modules handling.

Install JQuery and its plugins

You know, the usual:

npm i --save jquery

Ask Angular to load it

Go to the file angular.json and include there JQuery and any other plugin you need to load:

Put the $ and jQuery objects in the Typescript global context

To avoid intellisense and compiling issues, declare the following variables in a typings.d.ts file.

This is the main purpose of the typings file. To tell Typescript about those libraries that we commonly use to extend the Javascript environment. Give it a look to the oficial documentation about the typings file

This way you will be able to make use of jQuery in your components and allow those third party plugins to find it when they are loading. Remember: Don’t import it again or you will get a local copy without those plugins attached to it.