How to import JQuery into a Typescript file?
Asked Answered
E

7

39

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
Ensoul answered 4/5, 2017 at 12:46 Comment(4)
Did you install the typings? npm install --save-dev @types/jquery Olpe
@Olpe I have the typings/jquery/jquery.d.ts file from NuGet. Is that the same thing?Ensoul
Did you install this package? nuget.org/packages/jquery.TypeScript.DefinitelyTypedOlpe
@Olpe Yes I didEnsoul
E
25

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.

Ensoul answered 31/5, 2017 at 2:45 Comment(0)
M
41

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.

Marva answered 29/5, 2017 at 4:43 Comment(1)
Easiest would be just import * as jQuery from 'jquery'; and then use jQuery instead of $ everywhere.Rhythm
E
25

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.

Ensoul answered 31/5, 2017 at 2:45 Comment(0)
L
22

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

first:

npm install @types/jquery --save-dev

and after:

import * as $ from 'jquery';

Lamkin answered 10/6, 2018 at 1:6 Comment(0)
G
5

es5

Importing is as simple as:

import * as $ from 'jquery';

But only if we install related .d.ts files:

npm install @types/jquery --save-dev

es6

Same as above, but if you want to be able to use "$" as function, to listen for document-ready event (like "$(function () { ... })"), then continue reading.

First, in tsconfig.json file, do something like:

{
    "compilerOptions": {
        "esModuleInterop": true
    }
}

Then import without "* as " part, like:

import $ from 'jquery';

See also stackoverflow.com/Understanding-esModuleInterop

Geehan answered 8/2, 2022 at 14:42 Comment(0)
C
3

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.

Conflagrant answered 8/2, 2019 at 14:57 Comment(2)
My tsconfi doesn't have typeRoots defined. which still references @types. Because of this I am having issue. It doesn't compain at compile time but at runtime it gives error. So even if I dont include import it is not complaining.Sanjuanitasank
Maybe define it? Check out the docs here: typescriptlang.org/docs/handbook/tsconfig-json.html under "@types, typeRoots and types". It describes how, by default, it tries to find all visible @types, and it seems this behavior is not working for you in prod.Conflagrant
D
0

Try replacing your import with declare let $ : any;

Dunnite answered 20/9, 2018 at 12:0 Comment(1)
The problem with doing this is that you lose all Intellisense and type-checking against the JQuery namespace.Barfly
W
0

In visual studio community, to do the work I have to add jquery in html at head / script section, then add my app.ts just under jquery script section then I add the reference to jquery lib in my typescript source.

In html page, head section :

<script src="./Scripts/jquery-3.5.1.js"></script>
<script src="app.js"></script>

In app.ts, first line of ts script :

/// <reference path ="./Scripts/typings/jquery/jquery.d.ts"/>
Wanton answered 13/9, 2020 at 14:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.