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.
- Begin by initializing a new TypeScript project. Open a terminal and run:
mkdir ts-jquery-example
cd ts-jquery-example
npm init -y
- Install TypeScript and jQuery as dependencies:
npm install --save typescript jquery
- Also, install jQuery type definitions:
npm install --save @types/jquery
- 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.
- Create a
src
directory in your project root and amain.ts
file within it:
mkdir src
touch src/main.ts
- 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.
- Compile the TypeScript code to JavaScript by running:
npx tsc
- 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>
- 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!