208

I am trying

$(function(){ 
    alert('Hello'); 
});

Its showing this error in Visual Studio: (TS) Cannot find name '$'.. How can I use jQuery with TypeScript ?

Kurtis Jungersen
  • 2,204
  • 1
  • 26
  • 31
JavaScript Linq
  • 2,605
  • 3
  • 13
  • 12

15 Answers15

261

Most likely you need to download and include the TypeScript declaration file for jQuery—jquery.d.ts—in your project.

Option 1: Install the @types package (Recommended for TS 2.0+)

In the same folder as your package.json file, run the following command:

npm install --save-dev @types/jquery

Then the compiler will resolve the definitions for jquery automatically.

Option 2: Download Manually (Not Recommended)

Download it here.

Option 3: Using Typings (Pre TS 2.0)

If you're using typings then you can include it this way:

// 1. Install typings
npm install typings -g
// 2. Download jquery.d.ts (run this command in the root dir of your project)
typings install dt~jquery --global --save

After setting up the definition file, import the alias ($) in the desired TypeScript file to use it as you normally would.

import $ from "jquery";
// or
import $ = require("jquery");

You may need to compile with --allowSyntheticDefaultImports—add "allowSyntheticDefaultImports": true in tsconfig.json.

Also Install the Package?

If you don't have jquery installed, you probably want to install it as a dependency via npm (but this is not always the case):

npm install --save jquery
David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • 9
    Had to reboot visual studio for it to work, small step but tripped me up for a little. – William Howley Oct 31 '16 at 14:02
  • how do you use the new ```npm install --save-dev @types/jquery ```? Where to find more infos about this please? – daslicht Nov 11 '16 at 18:42
  • 1
    @daslicht check [this question](https://stackoverflow.com/questions/38444279/how-should-i-use-types-with-typescript-2) – David Sherret Nov 11 '16 at 18:43
  • 6
    to help others: Then you just need to install jquery: npm install jquery and use it with import $ = require('jquery'); – Jonathan Nov 25 '16 at 18:18
  • 36
    Could also use `import * as $ from 'jquery'` – galdin Feb 23 '17 at 20:39
  • Thanks to William Howley :) That tip was all I need together with the answer option 1. – MartinJH Mar 31 '17 at 11:15
  • How is `/// ` related to all this? – Martin Wickman May 01 '17 at 15:09
  • 1
    I am getting error `Error TS1192 Module '"jquery"' has no default export.` – Karthik Aug 15 '17 at 14:02
  • Ugh. "Uncaught ReferenceError: exports is not defined". I can't remember how I solved this in the past! – Chuck Le Butt Oct 04 '17 at 17:47
  • What do you mean "In your project run..." a cmd prompt and cd to the project directory then type the command? Or is there a place 'in the project' within visual studio to type this? – pperrin Sep 10 '18 at 19:41
  • @pperrin updated the answer. Run the command in the root directory where *package.json* is located – David Sherret Sep 12 '18 at 04:00
  • Note sure why, but i had to do what @shobi suggested below as well. npm install jquery --save // save jquery as a dependency – Emile Aug 13 '19 at 20:00
  • 1
    It's also important to add it into the types section in the ts.config like @The One mentions in his [good answer](https://stackoverflow.com/a/54270462/1057791) – BornToCode Sep 16 '19 at 09:43
  • I realise that angular can't find the jquery if you didn't install it first with this command `npm install --save jquery` also you might want to use `-- force` flag according to npm install error message . It works for me . – AkiZukiLenn Jul 27 '22 at 15:03
39

In my case I had to do this

npm install @types/jquery --save-dev // install jquery type as dev dependency so TS can compile properly
npm install jquery --save // save jquery as a dependency

Then in the script file A.ts

import * as $ from "jquery";
... jquery code ...
Shobi
  • 10,374
  • 6
  • 46
  • 82
35

For Angular CLI V2+

npm install jquery --save
npm install @types/jquery --save

Make sure jquery has an entry in angular.json -> scripts

...
    "scripts": [
        "node_modules/jquery/dist/jquery.min.js"
    ]
...

Go to tsconfig.app.json and add an entry in "types"

{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": ["jquery","bootstrap","signalr"]
    },
    "exclude": [
        "test.ts",
        "**/*.spec.ts"
    ]
}
The One
  • 4,560
  • 5
  • 36
  • 52
30

FOR Visual Studio Code

What works for me is to make sure I do the standard JQuery library loading via a < script > tag in the index.html.

Run

npm install --save @types/jquery

Now the JQuery $ functions are available in all .ts files, no need of any other imports.

Sydwell
  • 4,954
  • 1
  • 33
  • 36
  • 2
    You do need to declare jquery/$ in your Component, If TsLint is On for these types of Type Checkings. For Eg. ```javascript declare var jquery: any; declare var $: any; ``` – phoenisx Oct 23 '17 at 10:22
  • 1
    @Subroto, Your suggestion is working OK. Put it as an answer. Thanks. – yW0K5o Aug 17 '18 at 13:29
22

I believe you may need the Typescript typings for JQuery. Since you said you're using Visual Studio, you could use Nuget to get them.

https://www.nuget.org/packages/jquery.TypeScript.DefinitelyTyped/

The command in Nuget Package Manager Console is

Install-Package jquery.TypeScript.DefinitelyTyped

Update: As noted in the comment this package hasn't been updated since 2016. But you can still visit their Github page at https://github.com/DefinitelyTyped/DefinitelyTyped and download the types. Navigate the folder for your library and then download the index.d.ts file there. Pop it anywhere in your project directory and VS should use it right away.

Licht
  • 1,079
  • 1
  • 12
  • 27
19

UPDATE 2019:

Answer by David, is more accurate.

Typescript supports 3rd party vendor libraries, which do not use Typescript for library development, using DefinitelyTyped Repo.


You do need to declare jquery/$ in your Component, If tsLint is On for these types of Type Checkings.

For Eg.

declare var jquery: any;
declare var $: any;
phoenisx
  • 1,507
  • 17
  • 28
  • "if they have their typing installed" I do not get get it. You mean NOT installed? Why declare them as any otherwise? I just want to compile without errors and not install any extra stuff and I am working with libs that have no types to install. – redanimalwar Oct 21 '19 at 14:12
  • @redanimalwar I think I wrote that, because in web projects like reactjs/angular, if webpack is configured manually, 3rd party libraries are defined globally, and it's difficult to tell webpack where these libraries are imported from, thus `declare` keyword is used. But, still we can tell vscode about typings if they are present in `node_modules`, that's why installing typings help in intellisense, but for a vanilla webpack project, without `declare` keyword project transpilation fails. I have removed my statement from the answer, to not confuse people. – phoenisx Oct 21 '19 at 17:19
  • Anyways, I haven't fiddled with Angular/Typescript for a long time now, but I feel, if typings are installed, we could've done something like this - `import JQuery from 'jquery'; declare var $: JQuery;`. Not sure, if this will work. – phoenisx Oct 21 '19 at 17:24
  • I have been using - https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types, in tsconfig, to suppress 3rd party type issues. – phoenisx Oct 21 '19 at 17:29
7

Here is my TypeScript & jQuery config steps.

It makes jQuery's types support to work better than the most articles in the internet . ( I believe. )

first:

npm install jquery --save
npm install @types/jquery --save-dev




second( very very very important ! ! ! ):

import jquery = require("jquery");



// this helps TypeScript to understand jQuery best !!!  otherwise It will confused .
const $: JQueryStatic = jquery;




then , You Can Enjoy It :

$(document).ready(function () {
    $('btn').click(function () {
       alert('I am clicked !')
    }
}




It's silky smooth !!!

Lancer.Yan
  • 857
  • 13
  • 10
  • so, have to write it in every component ts file? – Humble Dolt Aug 19 '19 at 10:14
  • @HumbleDolt If you bind jQuery on 【window】 , you just need add ```declare global { interface Window { $ :JQueryStatic; } }``` in yourTypeDeclaration.d.ts . And in properly consider , you need check whether $ is mounted in 【window】. Such as ```import $ = require('jquery'); window.$ = $ ;``` , or your jQuery【$】 has been mounted by external script tag . – Lancer.Yan Aug 19 '19 at 12:12
  • you mean, can include a script in index.html and write that there? typeDeclaration.ts in angular 8 ? there is tsconfig.json – Humble Dolt Aug 19 '19 at 12:14
  • @HumbleDolt So , you can try the second solution ```import $ = require('jquery') ; window.$ = $;``` . (You'd best init this one , in your project start point . And I prefer to create a ```sdk``` dir , to manage all outer lib's requirement and initial in one file or place ). – Lancer.Yan Aug 19 '19 at 12:18
  • @HumbleDolt 【yourTypeDeclaretion.d.ts】 is just a Type-Defined file . It is a special file to defined your self types . In TypeScript , 【.d.ts】 is just a explicit isolation way , to distinguish type-recognize and true-code . You can also write the type-declaration-snipet in a 【.ts】 file , it will still works . (maybe with some grammar fix notice) – Lancer.Yan Aug 19 '19 at 12:31
7

You can declare globals by augmenting the window interface:

import jQuery from '@types/jquery';

declare global {
    interface Window {
        jQuery: typeof jQuery;
        $: typeof jQuery;
    }
}

Sources:

Joe Maffei
  • 1,855
  • 1
  • 15
  • 18
6

If you want to use jquery in a web application (e.g. React) and jquery is already loaded with <script src="jquery-3.3.1.js"...

On the webpage you can do:

npm install --save-dev @types/query
and the use it with:
let $: JQueryStatic = (window as any)["jQuery"];

so, you don't need to load jquery a second time (with npm install --save jquery) but have all the advantages of Typescript

Brandon
  • 16,382
  • 12
  • 55
  • 88
  • This solved my problem. I have downloaded a template that includes many jquery libraries. I struggled to make it work with react. I just needed to change let $: JQueryStatic = (window as any)["jQuery"] to let $: any = (window as any)["jQuery"] and now I can call every library such as $.HSCore.components.... – Mak Suriya Jacobsen Oct 29 '20 at 12:57
5

This work for me now and today at Angular version 9

  1. Install via npm this: npm i @types/jquery just add --save to setup globally.
  2. Go to tsconfig.app.json and add in the array "types" jquery .
  3. ng serve and done.
3

My procedure for VS 2019 in a ASP.Net core project. So I don't have to mess around with the npm command line utility, and take a declarative approach using the npm config file.

  1. Do you have a package.json (npm dependencies config) in the root of your project?

    • If no, right click project -> Add -> New item -> (Search npm) Select npm Configuration File and keep default filename package.json
  2. Add an entry under devDependencies. This tells npm to install "@types/jquery" which is a npm package maintained by DefinitelyTyped. This is essentially the same as the npm install command shown in other answers.

    "devDependencies": {
      "@types/jquery": "3.5.1"
    }
    
  3. Supposedly upon saving the file this should trigger the npm package install. I find I have to right click the package.json file and click Restore Packages (option not shown while project is in debug mode).

    • The first time you run npm restore, you should switch to the Output tab/window and change dropdown to "npm" to verify there were no errors.

package.json Restore Packages Output window npm selection

  1. You should see a new item under Project -> node_modules/@types/jquery/
    • index.d.ts is the main typescript definition file, which references the others.

node_modules jquery typedef files

  1. Open your own typescript file, and drag the index.d.ts from the Solution Explorer onto the first line of your open typescript file. This should add at the top(relative path will vary depending on your typescript file's location):

    /// <reference path="../node_modules/@types/jquery/index.d.ts" />
    
  2. Now if you start writing code inside a function of your typescript file you should be able to type jQue and get intellisense completion prompts.

typescript completion prompt for jQuery

Note: Lately VS has been really bad about not reflecting various changes properly until you restart, especially things involving errors-as-you-type and intellisense. You can often see even in official MS documentation them mentioning restarts needed to resolve red squigglies for example. So when in doubt, close/reopen VS. The last step is the most likely place you might find intellisense isn't working till you restart.

This method works regardless of whether you are including jQuery using a non-npm method. For example, in one project we were not using imports, npm, js modules, nor requireJS to resolve dependencies. jQuery was just a script tag link from html pages. However, I can still reference the .d.ts jQuery typedefs in order to get typescript completion/type resolution.

I could easily add a dependency in package.json for "jquery": "3.5.1" to get jQuery itself.

Also note if VS is working properly it has some slow(due to web queries) name and version completion prompts in the package.json:

package.json completion hints

AaronLS
  • 37,329
  • 20
  • 143
  • 202
1

After installation of jquery and @types/jquery (as dev dependency), use this import:

import * as $ from "jquery";

In my case only this way was helpful. (angular9)

afruzan
  • 1,454
  • 19
  • 20
1

Step 1. I am using yarn, you can install the jQuery & jQuery's Types following cmd.

yarn add jquery
yarn add @types/jquery -D

Step 2 In your tsx file add

import jquery from 'jquery';
const $: JQueryStatic = jquery;

Step 3: You can as the jQuery into your react component.

useEffect(() => {  
  $(() => {
    console.log("Hello JQuery!");
  });
}, []);
pilathraj
  • 59
  • 6
0

This works for me:

export var jQuery: any = window["jQuery"];
Salar
  • 2,088
  • 21
  • 26
  • 1
    This would work but wouldn't function as strongly typed, which loses the benefits of using it with TypeScript a work around if you will for external libraries. Still quite an interesting approach. – bnns Jan 24 '19 at 07:29
0

This block of code would need to be in a function, not outside a function in the class. Otherwise you would get the error you describe.

Markus
  • 1,020
  • 14
  • 18