Typescript and JQuery compile error: Cannot find name '$'

Mark Yuan picture Mark Yuan · Jul 9, 2016 · Viewed 44.5k times · Source

I'm testing typescript with jquery, but when I compile the test.ts file, it always gives me an error indicating: Cannot find name '$'.

I've already imported jquery & added its definition reference. If I use import $ = require("jquery") in my test.ts file, another error "Cannot find module jquery" will occur when doing the tsc compiling. However, the JQuery folder already exists within the node_modules folder.

Does anyone know what is the correct way to use jquery in typescript?

Below is my steps:

  1. Install jquery using npm install jquery --save
  2. Install typings & jquery definition using typings install --global --save dt~jquery
  3. Add jquery reference at top of test.ts /// <reference path="../../../typings/globals/jquery/index.d.ts" />

tsconfig.json

{
    "compilerOptions": {
        "jsx": "react",
        "outDir": "./dist",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "experimentalDecorators": true
    },
    "exclude": [
        "node_modules"
    ],
    "files": [
        "./typings/index.d.ts",
        "./src/wo/tests/test.ts",
    ]
}

test.ts

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

let test:any=$("div");

Answer

Ignatius Andrew picture Ignatius Andrew · Aug 7, 2017

If you find these errors 90% of the time its because of versioning Problem of @types/jquery

Try running:

 npm install jquery --save

Then in app.module.ts:

import * as $ from 'jquery';

Then run:

  npm install @types/[email protected]

And you should be ready to go.