Utilizing webpack, gulp, and typescript to efficiently incorporate jQuery plugins

I'm having trouble figuring out the correct way to load third-party libraries that have dependencies on each other. I am using TypeScript and Gulp with either Webpack or SystemJS for my module loader, both of which are throwing similar errors in this situation. My application code runs smoothly with just jQuery, but as soon as I try to incorporate a jQuery plugin like jQuery Validation, I encounter issues with both Webpack and SystemJS indicating that jQuery is undefined.

There is quite a bit of configuration involved in both setups. Let me illustrate my most recent attempt with Webpack:

Here is my main.ts file:

import * as $ from "jquery";
// if I comment out these two imports, the '$("body").css...' line works
import "../bower_components/jquery-validation/dist/jquery.validate";
import "../bower_components/jquery-validation-unobtrusive/jquery.validate.unobtrusive";

$("body").css("color", "red");

The gulpfile used to generate the output:

var gulp = require('gulp'),
    webpack = require("gulp-webpack");

gulp.task("tsc-webpack", function () {
    return gulp.src("app/main.ts")
        .pipe(webpack({
            output: {
                filename: "main.js"
            },
            module: {
                loaders: [
                    { test: /\.tsx?$/, loader: "ts-loader" }
                ]
            }
        }))
        .pipe(gulp.dest(appDir + "js"))
});

My tsconfig.json file:

{
"compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "commonjs"
},
"exclude": [
    "node_modules"
]
}

Here is the error I am encountering in the Chrome developer console:

Uncaught ReferenceError: jQuery is not defined
    at Object.<anonymous> (main.js:12312)
    at __webpack_require__ (main.js:20)
    at Object.<anonymous> (main.js:51)
    at __webpack_require__ (main.js:20)
    at Object.defineProperty.value (main.js:40)
    at main.js:43

And here is the block in the generated file that is causing the error (last line):

(function ($) {
    var $jQval = $.validator,
    // ...
    $(function () {
        $jQval.unobtrusive.parse(document);
    });
}(jQuery));

Answer №1

My preferred method for incorporating jQuery into webpack is as follows:

module: {                                
  rules: [
    {  test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery' },
  ]
},
plugins: [
  new webpack.ProvidePlugin({
    '$': 'jquery',
    'jQuery': 'jquery',
    'window.jQuery': 'jquery'
  }),
]

Webpack should recognize amd/commonjs, and it seems that jquery-validation specifically checks for define.

For more information on shimming, visit this link: https://webpack.js.org/guides/shimming/

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

Utilize MaxMind GeoIP2 to identify the city accurately

I have been using this simple code to retrieve the city name through the maxmind service (geoip2). It has been working flawlessly and I am grateful to a fellow member of this site who shared this code with me. However, there is an issue when the user&apos ...

The array containing JSON objects enclosed within curly braces is causing a syntax error

Given a variable containing data that looks like an "array" with JSON Objects inside (even though it is not actually formatted as an array, starting and ending with curly braces): {"x1","x2"},{"y1","y2"},{"z1","z2"} How can I transform this so that the i ...

What is the process for duplicating a group containing loaded .obj models?

Initially, I created a new THREE.Object3D() and named it groupChair. I then loaded 3 obj files and added them to groupChair within the callback function. After that, I added the groupChair to the scene and it worked perfectly. However, I encountered an iss ...

Chrome browser exhibits a phenomenon where the Bootstrap modal will erroneously print the same page multiple times based on the

When I open a modal, there's a print button inside it. I've researched solutions provided here and here to enable printing of Bootstrap modals, but I'm encountering a Chrome-specific bug. The issue doesn't occur in Safari, Firefox, or E ...

Tips for ensuring that the code inside a subscribe block completes before moving on to the next iteration within a forEach loop in Angular

Within the code snippet below, there exists a for loop where an API call is made. The intention is to have the 1st API call complete and execute all the subscribed code before moving on to the next iteration of the loop, triggering another API call. Curre ...

What action is initiated when the save button is clicked in ckEditor?

Incorporating a ckeditor editor into my asp.net application has been successful. At this point, I am looking to identify the event that is fired by ckeditor when the save button in the toolbar is clicked. Has anyone come across this information? ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman ...

Incorporating a pre-loaded database into a jQuery Mobile Phonegap app

After developing a native iPhone app that utilized an SQLite database with thousands of rows, I am now facing the task of creating an Android app using Phonegap. While I have some knowledge in HTML, CSS, and JavaScript, I am fairly new to Phonegap and jQue ...

A guide on dynamically checking the checkbox values in each row of a table using JavaScript or jQuery

My table is dynamically populated with values from a database using the following code: var row = table.insertRow(i); i = i+1; // Insert new cells (<td> elements) at the 1st and 2nd position of the new <tr> element: var cell1 = row.insertCell ...

Tips on retrieving and sending an XML string in PHP to JavaScript using MySQL

Here is the code snippet I have: <input type='button' value='clickme' onclick='download(\"\" . $rowtable['Protocolo'] . \".xml\", \"\" . $rowtable['XML&a ...

Is it possible to create a single button that, upon clicking, fades in one image while simultaneously fading out another?

My goal is to have the blue square fade in on the first button click, then fade out while the red square fades in on the second click. Unfortunately, it seems that my current code is not achieving this effect. I'm open to any suggestions or help on h ...

The method beforeEach in angular2/testing seems to be failing as it is not

Currently, I am utilizing Gulp, Gulp-Jasmine, and SystemJS to conduct tests on an Angular2 demo application. The setup is fairly straightforward. I have successfully implemented a System.config block and loaded the spec file. However, I encounter an error ...

Tips for managing your time while anticipating an observable that may or may not

I am facing a dilemma in my Angular app where I need to conditionally make an HTTP call to check for the existence of a user. Depending on the result of this call, I may need to either proceed with another API request or halt the processing altogether. I ...

Change the location of an html td element with JavaScript

I am currently working on a simple JavaScript car racing game where the cars are represented by HTML table elements. I want to implement functionality where pressing the "e" key moves player one's car and the "d" key moves player two's car. This ...

Playing back an Audio object using JavaScript

I'm facing an issue with replaying an audio sound every time the game starts in my Cocos2d javascript code. The sound plays correctly the first time, but subsequent attempts to play it result in no sound being heard. Below is my code snippet: var my ...

Can I use jQuery to fetch a PHP variable?

Is there a way to extract a PHP variable from jQuery? Let's say I am using the jQuery POST function like this: $.post("login.php", {username:username, password:password}, function(data){ $('section').html(data); }); Rather than displa ...

Tips for sending a structured search query to the findOne() function in MongoDB with Node.js

I have a Restful service built with node.js that takes user input to create a query string for MongoDB. However, whenever I try to pass this query to findone() in MongoDb and call the service, it displays a "query selector must be an object" message in the ...

There was an error thrown: [vuex] getters must be defined as a function, however, the getter "getters.default" is an empty

After building my VUE project for production with NPM, I encountered an error in the console. Can anyone shed some light on why vuex is presenting this complaint? npm 3.10 , node.js 8.11 Uncaught Error: [vuex] getters should be function but "getters.defau ...

Creating a PHP proxy to retrieve and parse cross domain XML data using jQuery

Ever since Google's feed load service was disabled, I have been facing difficulties in finding a new method to showcase xml feeds across various protocols and domains. My goal is to integrate a blog onto a website where the website is secure (https) b ...

Injecting CSS styles into the head tag dynamically with jQuery from within the body of a

When it comes to adding CSS to the head of an HTML page from the body using JavaScript and jQuery, I have come across two methods. One involves using jQuery to directly append the CSS to the head, while the other method involves creating a style element an ...