Utilizing Typescript and RequireJS for Incorporating jqueryui

Recently, I've been encountering issues with getting jQueryUI to function properly. Strangely enough, prior to attempting to integrate jQueryUI, using jQuery alone worked perfectly fine.

The current problem I'm facing is receiving a "TypeError: jQuery is not a function(...)" error in Chrome, even though jquery is designated as a dependency in the require.config file.

No errors occur during the compilation from .ts to .js.

Here is my initApp.ts code:

/// <reference path="../../../typings/jqueryui/jqueryui.d.ts"/>
import * as jQuery from "jquery"; //Operates without any issues
import * as jQueryUI from "jquery-ui"; //Module cannot be found unless the d.ts file is modified

After compilation to js:

define(["require", "exports", "jquery-ui"], function (require, exports, jQuery) {...}

This is the content of jqueryui.d.ts:

/// <reference path="../jquery/jquery.d.ts"/>
declare module JQueryUI { <unmodified code>}

//Added this declare

declare module "jquery-ui" {
  export = jQuery;
}

For Require.config.js:

require.config({
    baseUrl: "./components/",
    paths: {
        "jquery": "./javascripts/lib/jquery-2.1.4",
        "jquery-ui": "./javascripts/lib/jquery-ui",
        "go": "./javascripts/lib/go-debug"
    },
    shim: {
        "jquery": {
          exports: "jQuery",
        },
        "jquery-ui": {
            //exports: "jQuery", //Even adding this line does not resolve the issue
            deps: ["jquery"],
        }
    },
});
require(["./javascripts/initApp"]);

Directory Tree structure:

typings/
    jquery/
        jquery.d.ts
    jqueryui/
        jqueryui.d.ts
web/
    components/
        javascripts/
            lib/
                jquery-2.1.4.js
                jquery-ui.js
                require.js
            initApp.js
            initApp.ts
            require.config.js

Links to complete d.ts files can be found here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jquery/index.d.ts (jquery V3.3)

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jqueryui/index.d.ts (QueryUI V1.12)

If anyone could provide some assistance, it would be greatly appreciated.

Answer №1

When using jQuery and jQueryUi together, the situation is that jQuery has an export, while jQueryUi imports jQuery, enhances it, and then exports $.widget instead of $.

As previously mentioned,

import * as jQuery from 'jquery-ui';

causes issues.

Similarly,

import jQueryUi from 'jquery-ui';

fails because jQueryUi never gets utilized in a value position and thus gets removed by the compiler, which can be beneficial for certain loading scenarios despite being tricky to handle.

The solution lies in informing TypeScript to import the library regardless of its usage, meaning it's imported for its side effects only.

In this case, ECMAScript offers a specific import form for such situations. By simply writing:

import 'jquery-ui';

you signify your reliance on 'jquery-ui' solely for its side effects.

It's worth noting that shims for jQuery are no longer necessary nowadays.

All you really need is:

import $ from 'jquery';
// TypeScript will retain this syntax for importing solely for side-effects!
import 'jquery-ui';

No modifications should be required for your require.config(....), although there may be room for misinterpretation on my part.

Additionally, consider updating the jQuery-UI declarations, as the current link provided was inactive due to package restructuring. These declarations do not specify exports and refer to jQuery as a global entity, causing complications in multi-version .d.ts scenarios, though this likely won't impact runtime functionality in your specific scenario.

Answer №2

Encountering the same issue, I delved into various questions, finding the responses to be quite convoluted. Here's my simple solution:

By including reference paths at the beginning of each file, the problem is resolved with no further modifications necessary. TypeScript just needs to know where the definition files are located that outline all available functions. Adding a direct reference in each file addresses this issue:

/// <reference path="/typings/jquery.d.ts"/>
/// <reference path="/typings/someotherlibrary.d.ts"/>

Other suggested methods did not work for me. It could be due to my own shortcomings, or there might be bugs in the code or changes in the APIs. If you have a large number of files to resolve, this may not be the most efficient solution.

Answer №3

Previously, my workaround was included within the body of my question, but I am now reposting it as an answer to align with StackOverflow's editorial guidelines.

Aluan's response addresses some of the inquiries I raised in the preceding section.


To rectify the error manually, I edited the compiled javascript to incorporate the "jquery" and "jquery-ui" modules, assigning them to variables:

define(["require", "exports", "jquery", "jquery-ui"], function (require, exports, jQuery, jQueryUI) {...}

Nevertheless, I desired for the typescript compiler to automate this process, or something analogous to designate both jquery-ui and jquery as dependencies of my file.

The TypeScript interprets the declared module name and transforms that string into the dependency parameters of the AMD define() function. Consequently, the TypeScript definition d.ts file must declare the module by the same string that represents my library in require.config.js

Merely having an import statement does not prompt any action from the TypeScript compiler. The variable (foo, in this instance) into which the properties from the module/library are imported must be called at least once and should not clash with any existing variables in that scope.

Previously, I utilized this directive:

import * as jQuery from "jquery-ui"

This consumed the 'jQuery' variable name, causing the jQuery function to become unassignable to that variable name, resulting in the error: "jQuery is not a function(...)".

As jquery-ui merely extends the jQuery library, there is no need to invoke it. However, the compiler hesitated to actually compile jquery-ui as a dependency in my define(...). This issue was promptly resolved once I identified the underlying problem.

Final code


initApp.ts

/// <reference path="../../../typings/jqueryui/jqueryui.d.ts"/>
import * as jQueryUI from "jquery-ui";
uiVar from "./uiVariables";
jQueryUI

Compiled to js:

define(["require", "exports", "jquery-ui"], function (require, exports, jQueryUI) {...}

require.config.js

require.config({
    baseUrl: "./components/",
    paths: {
        "jquery": "./javascripts/lib/jquery-2.1.4",
        "jquery-ui": "./javascripts/lib/jquery-ui",
        "go": "./javascripts/lib/go-debug"
    }
});
require(["./javascripts/app"]);

Answer №4

I created a simple demonstration on GitHub showcasing how to utilize TypeScript 2 with ES 6 modules and JQuery / JQuery UI featuring custom plugins. If you're looking to learn more, feel free to check it out here: https://github.com/lgrignon/typescript-es6-jquery

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper way to reference a computed symbol that has been inherited as a function in an extended class

As a newcomer to Typescript, my understanding of the code might be lacking. I am currently working with the Klasa framework, which is built on top of Discord bot framework using Discord.js. The framework recently introduced plugin functionality and there a ...

combine multiple select options values in a single function using jQuery

My HTML code includes two select options for users to choose the origin and destination cities. I need to calculate the cost of travel between these cities. How can I compare the selected options using jQuery? </head> <body> <div> ...

Functions have been successfully deployed, but they are not appearing on the Azure Portal

I am experiencing difficulties deploying basic Typescript functions to Azure. Despite a successful deployment using VS code and confirmation in the Output window, I cannot see any functions listed in the Azure Portal under the Function App: https://i.stac ...

What is the best way to create a universal function that can return a promise while also passing along event

I created a specialized function that waits for an "EventEmitter" (although it's not completely accurate as I want to use it on other classes that have once but don't inherit from EventEmitter): export function waitEvent(emitter: { once: Function ...

Discover the inverse of Object Arrays interaction in TypeScript

My agent object has the following structure: agentObj = { "agentId": "saqib", "attributes": [ { "name": "Marketing", "type": "Boolean", }, { "name": "English", "type": "Profi ...

Moving icon that appears when hovering over a menu button

Before diving into this, please take a moment to visit the following website to understand my goal: You'll notice there is a noticeable RED arrow positioned below the menu. What I aim to accomplish is... when I hover over a menu button, the arrow smo ...

Is there a way to activate the jQuery UI calendar from a cloned textbox, rather than the initial one?

I am currently working with a table that includes a jQuery UI calendar datepicker. The table has been simplified for space, but the primary focus is on using the datepicker functionality within it. <table class="formInfo" cellpadding="0" cellspacing="0 ...

leveraging the power of JQuery and Ajax for submitting a form

I am looking to implement ajax functionality for form submission I want to achieve this using radio buttons instead of a submit button Essentially, when a radio button is clicked, the form should be submitted or posted My PHP page needs to determine whi ...

Troubleshooting: Issues with Integrating Javascript and CSS into

I'm still new to this platform, so please correct me if I make any mistakes. My goal is to create a "task table" that allows users to edit existing tasks and add new ones. Thanks to the base template provided by Ash Blue, I've managed to program ...

Using jQuery's AJAX method to serialize and upload form data

I'm currently facing an issue with uploading an image through an HTML form. The form gets added to a div when a user clicks on an item, and here's how the code looks: $("#editavatar").click(function(){ $(".rightdisplay").html('<form ...

Generating a highchart by retrieving JSON data using AJAX

I'm currently working on generating a basic chart on a webpage using data from a MySQL database that is fetched via a MySQL script. My main challenge lies in understanding how to combine the ajax call with the necessary data for the chart. I'm n ...

Comparison of jQuery, AngularJS, and Node.js

I'm a beginner in web development and I have some basic knowledge: HTML - structure of websites CSS - design aspect JavaScript - for adding interactivity Now, what exactly is jQuery, AngularJS, and Node.js? Upon researching, I discovered that jQue ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => ...

Refresh a webpage using JavaScript (inside a jquery ajax call)

Seeking guidance on how to reload a page using JavaScript, I have created the following function: function update(id, name) { if(/^\d+$/.test(id)) { $.ajax({ url: baseurl + "/url/action/param/" + id + "/param2/" + unescap ...

Guide to binding dates with PrimeNG's p-calendar

<p-calendar [showIcon]="true" [(ngModel)]="model.SelectedDate" name="SelectedDate"></p-calendar> I'm currently facing an issue in my HTML code where I am unable to bind model.SelectedDate from my TypeScript file successfully. My goal is t ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

What can be done to prevent an ajax call on keyup when there are no search results?

I have implemented an autofill search feature using .ajax call on keyup event. Currently, it triggers a new call when the user inputs more than 3 characters. However, I want to prevent additional ajax calls once there are no more results, allowing the user ...

Angular2/Typescript: Transforming a Javascript/Typescript Date into a C# DateTime string on the client side

Currently immersed in an Angular2/Typescript project, I am faced with the task of sending a date to a C# backend. Despite my extensive research, all I could uncover through Google searches was information on converting the date on the backend side. My la ...

Choose the option to replace "&" using regular expressions

I am currently working on a function that allows for selecting options and dynamically replacing a specific character in the URL. & The goal is to replace &amp; with & In the given code snippets, Jquery and Perl Template (jquery) are u ...

Tips for extracting title and image from someone else's blog posts to share on your own website

Currently, I am in the process of creating a website where I can showcase my personally curated content. I have been struggling to figure out how to seamlessly integrate this content into my site without relying on an API. My initial idea was to manually ...