Gozo
Gozo

Reputation: 149

Use jQuery in TypeScript in VS Code

I'm trying to add jQuery to a TypeScript project in Visual Studio Code. The goal is to use it via the $, as I would do in plain JavaScript, WITHOUT providing the jQuery tag in the head of my html.

I have my jquery and its definition installed on the project:

Packages

Hence, $ and intellisense is working like a charm:

VSCode

But opening the page I'm getting the error: "ReferenceError: $ is not defined".

I have read several related topics, including this, but the question there is about Visual Studio, and the last answer also suggest to load jQuery via tag in html, what I'm trying to avoid.

So how do I tell the ts compiler to include jQuery? I cannot import it because there is no export in jQuery. Am I missing something from tsconfig.json?

tsconfig

Upvotes: 4

Views: 3664

Answers (1)

Stewart_R
Stewart_R

Reputation: 14495

Your packages are installed in the node_modules folder. You need to somehow serve these up on the page. As it stands only your own javascript code is included (the /// <reference path='...' style reference is a design-time only thing) on the page.

You also need to include the jquery library in order to avoid the run-time error.

You have a couple of options:

  1. Simply reference the jquery script in your html (something you said you wanted to avoid)
  2. Use a build tool such as webpack or browserify/tsify to import your references and change the /// <reference path='...' reference to import * as $ from "jquery"; in which case the bundler will add the imported script to your outputed js file

More information here: http://www.typescriptlang.org/docs/handbook/integrating-with-build-tools.html

As an aside, this isn't really a typescript thing - if using plain js you would still either need to use the build tool with an import statement or have the jquery library loaded onto your page.

Upvotes: 2

Related Questions