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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With