Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery with Typescript 2

I'm new to Typscript 2. What i'm trying to do is to use jQuery within typescript. In this question i read that you need two things:

npm install --save-dev @types/jquery

This installs package '@types/jquery 2.0.39'.

"devDependencies": {
    "@types/jquery": "^2.0.39",
    "typescript": "^2.0.2",
    "typings": "^1.0.4"
  }

Then, in the Typescript file i put this:

import $ from "jquery";

but i got typescript error 'Cannot find module 'jquery'. What am I doing wrong?

Same error with

import $ = require("jquery");

Full typescript file:

import { Component } from '@angular/core';
import $ from "jquery";

@Component({
  selector: 'my-app',
  template: `<div id="test"></div>`,
})
export class AppComponent  {
    constructor() {
        $('#test').html('This is a test');
    }
}
like image 828
user2073333 Avatar asked Jan 24 '17 11:01

user2073333


2 Answers

You only install jquery's typings. You will need jQuery itself, too:

npm install jquery --save

Furthermore, since you use typescript@2, you don't need the typings package anymore. This will now be handled via npm and the @types packages, available at $types/{your-package}, in your case @types/jquery:

npm install @types/jquery --save
like image 113
k0pernikus Avatar answered Sep 25 '22 00:09

k0pernikus


I installed Visual Studio update (Tools -> Extensions and Updates) "Typescript 2.0.6 for Visual Studio 2015".

Also, I installed the following NuGet packages:

  • Microsoft.TypeScript.Compiler
  • Microsoft.Typescript.MSBuild

Then I installed jQuery and jQuery typings via npm:

npm install jquery @types/jquery --save

And finally, in tsconfig.json::

"compilerOptions": {
    ... other compiler options ...
    "typeRoots": [ "node_modules/@types/" ],
    "types": ["jquery" ]
  },

Now I can build the project and $ is recognized as jQuery inside the TypeScript.

like image 24
user2073333 Avatar answered Sep 22 '22 00:09

user2073333