How to import JQuery into a Typescript file?

65,717

Solution 1

An import is not required. Instead, add a reference to the Typescript definition file the top of the file. So the first line of the WebAPI.js should be

/// <reference path ="../typings/jquery/jquery.d.ts"/> 

instead of

import { $ } from '../jquery-3.1.1';

According to the DefinitelyTyped wiki:

A TypeScript declaration file is way of defining the types, functions and parameters in an external third-party JavaScript library. By using a declaration file in your TypeScript code will enable Intellisense and type checking against the external library you are using.

jquery.d.ts is a part of the DefinitelyTyped Library found on GitHub. Definitely Typed can be include in Visual Studio projects via the NuGet Package Manager.

Solution 2

You have to import it as import * as $ from "jquery";, according to typescript's documentation, and jquery's definition file the module is defined as an ambient module:

declare module "jquery" {
    export = $;
}

According to this:

Ambient declarations is a promise that you are making with the compiler. If these do not exist at runtime and you try to use them, things will break without warning.

Solution 3

do this : after installing jquery with npm or used with cdn

first:

npm install @types/jquery --save-dev

and after:

import * as $ from 'jquery';

Solution 4

Tim's solution using the reference compiler directive works, however there is an easier way now.

In tsconfig.json, if you set typeRoots, you don't need to do anything at all in your .ts files. TypeScript does the work for you.

How does it work?

In my solution, I pull in all my @types via npm, so those are placed at ./node_modules/@types. I also have a few types I created by hand at ./@types.

In my tsconfig.json, I added:

 "compilerOptions": {     
   // lots of other config here
   "typeRoots": [
     "./node_modules/@types",
     "./@types"
   ]
  }

Now all my types are discovered and used by the compiler automatically, so there's no need to bother with reference tags!

In conclusion...

I should note that if you do this and you try to explicitly import jquery, it will fail, and you will be confused. I sure was.

Share:
65,717
Tim Hutchison
Author by

Tim Hutchison

I'm a Senior Software Engineer at Cohen &amp; Company in Cleveland, OH. We build internal applications using Typescript, Vuejs, Nodejs, and Expressjs that improve the efficiency and operations of the company. In my free time I enjoy playing various sports (primarily golf and ping pong), watching football and hockey, mentoring high schoolers, reading, and spending time with friends.

Updated on February 09, 2022

Comments

  • Tim Hutchison
    Tim Hutchison over 2 years

    Update

    No import was required. Instead, I needed to add a reference to the top of the file. So the first line of my WebAPI.js should have been /// <reference path ="../typings/jquery/jquery.d.ts"/> instead of import { $ } from '../jquery-3.1.1';


    I am trying to import jQuery to use in a Typescript file, but I am receiving a variety of errors with everything I try. I followed the solutions here and here, but without any luck.

    tsconfig.json

    {
        "compilerOptions": {
            "removeComments": true,
            "preserveConstEnums": true,
        "out": "Scripts/CCSEQ.Library.js",
        "module": "amd",
            "sourceMap": true,
        "target": "es5",
        "allowJs": true
    }
    

    WebAPI.js

    import { $ } from '../jquery-3.1.1';
    
    export class ExpenseTransaction extends APIBase {
    
        constructor() {
            super();
        }
    
        Get(): void {
            let expenses: Array<Model.ExpenseTransaction>;
            let self = this;
            $.ajax({
                url: this.Connection,
                type: "GET",
                contentType: "application/json",
                dataType: "json",
                success: function (data: any): void {
                    expenses = self.ConvertToEntity(data.value);
                },
                error: function (data: any): void { console.log(data.status); }
            });
        };
    }
    

    I have also tried import * as $ from '../jquery.3.1.1'

    Errors

    • Module jquery-3.1.1 has no exported member $
    • Property ajax does not exist on type (selector: any, context: any) => any