Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

globally declare $ or jQuery in angular 2/4

Tags:

angular

I am using jQuery in my angular 4 project. In every file I am declaring it on the top. I use this in most of my .ts files

declare const $: any;

Is there any way I can declare it in a single place and use it in all files, instead of declaring in every file?

like image 978
sunnyiitkgp Avatar asked Dec 04 '17 10:12

sunnyiitkgp


1 Answers

The better way of using JQuery in Angular is importing its .d.ts file, and using declare const $: any; is not the a good way since your IDE won't give you auto-completion and can run into some problems

Steps to use JQuery in Angular:

1- Find JQuery (or any other package you want) from TypeSeach, then you will end up on this NPM package, install it:

npm install --save @types/jquery

2- Install JQuery itself:

npm install --save jquery

3- Anywhere you want to use JQuery, just Import type declaration file (.d.ts) into Angular app:

import * as $ from 'jquery';

Read more on this article

When working with scripts that extend other libraries, for instance with JQuery plugins (e.g, $('.test').myPlugin();), since the installed @types/jquery may not include myPlugin, you would need to add an interface like the one below in src/typings.d.ts.

interface JQuery {
  myPlugin(options?: any): any;
}
like image 124
Mohammad Kermani Avatar answered Sep 30 '22 18:09

Mohammad Kermani