4

I want to use jquery in my Angular-TypeScript project. So I installed jquery like "npm install @type/jquery". Now when I try to serve it says:

error TS2592: Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i @types/jquery and then add jquery to the types field in your tsconfig.

How do I add jquery to the types field?

My Code:

let settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://api.com/getSomething",
  "method": "POST",
  "headers": {
    "x-rapidapi-host": "xxx",
    "x-rapidapi-key": "xxx",
    "content-type": "xxx"
  },
  "data": {}
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
Julius
  • 81
  • 1
  • 7
  • 1
    Possible duplicate of https://stackoverflow.com/questions/31173738/typescript-getting-error-ts2304-cannot-find-name-require – saglamcem Mar 16 '20 at 10:54

2 Answers2

9

It's very well explained in the error message. If you want to use TS, and use jQuery, you'll need the typings for jQuery. You can achieve this by running npm i @types/jquery in your project.

You will then need to add "jquery" in the types array in your tsconfig.app.json file, in the Angular application (might depend on your Angular version - best to check in the documentation).

Might I add - if you're using Angular, I'd say it's best not to use jQuery. Angular is already capable of doing everything. If you'd like to use jQuery, having an entire Angular application with it is a bit unnecessary.

saglamcem
  • 677
  • 1
  • 8
  • 15
  • Thank you for the simple explanation. I am using the RapidAPI and they only have jQuery. Is there a way using it whitout jQuery? – Julius Mar 16 '20 at 11:06
  • @Julius no problem! I'm not very familiar with RapidAPI - is it just a place where you use API's from? I'd appreciate an example about how "they only have jQuery", so I can help further. :) Because normally when you make a request to an API, it would give you back data in a specific format (JSON, XML etc). You could then use whatever technology you'd like to make use of that JSON, XML or whatever formatted response. – saglamcem Mar 16 '20 at 11:21
  • 1
    The response is as JSON. And you are right. I don't need jQuery I can write it myself :) – Julius Mar 17 '20 at 12:37
0

For someone coming from angular universal

you need to add in tsconfig.server.json also like i did

{
  "extends": "./tsconfig.app.json",
  "compilerOptions": {
    "outDir": "./out-tsc/server",
    "types": ["node", "jquery"]
  },
  "files": ["src/main.server.ts", "server.ts"]
}
Mohammed
  • 838
  • 6
  • 14