4

I'm trying to intregate JQUERY into Typescript but I hit a brick wall and I don't know how to get over it. Bear in mind that I'm a newbie when it comes to Typescript (been messing with it for a couple of months only), so there is a chance that this problem is very easy to solve but I can't figure it out.

So, I have this very simple program in TS:

/// <reference path="node_modules/@types/jquery/index.d.ts" />

function PrintName()
{
    let name:any = $('#txtName').val();
    console.log(name);
}

But when I run it in the web I get the error: Uncaught ReferenceError: $ is not defined at PrintName

But, when I include this line in the HTML:

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

It works just fine. So, how can I add Jquery to the Typescript ? I tried with this command:

npm install --save-dev @types/jquery

And then adding the reference to index.d.ts, but I get the same error. I'm using Visual Studio Code 1.27, tsc 3.0.1 and npm 3.5

Thanks!

2 Answers 2

3

Installing @types/jquery only gives you type information for jQuery; you still have to load an implementation at runtime. Using a separate <script> tag is OK. If you want to produce a single JavaScript file that includes your code as well as libraries it depends on that are packaged in module form (such as jQuery), you'll need to use a module bundler such as Webpack, Rollup, or Browserify; the TypeScript compiler is not capable of doing this by itself.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, I would have to check those modules then. Thanks!
-1

add dependencies: type in CLI.

npm --save jquery
npm --save jquery-ui-bundle

in angular-cli.json:

"scripts": [ 
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/jquery-ui-bundle/jquery-ui.js"], ...

then in your component use:

declare var jQuery:any; // jQuery is the same as $

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.