7

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?

2
  • 1
    To be honest I can't see why you need jQuery with Angular at all. Commented Dec 4, 2017 at 11:42
  • Perhaps back then (Angular 4 times) this may have been needed in some cases. Nowadays however, JQuery should not be used in Angular apps in my opinion, just to make the world a better place. Commented Nov 12, 2020 at 6:51

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This solution worked in some pages. But at some places, I am using 'jquery-slimscroll' plugin. When I remove declare from there, it's giving me this error: "Property 'slimScroll' does not exist on type 'JQuery<HTMLElement>'."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.