Skip to main content

Working with jQuery in Typescript

Getting Started with jQuery in TypeScript

In this tutorial, we will be looking at how to work with jQuery in TypeScript. jQuery is a popular JavaScript library that simplifies HTML document traversal, event handling, and animation. By integrating jQuery with TypeScript, we can enjoy the benefits of static typing and other powerful features of TypeScript.

Setting Up the TypeScript Project

Before we begin, ensure that you have Node.js and npm (Node Package Manager) installed on your computer. If not, you can download them from here.

  1. Begin by initializing a new TypeScript project. Open a terminal and run:
mkdir ts-jquery-example
cd ts-jquery-example
npm init -y
  1. Install TypeScript and jQuery as dependencies:
npm install --save typescript jquery
  1. Also, install jQuery type definitions:
npm install --save @types/jquery
  1. Create a tsconfig.json file in your project root and add the following configuration:
{
"compilerOptions": {
"outDir": "./dist",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es6",
"allowJs": true
},
"include": [
"./src/**/*"
]
}

This configuration tells TypeScript to compile the .ts files in the src directory and output the resulting .js files to the dist directory.

Writing TypeScript Code with jQuery

Let's now write some TypeScript code that uses jQuery.

  1. Create a src directory in your project root and a main.ts file within it:
mkdir src
touch src/main.ts
  1. Open the main.ts file and add the following code:
import $ from 'jquery';

$(document).ready(() => {
$('body').html('<h1>Hello, TypeScript with jQuery!</h1>');
});

This code imports jQuery and uses it to set the HTML of the body element when the document is ready.

  1. Compile the TypeScript code to JavaScript by running:
npx tsc
  1. Now, you can use the compiled JavaScript code in an HTML file. Create an index.html file in your project root and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>TypeScript with jQuery</title>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
</head>
<body>
<script src="dist/main.js"></script>
</body>
</html>
  1. Open index.html in a web browser and you should see "Hello, TypeScript with jQuery!" displayed on the page.

Conclusion

In this tutorial, you learned how to set up a TypeScript project with jQuery and how to write TypeScript code that uses jQuery. Remember, TypeScript is a superset of JavaScript, so you can use any JavaScript library, including jQuery, in your TypeScript code. Happy coding!