jQuery UI's $(...).sortable function is throwing an error when being used with WebPack

After setting up everything correctly, I encountered an unusual issue with Webpack.

Let's take a look at this simple app.ts file:

'use strict';

import $ = require('jquery');
import 'jquery-ui';

$(function() {
    $( "#sortable" ).sortable();
});

Although the code compiles without errors, running the site generates the message "Uncaught TypeError: $(...).sortable is not a function". (Note that sortable is a jQuery UI function).

Interestingly, everything works fine when I switch to linking to CDN-hosted versions of jQuery and jQuery UI. However, using JS modules and Webpack leads to the aforementioned error. Any idea on why this occurs?

What could be the reason behind the unrecognized jQueryUI function sortable()?

Answer â„–1

The issue arises when using jQuery UI with Webpack, as it does not automatically include the necessary components like when linked via a CDN. However, starting from version 1.11 of jQuery UI, you can manually import additional components as needed:

'use strict';

import $ = require('jquery');

require('jquery-ui');
require('jquery-ui/ui/widgets/sortable');
require('jquery-ui/ui/disable-selection');

For more information on this, refer to the official documentation.

Answer â„–2

the ES6 import syntax is incorrect, and even if it was correct, the code still wouldn't work. sortable is not recognized because $ is not available within the jquery-ui module.

This solution is not optimized as it imports the entire jquery-ui library.

npm install --save jquery-ui-bundle

index.js

'use strict';

import 'jquery-ui-bundle';

$(function() {
    $( "#sortable" ).sortable();
});

webpack

plugins: [
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        'window.$': 'jquery'
    })
]

Answer â„–3

This summary serves to combine the insights from two valuable answers: Answer 1, Answer 2

It's important to note that jquery-ui-dist and jquery-ui-bundle are not actively maintained by the jquery-ui team, so it's advisable to steer clear of them. However, starting from jquery-ui version 1.11, you can utilize AMD for require/import, and from version 1.12, you have the option to use the official package via npm.

Solution 1 :
The recommended approach is to import specific parts of jquery-ui like this:

import 'jquery-ui/ui/widgets/draggable';

An alternative is having to individually import modules you require, instead of using import 'jquery-ui', which will only bundle the necessary imports.

Refer to the 1.11 AMD support documentation and 1.12 npm documentation on their website for more details.

Solution 2 :
For those who prefer a single global import of jquery-ui, adjustments to the webpack configuration are required:

Firstly, ensure webpack recognizes the jquery aliases:

...
plugins: [
    new webpack.ProvidePlugin({
      '$':'jquery',
      'jQuery':'jquery',
      'window.jQuery':'jquery',
      'global.jQuery': 'jquery'
    }),
...

Then assist webpack in resolving the location of the jquery-ui JS file:

resolve : {
    alias: {
      "jquery-ui": "jquery-ui/jquery-ui.js",      
      modules: path.join(__dirname, "node_modules"),

Additionally, make sure jquery-ui is loaded early on, perhaps during startup:

var $ = require("jquery"),
        require("jquery-ui");

If utilizing a jquery-ui theme, configure the css-loader and file-loader accordingly (and don't forget to install these loaders):

module: {
    loaders: [
      { test: /\.css$/, loader: "style!css" },
      { test: /\.(jpe?g|png|gif)$/i, loader:"file" },

Finally, after your imports of jquery and jquery-ui, remember to include:

import 'modules/jquery-ui/themes/black-tie/jquery-ui.css';
import 'modules/jquery-ui/themes/black-tie/jquery-ui.theme.css';

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

Javascript chart

Hello everyone, I am diving into the world of fetch API. Currently, I am faced with a challenge where I need to generate the following list items: <li>Zimmerman, Paul</li> <li>Yimmerman, Raul</li> <li>Limmerman, Caul</li> ...

Ajax updates previous text to new text upon successfully completing the task

I have a question regarding changing text using AJAX after success. I have written this AJAX code which is functioning properly. However, I aim to replace the old text with new text in the .chnged div. For instance: <input type="text" name="text" va ...

Using JavaScript to display a line using `document.write`

I'm having trouble displaying a line using the Document.Write function in JavaScript. When I submit the form, the line briefly appears and then disappears Any ideas on why this might be happening? <!DOCTYPE html> <html> <head& ...

Refreshing CSS-Element-Queries following an ajax request

I’ve been utilizing css-element-queries from the https://github.com/marcj/css-element-queries repository to tailor styles based on an element's dimensions. However, I encountered an issue when dynamically adding elements via ajax calls. The new elem ...

Purge command in Grunt does not output any files for CSS

My code snippet in the gruntfile.js looks like this: // Css Purge css_purge: { options: { "verbose": false, "no_duplicate_property": true, }, files: { src: 'css/bigfile.css', dest: 'css/purged.css' }, } I decided to test the big ...

Error is thrown when attempting to access nested elements using GetElementsByClassName within the window.onload function

I have a funky looking table on my webpage, here's an example: <body> <table class="table table-bordered"> <thead> <tr> <th>#</th> <th>Product name</th> <th>Product ...

The error message "MVC JS deletethisproduct is not defined at HTMLAnchorElement.onclick (VM457 Index:40)" indicates that there

Upon clicking the button, I encounter this error: "deletethisproduct is not defined at HTMLAnchorElement.onclick" While I understand that using onclick is not the ideal approach, I am employing it because I need to retrieve the product id from the mode ...

The length of JSON data retrieved may vary between Internet Explorer and Firefox

After receiving JSON data from the server via AJAX, I proceeded to evaluate it as follows: request.responseText=[{name:xxx},{name:yyy},{name:zzz}]. I then used the following code snippet: var data=eval(request.responseText); alert(data.length); Surpri ...

In JavaScript, combine two arrays of equal length to create a new array object value

Trying to figure out how to merge two arrays into a new object in JavaScript var array1 = ['apple', 'banana', 'orange']; var array2 = ['red', 'yellow', 'orange']; If array1[0] is 'apple&apos ...

Create a regex pattern that can accurately extract email addresses from a comma-del

Currently, I have a regular expression that validates a single email address. How can I modify this regex to accept a list of email addresses separated by commas? ^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A- ...

Submit a data array using formData through axios

I am planning to send array data using formData. The backend is set up to accept the data array separated by a dash ; For example, if I were to use Postman and input the form-data like this: id_barang : 122;288;383 (sending 3 values of id with dashes ;) W ...

Extracting an ID value from a select box in Vue.js

I'm attempting to extract the value of idTipoExame from the following JSON: { "idTipoExame": "11", "mnemonico": "AUR", "exame": "ACIDO URICO" }, { "idTipoExame": "24&qu ...

How can I include environment variables in an npm package and make modifications to it within an Azure build pipeline?

I recently developed an npm package that connects to various APIs on the backend. The package currently has hardcoded URLs to access these APIs. However, we often find ourselves needing to update these URLs to point to a different API version, which result ...

Exploring AngularJS: Effiecient Looping and Styling

Being a beginner in AngularJS, please excuse me if this question seems silly. I want to display my data in a grid format (using Ionic) where each row has separate columns like this: <div class="row"> <div class="col-33">Item 1</div> ...

Retrieve and dynamically load an entire webpage using AJAX

Although it's typically not recommended, I am interested in displaying the progress of a download on a heavy page to show the user when it's ready. Is there a way for me to track and display the actual progress of the download? Can I monitor how ...

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

What factors might cause varying WebGL extension availability?

When I analyze my code, I am checking for available WebGL extensions. console.log(GL.getSupportedExtensions()); This results in an array containing 9 extensions. https://i.sstatic.net/5sTcX.png However, upon inspecting my extensions on a platform like ...

What is the best way to access a video stored in a local file on the initial page and then watch it on the subsequent

I recently encountered a scenario where I needed to select a video on one page and have it automatically play on another page without any redirection. The initial page displays a list of videos for selection, like this: FirstPage Once a video is chosen on ...

What could be the reason that step 3 of the AngularJS Tutorial is not functioning correctly?

During Step 3 of the AngularJS Tutorial, an additional e2e test is recommended to enhance the example: it('should display the current filter value within an element with id "status"', function() { expect(element('#status').text() ...

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...