Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import JQuery into a Typescript file?

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
like image 673
Tim Hutchison Avatar asked May 04 '17 12:05

Tim Hutchison


People also ask

Can we use jQuery in TS file?

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

Can you import jQuery in a JavaScript file?

Your JavaScript file ( scripts. js ) must be included below the jQuery library in the document or it will not work. Note: If you downloaded a local copy of jQuery, save it in your js/ folder and link to it at js/jquery. min.

Can I use jQuery in angular?

Adding jQuery to Angular You need to create an Angular application using ng new command and then you need to 'cd' into that folder to install jQuery via NPM in the development environment.


1 Answers

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.

like image 127
Marco Maldonado Avatar answered Oct 02 '22 22:10

Marco Maldonado